agent-config 0.3.3

Install hooks/integrations into AI coding harnesses (Claude Code, Cursor, Gemini CLI, OpenCode, Codex CLI, Cline, Windsurf, ...) without learning each one's filesystem layout.
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
//! Hook spec, builder, and supporting types.
//!
//! Layout: this module is a directory split into `builder.rs` (the
//! [`HookSpecBuilder`] fluent API) and the rest of the spec types
//! ([`HookSpec`], [`HookCommand`], [`Matcher`], [`Event`], [`RulesBlock`],
//! [`ScriptTemplate`]) plus shared validators here. The flat re-exports
//! below match the parent `spec` module's expected surface.

use crate::error::AgentConfigError;

use super::validate::{validate_identifier, IdentifierKind};

mod builder;

pub use builder::HookSpecBuilder;

/// Optional execution configuration for command hooks.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct HookRuntimeOptions {
    /// Maximum time in seconds the harness should allow the hook script to run.
    pub timeout_seconds: Option<u64>,
    /// Optional status message the harness should display while executing the hook.
    pub status_message: Option<String>,
    /// Whether the hook should run asynchronously (non-blocking).
    pub async_run: Option<bool>,
    /// Custom shell path to use when executing the command (e.g. `"/bin/bash"`).
    pub shell: Option<String>,
    /// Windows-specific command override.
    pub windows_command: Option<HookCommand>,
    /// Codex-specific: install inline inside `config.toml` instead of `hooks.json`.
    pub codex_inline_toml: Option<bool>,
}

/// Everything an [`Integration`](crate::Integration) needs to install a hook.
///
/// Build via [`HookSpec::builder`]. For fallible construction see
/// [`HookSpecBuilder::try_build`].
#[derive(Debug, Clone)]
pub struct HookSpec {
    /// Unique identifier for *the consumer of this library*. Used to namespace
    /// fenced markdown blocks, JSON entries, and per-tag filenames so multiple
    /// CLIs can coexist without stomping each other. Must be ASCII alnum / `_`
    /// / `-`, non-empty.
    pub tag: String,

    /// The command the harness should execute.
    ///
    /// Use [`HookSpecBuilder::command_program`] for the safe default. Raw shell
    /// remains available through [`HookSpecBuilder::command_shell_unchecked`]
    /// for callers that intentionally need shell syntax.
    pub command: HookCommand,

    /// Which tool calls the hook should match.
    pub matcher: Matcher,

    /// Which lifecycle event to attach to.
    pub event: Event,

    /// Optional markdown to inject into the harness's rules/memory file
    /// (e.g., `~/.claude/CLAUDE.md`, `./.clinerules`, `~/.gemini/GEMINI.md`).
    pub rules: Option<RulesBlock>,

    /// Optional script body for harnesses that delegate via a script file
    /// (currently Gemini's `~/.gemini/hooks/*.sh`) or a TS plugin
    /// (OpenCode, OpenClaw).
    pub script: Option<ScriptTemplate>,

    /// Optional human-friendly display name for log/UI output. If absent the
    /// integration's `display_name` is used.
    pub friendly_name: Option<String>,

    /// Optional execution options for command hooks.
    pub options: HookRuntimeOptions,
}

impl HookSpec {
    /// Start building a spec with the given consumer tag.
    pub fn builder(tag: impl Into<String>) -> HookSpecBuilder {
        HookSpecBuilder {
            tag: tag.into(),
            command: None,
            matcher: Matcher::All,
            event: Event::PreToolUse,
            rules: None,
            script: None,
            friendly_name: None,
            options: HookRuntimeOptions::default(),
        }
    }

    /// Validate that the tag is non-empty and contains only safe characters.
    pub(crate) fn validate_tag(tag: &str) -> Result<(), AgentConfigError> {
        validate_identifier(tag, IdentifierKind::Tag)
    }
}

/// Hook command representation.
///
/// [`HookCommand::Program`] is the safe default. It stores argv-like program
/// and argument values, then renders them with **POSIX shell quoting** (see
/// [`HookCommand::render_shell`]) for harnesses whose hook APIs only accept
/// strings. [`HookCommand::ShellUnchecked`] is an escape hatch for trusted
/// raw shell syntax — including the case where the target shell is not POSIX
/// (e.g. PowerShell on native Windows).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum HookCommand {
    /// A program plus arguments, rendered safely when a shell string is needed.
    Program {
        /// Executable name or path.
        program: String,
        /// Command arguments.
        args: Vec<String>,
    },
    /// Trusted raw shell syntax.
    ShellUnchecked {
        /// Shell command passed through without quoting or escaping.
        command: String,
    },
}

impl HookCommand {
    /// Construct a safe program command.
    pub fn program<I, S>(program: impl Into<String>, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self::Program {
            program: program.into(),
            args: args.into_iter().map(Into::into).collect(),
        }
    }

    /// Construct an unchecked raw shell command.
    pub fn shell_unchecked(command: impl Into<String>) -> Self {
        Self::ShellUnchecked {
            command: command.into(),
        }
    }

    /// Render the command for harnesses whose hook contract accepts a shell
    /// command string.
    ///
    /// The output is **POSIX-shell quoted**: arguments are escaped using
    /// single-quote rules suitable for `sh`/`bash`. It is not safe for
    /// `cmd.exe` or PowerShell; on native Windows, callers targeting a
    /// non-POSIX shell should construct [`HookCommand::ShellUnchecked`] and
    /// quote the command themselves.
    ///
    /// Integrations that store the rendered string in a JSON or YAML field
    /// (Copilot's `bash` field, Windsurf's `bash`, Gemini's `command`, etc.)
    /// inherit POSIX semantics through this method. A platform-aware shell
    /// abstraction (`ShellKind`/PowerShell quoting) is intentionally
    /// deferred; see the project README for the supported-platforms model.
    pub fn render_shell(&self) -> String {
        match self {
            Self::Program { program, args } => std::iter::once(program.as_str())
                .chain(args.iter().map(String::as_str))
                .map(shell_quote)
                .collect::<Vec<_>>()
                .join(" "),
            Self::ShellUnchecked { command } => command.clone(),
        }
    }

    pub(super) fn validate(&self) -> Result<(), AgentConfigError> {
        match self {
            Self::Program { program, args } => {
                if program.is_empty() {
                    return Err(AgentConfigError::InvalidCommand {
                        reason: "program must not be empty",
                    });
                }
                validate_no_nul(program)?;
                for arg in args {
                    validate_no_nul(arg)?;
                }
            }
            Self::ShellUnchecked { command } => {
                if command.trim().is_empty() {
                    return Err(AgentConfigError::InvalidCommand {
                        reason: "shell command must not be empty",
                    });
                }
                validate_no_nul(command)?;
            }
        }
        Ok(())
    }
}

fn validate_no_nul(value: &str) -> Result<(), AgentConfigError> {
    if value.contains('\0') {
        return Err(AgentConfigError::InvalidCommand {
            reason: "command values must not contain NUL bytes",
        });
    }
    Ok(())
}

#[derive(Copy, Clone)]
pub(super) enum HookStringKind {
    Matcher,
    CustomEvent,
}

impl HookStringKind {
    fn empty_reason(self) -> &'static str {
        match self {
            Self::Matcher => "matcher value must not be empty",
            Self::CustomEvent => "custom event name must not be empty",
        }
    }

    fn control_reason(self) -> &'static str {
        match self {
            Self::Matcher => "matcher value must not contain control characters",
            Self::CustomEvent => "custom event name must not contain control characters",
        }
    }
}

pub(super) fn validate_hook_string(
    value: &str,
    kind: HookStringKind,
) -> Result<(), AgentConfigError> {
    if value.is_empty() {
        return Err(AgentConfigError::InvalidTag {
            tag: value.to_string(),
            reason: kind.empty_reason(),
        });
    }
    if value.chars().any(|c| (c as u32) < 0x20 || c == '\u{007F}') {
        return Err(AgentConfigError::InvalidTag {
            tag: value.to_string(),
            reason: kind.control_reason(),
        });
    }
    Ok(())
}

fn shell_quote(value: &str) -> String {
    if value.is_empty() {
        return "''".to_string();
    }
    if value
        .bytes()
        .all(|b| matches!(b, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'_' | b'-' | b'.' | b'/' | b':' | b'@' | b'%' | b'+' | b'=' | b','))
    {
        return value.to_string();
    }
    format!("'{}'", value.replace('\'', "'\\''"))
}

/// Which tool calls a hook should match.
///
/// Each integration translates this to its harness's native syntax. For
/// example, Claude Code accepts a regex when the matcher contains characters
/// outside `[A-Za-z0-9_|]`, so [`Matcher::Regex`] passes through verbatim.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Matcher {
    /// Match any tool call.
    All,
    /// Match the harness's "Bash"/"Shell"/"shell" tool (whatever it calls
    /// command execution). Each integration maps this to the right literal.
    Bash,
    /// Match exactly this tool name (e.g., `"Edit"`, `"Read"`).
    Exact(String),
    /// Match any of these tool names.
    AnyOf(Vec<String>),
    /// Match using the harness's regex syntax (passed through unchanged).
    Regex(String),
}

/// Lifecycle event to attach to. Each integration maps this to its harness's
/// own event name (e.g., `PreToolUse` on Claude Code, `BeforeTool` on Gemini,
/// `tool.execute.before` on OpenCode).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Event {
    /// Fire before a tool call is executed (the most common case; lets the
    /// hook modify or block the call).
    PreToolUse,
    /// Fire after a tool call completes.
    PostToolUse,

    /// Hook fires when a notification event is dispatched.
    Notification,
    /// Hook fires when user submits a prompt.
    UserPromptSubmit,
    /// Hook fires when the agent stops.
    Stop,
    /// Hook fires when a subagent stops.
    SubagentStop,
    /// Hook fires before message compaction.
    PreCompact,
    /// Hook fires when a session starts.
    SessionStart,
    /// Hook fires when a session ends.
    SessionEnd,
    /// Hook fires when a permission request is initiated.
    PermissionRequest,
    /// Hook fires when a permission is denied.
    PermissionDenied,
    /// Hook fires when configuration changes.
    ConfigChange,
    /// Hook fires when a file is changed.
    FileChanged,
    /// Hook fires when instructions are loaded.
    InstructionsLoaded,

    /// Pass through a custom event name verbatim.
    Custom(String),
}

impl Event {
    /// Return the canonical string representation of the event.
    pub fn as_str(&self) -> &str {
        match self {
            Event::PreToolUse => "PreToolUse",
            Event::PostToolUse => "PostToolUse",
            Event::Notification => "Notification",
            Event::UserPromptSubmit => "UserPromptSubmit",
            Event::Stop => "Stop",
            Event::SubagentStop => "SubagentStop",
            Event::PreCompact => "PreCompact",
            Event::SessionStart => "SessionStart",
            Event::SessionEnd => "SessionEnd",
            Event::PermissionRequest => "PermissionRequest",
            Event::PermissionDenied => "PermissionDenied",
            Event::ConfigChange => "ConfigChange",
            Event::FileChanged => "FileChanged",
            Event::InstructionsLoaded => "InstructionsLoaded",
            Event::Custom(s) => s.as_str(),
        }
    }
}

/// Markdown content to inject into the harness's memory/rules file, fenced by
/// HTML comments keyed on the [`HookSpec::tag`].
#[derive(Debug, Clone)]
pub struct RulesBlock {
    /// Raw markdown body (no fences — they are added by the library).
    pub content: String,
}

/// Optional script body for harnesses that need a shell script or TS plugin.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ScriptTemplate {
    /// POSIX shell script body. The library adds the shebang if absent and
    /// chmods the file `0755`. A SHA-256 sidecar is written for harnesses
    /// (Gemini) that verify integrity.
    Shell(String),
    /// TypeScript plugin body for OpenCode / OpenClaw.
    TypeScript(String),
}

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

    #[test]
    fn try_build_rejects_empty_tag() {
        let err = HookSpec::builder("")
            .command_program("x", [] as [&str; 0])
            .try_build()
            .unwrap_err();
        assert!(
            matches!(err, AgentConfigError::InvalidTag { reason, .. } if reason == "tag must not be empty")
        );
    }

    #[test]
    fn try_build_rejects_tag_with_spaces() {
        let err = HookSpec::builder("not valid")
            .command_program("x", [] as [&str; 0])
            .try_build()
            .unwrap_err();
        assert!(
            matches!(err, AgentConfigError::InvalidTag { reason, .. } if reason.contains("ASCII"))
        );
    }

    #[test]
    fn try_build_rejects_tag_with_special_chars() {
        for bad in ["tag/slash", "tag.dot", "tag!bang", "tag@at"] {
            let err = HookSpec::builder(bad)
                .command_program("x", [] as [&str; 0])
                .try_build()
                .unwrap_err();
            assert!(
                matches!(err, AgentConfigError::InvalidTag { .. }),
                "expected InvalidTag for {bad:?}"
            );
        }
    }

    #[test]
    fn try_build_accepts_valid_tags() {
        for ok in ["myapp", "my-app", "my_app", "App123", "A", "z9_z"] {
            HookSpec::builder(ok)
                .command_program("x", [] as [&str; 0])
                .try_build()
                .expect("expected valid tag");
        }
    }

    #[test]
    fn try_build_rejects_missing_command() {
        let err = HookSpec::builder("ok").try_build().unwrap_err();
        assert!(
            matches!(err, AgentConfigError::MissingSpecField { field, .. } if field == "command")
        );
    }

    #[test]
    fn build_panics_on_missing_command() {
        let result = std::panic::catch_unwind(|| {
            HookSpec::builder("ok").build();
        });
        assert!(result.is_err());
    }

    #[test]
    fn builder_sets_all_fields() {
        let spec = HookSpec::builder("myapp")
            .command_program("run", ["--flag"])
            .matcher(Matcher::Bash)
            .event(Event::PostToolUse)
            .rules("my rules")
            .script(ScriptTemplate::Shell("set -e".into()))
            .friendly_name("My App")
            .build();

        assert_eq!(spec.tag, "myapp");
        assert_eq!(
            spec.command,
            HookCommand::Program {
                program: "run".into(),
                args: vec!["--flag".into()]
            }
        );
        assert!(matches!(spec.matcher, Matcher::Bash));
        assert!(matches!(spec.event, Event::PostToolUse));
        assert!(spec.rules.is_some());
        assert!(spec.script.is_some());
        assert_eq!(spec.friendly_name.as_deref(), Some("My App"));
    }

    #[test]
    fn builder_defaults() {
        let spec = HookSpec::builder("myapp")
            .command_program("run", [] as [&str; 0])
            .build();

        assert!(matches!(spec.matcher, Matcher::All));
        assert!(matches!(spec.event, Event::PreToolUse));
        assert!(spec.rules.is_none());
        assert!(spec.script.is_none());
        assert!(spec.friendly_name.is_none());
    }

    #[test]
    fn program_command_renders_shell_safe_arguments() {
        let command = HookCommand::program(
            "my hook",
            [
                "repo path",
                "semi;colon",
                "$(not run)",
                "`not run`",
                "line\nbreak",
                "quote's",
                "",
            ],
        );
        assert_eq!(
            command.render_shell(),
            "'my hook' 'repo path' 'semi;colon' '$(not run)' '`not run`' 'line\nbreak' 'quote'\\''s' ''"
        );
    }

    #[test]
    fn raw_shell_command_is_explicitly_unchecked() {
        let spec = HookSpec::builder("myapp")
            .command_shell_unchecked("myapp hook \"$REPO\"")
            .build();
        assert_eq!(spec.command.render_shell(), "myapp hook \"$REPO\"");
    }

    #[test]
    fn try_build_rejects_invalid_command_values() {
        let empty_program = HookSpec::builder("myapp")
            .command_program("", [] as [&str; 0])
            .try_build()
            .unwrap_err();
        assert!(matches!(
            empty_program,
            AgentConfigError::InvalidCommand { .. }
        ));

        let nul_arg = HookSpec::builder("myapp")
            .command_program("myapp", ["bad\0arg"])
            .try_build()
            .unwrap_err();
        assert!(matches!(nul_arg, AgentConfigError::InvalidCommand { .. }));

        let empty_shell = HookSpec::builder("myapp")
            .command_shell_unchecked(" ")
            .try_build()
            .unwrap_err();
        assert!(matches!(
            empty_shell,
            AgentConfigError::InvalidCommand { .. }
        ));
    }

    #[test]
    fn try_build_rejects_empty_exact_matcher() {
        let err = HookSpec::builder("ok")
            .command_program("x", [] as [&str; 0])
            .matcher(Matcher::Exact(String::new()))
            .try_build()
            .unwrap_err();
        assert!(matches!(err, AgentConfigError::InvalidTag { .. }));
    }

    #[test]
    fn try_build_rejects_empty_anyof_matcher() {
        let err = HookSpec::builder("ok")
            .command_program("x", [] as [&str; 0])
            .matcher(Matcher::AnyOf(Vec::new()))
            .try_build()
            .unwrap_err();
        assert!(matches!(err, AgentConfigError::InvalidTag { .. }));
    }

    #[test]
    fn try_build_rejects_empty_string_in_anyof() {
        let err = HookSpec::builder("ok")
            .command_program("x", [] as [&str; 0])
            .matcher(Matcher::AnyOf(vec!["Edit".into(), String::new()]))
            .try_build()
            .unwrap_err();
        assert!(matches!(err, AgentConfigError::InvalidTag { .. }));
    }

    #[test]
    fn try_build_rejects_control_char_in_regex() {
        let err = HookSpec::builder("ok")
            .command_program("x", [] as [&str; 0])
            .matcher(Matcher::Regex("foo\u{0007}".into()))
            .try_build()
            .unwrap_err();
        assert!(matches!(err, AgentConfigError::InvalidTag { .. }));
    }

    #[test]
    fn try_build_rejects_empty_custom_event() {
        let err = HookSpec::builder("ok")
            .command_program("x", [] as [&str; 0])
            .event(Event::Custom(String::new()))
            .try_build()
            .unwrap_err();
        assert!(matches!(err, AgentConfigError::InvalidTag { .. }));
    }

    #[test]
    fn try_build_rejects_control_char_in_custom_event() {
        let err = HookSpec::builder("ok")
            .command_program("x", [] as [&str; 0])
            .event(Event::Custom("before\nShell".into()))
            .try_build()
            .unwrap_err();
        assert!(matches!(err, AgentConfigError::InvalidTag { .. }));
    }

    #[test]
    fn try_build_accepts_valid_custom_event_and_matcher() {
        HookSpec::builder("ok")
            .command_program("x", [] as [&str; 0])
            .event(Event::Custom("beforeShellExecution".into()))
            .matcher(Matcher::AnyOf(vec!["Edit".into(), "Read".into()]))
            .try_build()
            .expect("valid");
    }
}