Skip to main content

kintsugi_intercept/
hook.rs

1//! Agent-CLI hook adapter.
2//!
3//! Many AI coding CLIs can run a command before they execute a tool, hand it a
4//! JSON description of the call, and read a decision back. This adapter bridges
5//! that payload to a [`ProposedCommand`], asks the daemon, and maps the
6//! [`Verdict`] to the CLI's decision protocol.
7//!
8//! The per-CLI wire formats live in [`crate::dialect`]; this module owns the
9//! shared *policy*: the daemon round-trip, the fail-closed-catastrophic
10//! backstop, and the Allow/Deny/Hold → decision mapping. Selecting a dialect is
11//! one `--agent <id>` flag, so a single `kintsugi-hook` binary serves every CLI.
12//!
13//! Fail-open: a malformed payload, a non-shell tool, or an unreachable daemon
14//! never blocks the agent — *except* a catastrophic command with the daemon
15//! down (denied fail-closed), or when `KINTSUGI_FAIL_CLOSED=1`.
16
17use std::path::Path;
18
19use kintsugi_core::{shell, Class, Decision, ObservedIngest, ProposedCommand};
20use kintsugi_daemon::Client;
21
22pub use crate::dialect::HookOutcome;
23
24use crate::dialect::{self, Dialect, Parsed, Resolved};
25use crate::observe;
26
27/// Handle one hook payload for a given dialect, performing the daemon round-trip.
28pub fn handle_with(dialect: Dialect, input: &str) -> HookOutcome {
29    let parsed = match dialect.parse(input) {
30        Parsed::Shell(s) => s,
31        Parsed::NotShell => {
32            // Not a shell tool — but it may be a content-ingesting one (a web
33            // fetch, search, MCP call, out-of-workspace read). Observe it for
34            // provenance taint, then pass: observation only labels, never blocks.
35            observe_content_call(dialect, input);
36            return HookOutcome::silent();
37        }
38        Parsed::Bad(e) => {
39            // Never block the agent on a payload we couldn't parse.
40            eprintln!(
41                "kintsugi-hook: could not parse {} payload: {e}",
42                dialect.agent_id()
43            );
44            return HookOutcome::silent();
45        }
46    };
47
48    let argv = shell::split(&parsed.command);
49    let session = parsed.session_id.clone();
50    let cwd = parsed.cwd.clone();
51    let proposed =
52        ProposedCommand::new(dialect.agent_id(), parsed.cwd, argv.clone(), parsed.command)
53            .with_session(parsed.session_id);
54
55    match Client::send(&proposed) {
56        Ok(verdict) => {
57            let resolved = match dialect::resolve(&verdict) {
58                // A catastrophic command is held in Kintsugi's queue but denied to
59                // the agent: an in-agent "allow" would run it with no snapshot,
60                // voiding reversibility. The agent can't offer that approval, so
61                // tell the human where it lives — otherwise the agent just sees a
62                // bare deny and silently works around it.
63                Resolved::Deny(reason)
64                    if verdict.decision == Decision::Hold
65                        && verdict.class == Class::Catastrophic =>
66                {
67                    Resolved::Deny(held_for_approval(&reason, &proposed.id.to_string()))
68                }
69                other => other,
70            };
71            let outcome = dialect.format(&resolved);
72            // A shell command that fetches remote content (`curl`/`wget`/`git
73            // clone`) taints the session for FUTURE commands. Observe it only when
74            // it will actually run (Allow) and AFTER the verdict — so the fetch is
75            // judged against prior state and isn't tripped by its own taint.
76            if matches!(resolved, Resolved::Allow) {
77                observe_shell_ingest(dialect, &argv, session.as_deref(), &cwd);
78            }
79            outcome
80        }
81        Err(e) => {
82            // Daemon down: locally classify so a catastrophic command is still
83            // denied (fail-closed for the hard floor); non-catastrophic honors
84            // the fail-open default.
85            if kintsugi_core::classify(&proposed).class == Class::Catastrophic {
86                eprintln!(
87                    "kintsugi-hook: daemon unreachable; denying catastrophic (fail-closed): {e}"
88                );
89                dialect.format(&dialect::Resolved::Deny(
90                    "Kintsugi daemon unreachable; catastrophic command blocked (fail-closed)"
91                        .into(),
92                ))
93            } else if fail_closed() {
94                eprintln!("kintsugi-hook: daemon unreachable; denying (fail-closed): {e}");
95                dialect.format(&dialect::Resolved::Deny(
96                    "Kintsugi daemon unreachable (fail-closed)".into(),
97                ))
98            } else {
99                eprintln!("kintsugi-hook: warning: daemon unreachable; allowing unguarded: {e}");
100                dialect.pass()
101            }
102        }
103    }
104}
105
106/// Backwards-compatible Claude Code entry point.
107pub fn handle(input: &str) -> HookOutcome {
108    handle_with(Dialect::Claude, input)
109}
110
111/// Observe a non-shell content-tool call (web fetch / search / MCP / read) as a
112/// provenance taint source. Best-effort and silent: a parse miss, an untracked
113/// session, or an unreachable daemon must never affect the agent — observation
114/// only labels, it is not a gate.
115fn observe_content_call(dialect: Dialect, input: &str) {
116    let Some(call) = dialect.parse_content(input) else {
117        return;
118    };
119    if let Some(src) = observe::classify_tool_ingest(&call.tool, &call.input, &call.cwd) {
120        send_ingest(dialect, src, call.session_id.as_deref(), &call.cwd);
121    }
122}
123
124/// Observe a shell command that ingests remote content (`curl`/`wget`/`git
125/// clone`). Best-effort and silent, same as [`observe_content_call`].
126fn observe_shell_ingest(dialect: Dialect, argv: &[String], session: Option<&str>, cwd: &Path) {
127    if let Some(src) = observe::classify_shell_ingest(argv) {
128        send_ingest(dialect, src, session, cwd);
129    }
130}
131
132/// Build and send an [`ObservedIngest`] to the daemon. Skips untracked sessions
133/// (a `None`/empty session can never be taint-tracked, so there is nothing to
134/// label) and swallows any IPC error (observation never blocks the agent).
135fn send_ingest(dialect: Dialect, src: observe::IngestSource, session: Option<&str>, cwd: &Path) {
136    let Some(session) = session.filter(|s| !s.is_empty()) else {
137        return;
138    };
139    let observed = ObservedIngest::now(src.kind, src.id, dialect.agent_id(), session, cwd);
140    let _ = Client::ingest(&observed);
141}
142
143/// Augment a catastrophic deny with the stop → approve → continue flow.
144///
145/// A hook is one-shot: by the time you see this, the agent already got the deny
146/// and there is no parked tool call to resume. The agent must never run a
147/// catastrophic itself, and approving it elsewhere does NOT auto-resume the agent.
148/// So this message tells the agent to *stop and hand off to the human*, who can
149/// run it from the trusted UI (Held → Approve & run) or via `kintsugi run <id>` —
150/// both snapshot first (so `kintsugi undo` works) and are gated on a deliberate
151/// human action (a real-terminal keypress on the CLI; a click in the unlocked app)
152/// so an agent shelling out still can't self-approve. After the human handles it,
153/// they tell the agent to continue. The short id prefix is surfaced for the CLI.
154fn held_for_approval(reason: &str, id: &str) -> String {
155    let short = id.get(..8).unwrap_or(id);
156    format!(
157        "{reason} Kintsugi blocked this catastrophic command — do NOT run it or try to work \
158         around it. Stop and tell the user: if they want it, they can approve it in the Kintsugi \
159         app (Held → Approve & run) or run `kintsugi run {short}` in their terminal — either way \
160         it is snapshotted first, so `kintsugi undo` can roll it back. You will not resume \
161         automatically; once they've handled it, they can tell you to continue."
162    )
163}
164
165/// True if the admin-set fail-closed marker is present (an agent can't unset a
166/// root-owned marker) OR the `KINTSUGI_FAIL_CLOSED` env var opts in. The marker
167/// wins, so `KINTSUGI_FAIL_CLOSED=0` can't re-open the gate.
168fn fail_closed() -> bool {
169    kintsugi_daemon::is_fail_closed_marked()
170        || matches!(
171            std::env::var("KINTSUGI_FAIL_CLOSED").ok().as_deref(),
172            Some("1") | Some("true") | Some("yes")
173        )
174}
175
176/// Parse the `--agent <id>` flag from argv, defaulting to Claude Code.
177///
178/// Unknown ids fall back to Claude with a warning rather than failing — a
179/// misconfigured hook should still guard, not crash the agent.
180pub fn dialect_from_args<I: IntoIterator<Item = String>>(args: I) -> Dialect {
181    let mut it = args.into_iter();
182    while let Some(a) = it.next() {
183        let value = if let Some(v) = a.strip_prefix("--agent=") {
184            Some(v.to_string())
185        } else if a == "--agent" {
186            it.next()
187        } else {
188            None
189        };
190        if let Some(v) = value {
191            match Dialect::from_agent(&v) {
192                Some(d) => return d,
193                None => {
194                    eprintln!("kintsugi-hook: unknown --agent '{v}', defaulting to claude-code");
195                    return Dialect::Claude;
196                }
197            }
198        }
199    }
200    Dialect::Claude
201}
202
203/// Read the hook payload from stdin and emit the outcome, picking the dialect
204/// from the process arguments.
205pub fn run() -> i32 {
206    let dialect = dialect_from_args(std::env::args().skip(1));
207    let stdin = std::io::stdin();
208    let stdout = std::io::stdout();
209    run_io(dialect, stdin.lock(), stdout.lock())
210}
211
212/// The hook over arbitrary reader/writer for a given dialect (testable).
213pub fn run_io<R: std::io::Read, W: std::io::Write>(
214    dialect: Dialect,
215    mut reader: R,
216    mut writer: W,
217) -> i32 {
218    let mut input = String::new();
219    if let Err(e) = reader.read_to_string(&mut input) {
220        eprintln!("kintsugi-hook: failed to read stdin: {e}");
221        return 0; // fail-open
222    }
223    let outcome = handle_with(dialect, &input);
224    if let Some(out) = outcome.stdout {
225        let _ = writeln!(writer, "{out}");
226    }
227    outcome.exit_code
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn non_shell_tool_is_allowed_silently() {
236        let payload = r#"{"tool_name":"Edit","tool_input":{"file_path":"x"}}"#;
237        assert_eq!(handle(payload), HookOutcome::silent());
238    }
239
240    #[test]
241    fn held_for_approval_guides_stop_approve_continue() {
242        let msg = held_for_approval("recursively deletes files.", "abcd1234-5678-90ab-cdef");
243        assert!(msg.contains("recursively deletes files."));
244        assert!(
245            msg.contains("do NOT run it") && msg.contains("work around"),
246            "must tell the agent to stop, not run or work around it"
247        );
248        assert!(
249            msg.contains("Kintsugi app") || msg.contains("Approve & run"),
250            "should point at approving in the app"
251        );
252        assert!(
253            msg.contains("kintsugi run abcd1234"),
254            "should give the guarded CLI run command with the short id"
255        );
256        assert!(msg.contains("undo"), "should mention reversibility");
257        assert!(
258            msg.contains("continue"),
259            "should set up the human-driven resume (tell the agent to continue)"
260        );
261    }
262
263    #[test]
264    fn malformed_payload_is_allowed_silently() {
265        assert_eq!(handle("not json"), HookOutcome::silent());
266    }
267
268    #[test]
269    fn empty_command_is_allowed_silently() {
270        let payload = r#"{"tool_name":"Bash","tool_input":{"command":"   "}}"#;
271        assert_eq!(handle(payload), HookOutcome::silent());
272    }
273
274    #[test]
275    fn run_io_allows_non_shell_tool_silently() {
276        let input = br#"{"tool_name":"Edit","tool_input":{"file_path":"x"}}"#;
277        let mut out = Vec::new();
278        let code = run_io(Dialect::Claude, &input[..], &mut out);
279        assert_eq!(code, 0);
280        assert!(out.is_empty(), "allow-silent writes nothing");
281    }
282
283    #[test]
284    fn dialect_from_args_reads_flag_forms() {
285        assert_eq!(
286            dialect_from_args(["--agent".to_string(), "cursor".to_string()]),
287            Dialect::Cursor
288        );
289        assert_eq!(
290            dialect_from_args(["--agent=qwen".to_string()]),
291            Dialect::Qwen
292        );
293        // No flag → Claude (backwards compatible).
294        assert_eq!(dialect_from_args(Vec::<String>::new()), Dialect::Claude);
295        // Unknown → Claude fallback.
296        assert_eq!(
297            dialect_from_args(["--agent=banana".to_string()]),
298            Dialect::Claude
299        );
300    }
301}