kintsugi_intercept/
hook.rs1use 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
27pub fn handle_with(dialect: Dialect, input: &str) -> HookOutcome {
29 let parsed = match dialect.parse(input) {
30 Parsed::Shell(s) => s,
31 Parsed::NotShell => {
32 observe_content_call(dialect, input);
36 return HookOutcome::silent();
37 }
38 Parsed::Bad(e) => {
39 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 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 if matches!(resolved, Resolved::Allow) {
77 observe_shell_ingest(dialect, &argv, session.as_deref(), &cwd);
78 }
79 outcome
80 }
81 Err(e) => {
82 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
106pub fn handle(input: &str) -> HookOutcome {
108 handle_with(Dialect::Claude, input)
109}
110
111fn 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
124fn 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
132fn 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
143fn 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
165fn 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
176pub 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
203pub 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
212pub 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; }
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 assert_eq!(dialect_from_args(Vec::<String>::new()), Dialect::Claude);
295 assert_eq!(
297 dialect_from_args(["--agent=banana".to_string()]),
298 Dialect::Claude
299 );
300 }
301}