safe_chains/targets/
agy.rs1use std::path::{Path, PathBuf};
19
20use serde::Deserialize;
21use serde_json::{Map, Value, json};
22
23use super::{GatedPolicy, HookFormat, HookInput, HookResponse, InstallOutcome, ParseError, Target};
24use crate::verdict::Verdict;
25
26pub struct AntigravityTarget;
27
28impl Target for AntigravityTarget {
29 fn name(&self) -> &'static str {
30 "antigravity"
31 }
32
33 fn display_name(&self) -> &'static str {
34 "Antigravity CLI (agy)"
35 }
36
37 fn shell_tool_name(&self) -> &'static str {
38 "run_command" }
40
41 #[cfg(test)]
42 fn sample_envelope(&self, tool: &str, command: &str) -> Option<String> {
43 Some(format!(
44 r#"{{"toolCall":{{"name":"{tool}","args":{{"CommandLine":"{command}"}}}},"workspacePaths":["/w"]}}"#
45 ))
46 }
47
48 fn detect_paths(&self, home: &Path) -> Vec<PathBuf> {
49 vec![home.join(".gemini/antigravity-cli")]
50 }
51
52 fn install(&self, home: &Path) -> Result<InstallOutcome, String> {
53 let dir = home.join(".gemini/config");
55 if !dir.exists() {
56 return Ok(InstallOutcome::Skipped {
57 reason: format!("{} not found (Antigravity CLI not set up)", dir.display()),
58 });
59 }
60 let path = dir.join("hooks.json");
61 let binary = "safe-chains hook antigravity";
62
63 let mut settings: Value = if path.exists() {
64 let contents = std::fs::read_to_string(&path)
65 .map_err(|e| format!("Could not read {}: {e}", path.display()))?;
66 serde_json::from_str(&contents)
67 .map_err(|e| format!("Could not parse {}: {e}", path.display()))?
68 } else {
69 Value::Object(Map::new())
70 };
71
72 if has_safe_chains_hook(&settings) {
73 return Ok(InstallOutcome::AlreadyConfigured { path });
74 }
75 add_hook(&mut settings, binary);
76 let output = serde_json::to_string_pretty(&settings).expect("serializing valid JSON");
77 std::fs::write(&path, format!("{output}\n"))
78 .map_err(|e| format!("Could not write {}: {e}", path.display()))?;
79 Ok(InstallOutcome::Installed { path })
80 }
81
82 fn hook_format(&self) -> Option<&dyn HookFormat> {
83 Some(&AntigravityHookFormat)
84 }
85}
86
87struct AntigravityHookFormat;
88
89#[derive(Deserialize)]
92struct ToolArgs {
93 #[serde(rename = "CommandLine")]
94 command_line: Option<String>,
95}
96
97#[derive(Deserialize)]
98struct ToolCall {
99 #[serde(default)]
103 name: Option<String>,
104 #[serde(default)]
105 args: Option<ToolArgs>,
106}
107
108#[derive(Deserialize)]
109struct AntigravityEnvelope {
110 #[serde(rename = "toolCall")]
111 tool_call: Option<ToolCall>,
112 #[serde(rename = "workspacePaths", default)]
113 workspace_paths: Vec<String>,
114}
115
116impl HookFormat for AntigravityHookFormat {
117 fn parse_input(&self, stdin: &str) -> Result<HookInput, ParseError> {
118 let env: AntigravityEnvelope =
119 serde_json::from_str(stdin).map_err(|e| ParseError { message: e.to_string() })?;
120 let tool_call = env.tool_call;
121 if let Some(name) = tool_call.as_ref().and_then(|t| t.name.as_deref())
124 && name != "run_command"
125 {
126 return Err(ParseError { message: format!("not a shell tool: {name}") });
127 }
128 let command = tool_call
129 .and_then(|t| t.args)
130 .and_then(|a| a.command_line)
131 .ok_or_else(|| ParseError { message: "no toolCall.args.CommandLine".into() })?;
132 let cwd = env.workspace_paths.into_iter().next();
133 Ok(HookInput { command, root: cwd.clone(), cwd, session_id: None })
134 }
135
136 fn decision_pointer(&self) -> &'static str {
137 "/decision" }
139
140 fn render_response(&self, verdict: Verdict) -> HookResponse {
141 if verdict.is_allowed() {
146 decision("allow", "safe-chains: all commands in the chain are allowlisted")
147 } else {
148 HookResponse { stdout: String::new(), exit_code: 0 }
149 }
150 }
151
152 fn gated_policy(&self) -> GatedPolicy {
155 GatedPolicy::Ask
156 }
157
158 fn render_ask(&self, reason: &str) -> HookResponse {
159 decision("force_ask", reason)
163 }
164}
165
166fn decision(kind: &str, reason: &str) -> HookResponse {
167 let body = json!({ "decision": kind, "reason": reason });
168 HookResponse { stdout: serde_json::to_string(&body).unwrap_or_default(), exit_code: 0 }
169}
170
171fn hook_entry(binary: &str) -> Value {
172 json!({
173 "PreToolUse": [{
174 "matcher": "run_command",
175 "hooks": [{ "type": "command", "command": binary }],
176 }]
177 })
178}
179
180fn has_safe_chains_hook(settings: &Value) -> bool {
181 settings
183 .get("safe-chains")
184 .and_then(|h| h.get("PreToolUse"))
185 .and_then(Value::as_array)
186 .is_some_and(|groups| {
187 groups.iter().any(|g| {
188 g.get("hooks").and_then(Value::as_array).is_some_and(|hs| {
189 hs.iter().any(|h| {
190 h.get("command").and_then(Value::as_str).is_some_and(|c| c.contains("safe-chains"))
191 })
192 })
193 })
194 })
195}
196
197fn add_hook(settings: &mut Value, binary: &str) {
198 if !settings.is_object() {
199 *settings = json!({});
200 }
201 settings
202 .as_object_mut()
203 .expect("settings is an object")
204 .insert("safe-chains".to_string(), hook_entry(binary));
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210 use crate::verdict::SafetyLevel;
211
212 #[test]
213 fn install_skips_when_no_config_dir() {
214 let dir = tempfile::tempdir().unwrap();
215 assert!(matches!(AntigravityTarget.install(dir.path()).unwrap(), InstallOutcome::Skipped { .. }));
216 }
217
218 #[test]
219 fn install_writes_named_hook_with_run_command_matcher() {
220 let dir = tempfile::tempdir().unwrap();
221 std::fs::create_dir_all(dir.path().join(".gemini/config")).unwrap();
222 assert!(matches!(AntigravityTarget.install(dir.path()).unwrap(), InstallOutcome::Installed { .. }));
223 let s: Value = serde_json::from_str(
224 &std::fs::read_to_string(dir.path().join(".gemini/config/hooks.json")).unwrap(),
225 )
226 .unwrap();
227 assert!(has_safe_chains_hook(&s));
228 assert_eq!(
229 s.pointer("/safe-chains/PreToolUse/0/matcher").and_then(Value::as_str),
230 Some("run_command"),
231 );
232 }
233
234 #[test]
235 fn install_is_idempotent() {
236 let dir = tempfile::tempdir().unwrap();
237 std::fs::create_dir_all(dir.path().join(".gemini/config")).unwrap();
238 AntigravityTarget.install(dir.path()).unwrap();
239 assert!(matches!(
240 AntigravityTarget.install(dir.path()).unwrap(),
241 InstallOutcome::AlreadyConfigured { .. }
242 ));
243 }
244
245 #[test]
246 fn install_preserves_other_named_hooks() {
247 let dir = tempfile::tempdir().unwrap();
249 let cfg = dir.path().join(".gemini/config");
250 std::fs::create_dir_all(&cfg).unwrap();
251 std::fs::write(
252 cfg.join("hooks.json"),
253 r#"{"lint-checker":{"PostToolUse":[{"matcher":"run_command","hooks":[{"type":"command","command":"./lint.sh"}]}]}}"#,
254 )
255 .unwrap();
256 AntigravityTarget.install(dir.path()).unwrap();
257 let s: Value =
258 serde_json::from_str(&std::fs::read_to_string(cfg.join("hooks.json")).unwrap()).unwrap();
259 assert!(has_safe_chains_hook(&s));
260 assert!(
261 s.pointer("/lint-checker/PostToolUse/0/hooks/0/command").and_then(Value::as_str)
262 == Some("./lint.sh"),
263 "the user's own named hook must survive install",
264 );
265 }
266
267 #[test]
268 fn parses_command_and_workspace() {
269 let input = r#"{"toolCall":{"name":"run_command","args":{"CommandLine":"cat /etc/hosts"}},"workspacePaths":["/w"]}"#;
270 let parsed = AntigravityHookFormat.parse_input(input).unwrap();
271 assert_eq!(parsed.command, "cat /etc/hosts");
272 assert_eq!(parsed.cwd.as_deref(), Some("/w"));
273 }
274
275 #[test]
276 fn safe_emits_allow_gated_asks_never_silent() {
277 let safe = AntigravityHookFormat.render_response(Verdict::Allowed(SafetyLevel::Inert));
279 let v: Value = serde_json::from_str(&safe.stdout).unwrap();
280 assert_eq!(v.get("decision").and_then(Value::as_str), Some("allow"));
281
282 assert_eq!(AntigravityHookFormat.gated_policy(), GatedPolicy::Ask);
283 let ask = AntigravityHookFormat.render_ask("please confirm");
284 let v: Value = serde_json::from_str(&ask.stdout).unwrap();
285 assert_eq!(v.get("decision").and_then(Value::as_str), Some("force_ask"));
287 assert_eq!(v.get("reason").and_then(Value::as_str), Some("please confirm"));
288 }
289}