coding-agent-hooks 0.7.2

Agent-agnostic hook protocol types and adapters for AI coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//! Multi-agent support — agent identification, tool name normalization, and
//! protocol implementations.
//!
//! This module provides:
//!
//! - [`AgentKind`] — enum identifying each supported agent
//! - Canonical tool alias table — maps agent-native tool names to internal names
//! - Permission mode resolution — normalizes agent-specific mode strings
//! - Per-agent [`HookProtocol`](crate::protocol::HookProtocol) implementations

pub mod amazonq;
pub mod claude;
pub mod codex;
pub mod copilot;
pub mod gemini;
pub mod opencode;

use std::fmt;
use std::str::FromStr;

/// Identifies which coding agent is calling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
pub enum AgentKind {
    Claude,
    Gemini,
    Codex,
    #[cfg_attr(feature = "clap", value(name = "amazonq"))]
    AmazonQ,
    #[cfg_attr(feature = "clap", value(name = "opencode"))]
    OpenCode,
    Copilot,
}

impl fmt::Display for AgentKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AgentKind::Claude => write!(f, "claude"),
            AgentKind::Gemini => write!(f, "gemini"),
            AgentKind::Codex => write!(f, "codex"),
            AgentKind::AmazonQ => write!(f, "amazonq"),
            AgentKind::OpenCode => write!(f, "opencode"),
            AgentKind::Copilot => write!(f, "copilot"),
        }
    }
}

impl FromStr for AgentKind {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "claude" => Ok(AgentKind::Claude),
            "gemini" => Ok(AgentKind::Gemini),
            "codex" => Ok(AgentKind::Codex),
            "amazonq" | "amazon-q" | "amazon_q" => Ok(AgentKind::AmazonQ),
            "opencode" | "open-code" => Ok(AgentKind::OpenCode),
            "copilot" => Ok(AgentKind::Copilot),
            _ => Err(format!("unknown agent: {s}")),
        }
    }
}

// ---------------------------------------------------------------------------
// Canonical permission mode table
// ---------------------------------------------------------------------------

/// Maps agent-specific permission mode strings to canonical modes.
///
/// Canonical modes: "default", "plan", "edit", "unrestricted".
/// Unknown modes pass through as-is so agent-specific extensions still work.
struct ModeAlias {
    canonical: &'static str,
    agent_names: &'static [(AgentKind, &'static str)],
}

const MODE_ALIASES: &[ModeAlias] = &[
    ModeAlias {
        canonical: "default",
        agent_names: &[(AgentKind::Claude, "default")],
    },
    ModeAlias {
        canonical: "plan",
        agent_names: &[(AgentKind::Claude, "plan")],
    },
    ModeAlias {
        canonical: "edit",
        agent_names: &[(AgentKind::Claude, "edit")],
    },
    ModeAlias {
        canonical: "unrestricted",
        agent_names: &[(AgentKind::Claude, "dangerously_skip_permissions")],
    },
];

/// Given an agent's native permission mode string, return the canonical mode.
///
/// Case-insensitive. Returns the original string unchanged if no mapping exists.
pub fn resolve_permission_mode<'a>(agent: AgentKind, native_mode: &'a str) -> &'a str {
    let lower = native_mode.to_lowercase();
    for alias in MODE_ALIASES {
        for &(a, name) in alias.agent_names {
            if a == agent && name.to_lowercase() == lower {
                return alias.canonical;
            }
        }
    }
    native_mode
}

// ---------------------------------------------------------------------------
// Canonical tool alias table
// ---------------------------------------------------------------------------

/// Maps a canonical name and agent-native names to a single internal name.
///
/// Internal names use Claude Code's tool names (e.g. "Bash", "Read") since
/// they are already embedded throughout policy engines and permission logic.
struct ToolAlias {
    /// User-facing canonical name (e.g. "shell", "read").
    canonical: &'static str,
    /// Internal name used by the policy engine (Claude-style, e.g. "Bash").
    internal: &'static str,
    /// Agent-specific native names that map to this tool.
    agent_names: &'static [(AgentKind, &'static str)],
}

/// The ONE source of truth for tool name mappings across all agents.
///
/// Each entry is curated case-by-case. Tools that don't have a clean
/// cross-agent equivalent are NOT in this table — they stay agent-specific.
const TOOL_ALIASES: &[ToolAlias] = &[
    ToolAlias {
        canonical: "shell",
        internal: "Bash",
        agent_names: &[
            (AgentKind::Claude, "Bash"),
            (AgentKind::Gemini, "run_shell_command"),
            (AgentKind::Codex, "shell"),
            (AgentKind::AmazonQ, "execute_bash"),
            (AgentKind::OpenCode, "bash"),
            (AgentKind::Copilot, "bash"),
        ],
    },
    ToolAlias {
        canonical: "read",
        internal: "Read",
        agent_names: &[
            (AgentKind::Claude, "Read"),
            (AgentKind::Gemini, "read_file"),
            (AgentKind::AmazonQ, "fs_read"),
            (AgentKind::OpenCode, "read"),
            (AgentKind::Copilot, "view"),
        ],
    },
    ToolAlias {
        canonical: "write",
        internal: "Write",
        agent_names: &[
            (AgentKind::Claude, "Write"),
            (AgentKind::Gemini, "write_file"),
            (AgentKind::AmazonQ, "fs_write"),
            (AgentKind::OpenCode, "write"),
        ],
    },
    ToolAlias {
        canonical: "edit",
        internal: "Edit",
        agent_names: &[
            (AgentKind::Claude, "Edit"),
            (AgentKind::Gemini, "replace"),
            (AgentKind::OpenCode, "edit"),
            (AgentKind::Copilot, "edit"),
        ],
    },
    ToolAlias {
        canonical: "glob",
        internal: "Glob",
        agent_names: &[
            (AgentKind::Claude, "Glob"),
            (AgentKind::Gemini, "glob"),
            (AgentKind::OpenCode, "glob"),
        ],
    },
    ToolAlias {
        canonical: "grep",
        internal: "Grep",
        agent_names: &[
            (AgentKind::Claude, "Grep"),
            (AgentKind::Gemini, "grep_search"),
            (AgentKind::OpenCode, "grep"),
        ],
    },
    ToolAlias {
        canonical: "web_fetch",
        internal: "WebFetch",
        agent_names: &[
            (AgentKind::Claude, "WebFetch"),
            (AgentKind::Gemini, "web_fetch"),
            (AgentKind::OpenCode, "webfetch"),
        ],
    },
    ToolAlias {
        canonical: "web_search",
        internal: "WebSearch",
        agent_names: &[
            (AgentKind::Claude, "WebSearch"),
            (AgentKind::Gemini, "google_web_search"),
            (AgentKind::Codex, "web_search"),
            (AgentKind::OpenCode, "websearch"),
        ],
    },
];

/// Given an agent's native tool name, return the internal (Claude-style) name.
///
/// Case-insensitive. Returns the original name unchanged if no mapping exists
/// (unknown/agent-specific tools pass through as-is).
pub fn resolve_tool_name(agent: AgentKind, native_name: &str) -> &str {
    let lower = native_name.to_lowercase();
    for alias in TOOL_ALIASES {
        for &(a, name) in alias.agent_names {
            if a == agent && name.to_lowercase() == lower {
                return alias.internal;
            }
        }
    }
    native_name
}

/// Given a canonical name (e.g. "shell"), return the internal name (e.g. "Bash").
///
/// Case-insensitive. Used by the policy compiler to resolve user-facing aliases.
pub fn canonical_to_internal(clash_name: &str) -> Option<&'static str> {
    let lower = clash_name.to_lowercase();
    TOOL_ALIASES
        .iter()
        .find(|a| a.canonical.to_lowercase() == lower)
        .map(|a| a.internal)
}

/// Resolve any tool name to its internal form.
///
/// Accepts canonical names ("shell"), internal names ("Bash"), or any
/// agent-native name ("run_shell_command"). Case-insensitive.
/// Returns the internal name if found, or None if unrecognized.
pub fn resolve_any_to_internal(name: &str) -> Option<&'static str> {
    let lower = name.to_lowercase();
    for alias in TOOL_ALIASES {
        if alias.canonical.to_lowercase() == lower {
            return Some(alias.internal);
        }
        if alias.internal.to_lowercase() == lower {
            return Some(alias.internal);
        }
        for &(_, agent_name) in alias.agent_names {
            if agent_name.to_lowercase() == lower {
                return Some(alias.internal);
            }
        }
    }
    None
}

/// Given an internal name (e.g. "Bash"), return the canonical name (e.g. "shell").
///
/// Case-insensitive.
pub fn internal_to_canonical(internal_name: &str) -> Option<&'static str> {
    let lower = internal_name.to_lowercase();
    TOOL_ALIASES
        .iter()
        .find(|a| a.internal.to_lowercase() == lower)
        .map(|a| a.canonical)
}

/// Return the best user-facing display name for a tool.
///
/// Prefers the canonical name ("shell") if one exists, otherwise returns
/// the internal name as-is.
pub fn display_name(internal_name: &str) -> &str {
    internal_to_canonical(internal_name).unwrap_or(internal_name)
}

/// Given an internal name and target agent, return the agent's native tool name.
///
/// Used for formatting output in the agent's expected vocabulary.
pub fn internal_to_agent(agent: AgentKind, internal_name: &str) -> Option<&'static str> {
    let lower = internal_name.to_lowercase();
    for alias in TOOL_ALIASES {
        if alias.internal.to_lowercase() == lower {
            for &(a, name) in alias.agent_names {
                if a == agent {
                    return Some(name);
                }
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resolve_claude_bash() {
        assert_eq!(resolve_tool_name(AgentKind::Claude, "Bash"), "Bash");
    }

    #[test]
    fn resolve_gemini_shell() {
        assert_eq!(
            resolve_tool_name(AgentKind::Gemini, "run_shell_command"),
            "Bash"
        );
    }

    #[test]
    fn resolve_codex_shell() {
        assert_eq!(resolve_tool_name(AgentKind::Codex, "shell"), "Bash");
    }

    #[test]
    fn resolve_amazonq_bash() {
        assert_eq!(
            resolve_tool_name(AgentKind::AmazonQ, "execute_bash"),
            "Bash"
        );
    }

    #[test]
    fn resolve_case_insensitive() {
        assert_eq!(resolve_tool_name(AgentKind::Claude, "bash"), "Bash");
        assert_eq!(resolve_tool_name(AgentKind::Claude, "BASH"), "Bash");
        assert_eq!(
            resolve_tool_name(AgentKind::Gemini, "RUN_SHELL_COMMAND"),
            "Bash"
        );
    }

    #[test]
    fn resolve_unknown_passthrough() {
        assert_eq!(
            resolve_tool_name(AgentKind::Claude, "SomeCustomTool"),
            "SomeCustomTool"
        );
    }

    #[test]
    fn canonical_to_internal_works() {
        assert_eq!(canonical_to_internal("shell"), Some("Bash"));
        assert_eq!(canonical_to_internal("read"), Some("Read"));
        assert_eq!(canonical_to_internal("SHELL"), Some("Bash"));
        assert_eq!(canonical_to_internal("unknown"), None);
    }

    #[test]
    fn internal_to_canonical_works() {
        assert_eq!(internal_to_canonical("Bash"), Some("shell"));
        assert_eq!(internal_to_canonical("Read"), Some("read"));
        assert_eq!(internal_to_canonical("UnknownTool"), None);
    }

    #[test]
    fn internal_to_agent_works() {
        assert_eq!(
            internal_to_agent(AgentKind::Gemini, "Bash"),
            Some("run_shell_command")
        );
        assert_eq!(
            internal_to_agent(AgentKind::AmazonQ, "Read"),
            Some("fs_read")
        );
        assert_eq!(internal_to_agent(AgentKind::Codex, "Glob"), None);
    }

    #[test]
    fn resolve_any_canonical() {
        assert_eq!(resolve_any_to_internal("shell"), Some("Bash"));
        assert_eq!(resolve_any_to_internal("read"), Some("Read"));
    }

    #[test]
    fn resolve_any_internal() {
        assert_eq!(resolve_any_to_internal("Bash"), Some("Bash"));
        assert_eq!(resolve_any_to_internal("bash"), Some("Bash"));
        assert_eq!(resolve_any_to_internal("BASH"), Some("Bash"));
    }

    #[test]
    fn resolve_any_agent_native() {
        assert_eq!(resolve_any_to_internal("run_shell_command"), Some("Bash"));
        assert_eq!(resolve_any_to_internal("execute_bash"), Some("Bash"));
        assert_eq!(resolve_any_to_internal("fs_read"), Some("Read"));
    }

    #[test]
    fn resolve_any_unknown() {
        assert_eq!(resolve_any_to_internal("CustomTool"), None);
    }

    #[test]
    fn resolve_mode_claude_default() {
        assert_eq!(
            resolve_permission_mode(AgentKind::Claude, "default"),
            "default"
        );
    }

    #[test]
    fn resolve_mode_claude_plan() {
        assert_eq!(resolve_permission_mode(AgentKind::Claude, "plan"), "plan");
    }

    #[test]
    fn resolve_mode_claude_dangerously_skip() {
        assert_eq!(
            resolve_permission_mode(AgentKind::Claude, "dangerously_skip_permissions"),
            "unrestricted"
        );
    }

    #[test]
    fn resolve_mode_case_insensitive() {
        assert_eq!(
            resolve_permission_mode(AgentKind::Claude, "DANGEROUSLY_SKIP_PERMISSIONS"),
            "unrestricted"
        );
    }

    #[test]
    fn resolve_mode_unknown_passthrough() {
        assert_eq!(
            resolve_permission_mode(AgentKind::Claude, "custom_mode"),
            "custom_mode"
        );
    }

    #[test]
    fn resolve_mode_other_agents_default() {
        assert_eq!(
            resolve_permission_mode(AgentKind::Gemini, "default"),
            "default"
        );
        assert_eq!(
            resolve_permission_mode(AgentKind::Codex, "default"),
            "default"
        );
    }

    #[test]
    fn all_aliases_have_consistent_internal_names() {
        let claude_names: Vec<&str> = TOOL_ALIASES
            .iter()
            .flat_map(|a| {
                a.agent_names
                    .iter()
                    .filter(|(ak, _)| *ak == AgentKind::Claude)
            })
            .map(|(_, name)| *name)
            .collect();
        for alias in TOOL_ALIASES {
            assert!(
                claude_names.contains(&alias.internal),
                "internal name '{}' for canonical '{}' is not a Claude tool name",
                alias.internal,
                alias.canonical
            );
        }
    }
}