返回 CodeWhale
hooks.rs
1 //! Programmable admission listeners reuse the native strict hook fold.
2 //! The host returns proposals, never tool or approval authority.
3
4 use std::sync::Arc;
5 use std::time::{Duration, Instant};
6
7 use serde_json::{Value, json};
8
9 use super::protocol::{CoreRequest, HookCallPayload, HookEvaluateParams, HookVerdictWire};
10 use super::{ExtensionHostManager, HostAttachment, ManagerShared};
11 use crate::hooks::HookResult;
12
13 const HOOK_DEADLINE: Duration = Duration::from_secs(5);
14
15 impl HostAttachment {
16 pub async fn agent_pre_step_hooks(&self, payload: HookCallPayload) -> Vec<HookResult> {
17 self.evaluate_admitting_hooks("agent/pre-step", "pre-step", payload)
18 .await
19 }
20
21 pub async fn tool_before_hooks(&self, payload: HookCallPayload) -> Vec<HookResult> {
22 self.evaluate_admitting_hooks("tools/pre-execute", "pre-execute", payload)
23 .await
24 }
25
26 /// Only the reviewed owners this engine's own snapshot desires see its
27 /// call. A shared host never broadcasts another workspace's arguments.
28 async fn evaluate_admitting_hooks(
29 &self,
30 event_name: &str,
31 result_label: &str,
32 mut payload: HookCallPayload,
33 ) -> Vec<HookResult> {
34 let shared = &self.manager.shared;
35 let desired = shared
36 .attachments
37 .lock()
38 .expect("attachments lock")
39 .get(&self.id)
40 .map(|state| state.selection.clone())
41 .unwrap_or_default();
42 let hooks: Vec<_> = shared
43 .registry
44 .lock()
45 .expect("registry lock")
46 .live_hooks()
47 .into_iter()
48 .filter(|hook| {
49 hook.event == event_name
50 && desired.includes(
51 &hook.owner.plugin_id,
52 &hook.content_hash,
53 hook.scope.as_ref(),
54 )
55 })
56 .collect();
57 let mut results = Vec::with_capacity(hooks.len());
58 let batch_started = Instant::now();
59 for hook in hooks {
60 let started = Instant::now();
61 let answer = async {
62 let host = shared.live_host_for_hook(&hook).await?;
63 let still_desired = desired.revision.is_some_and(|revision| {
64 shared.selection_current(
65 revision,
66 &hook.owner.plugin_id,
67 &hook.content_hash,
68 hook.scope.as_ref(),
69 )
70 });
71 if !still_desired {
72 return Err("plugin hook was withdrawn".to_string());
73 }
74 let remaining_ms = HOOK_DEADLINE
75 .saturating_sub(batch_started.elapsed())
76 .as_millis() as u64;
77 if remaining_ms == 0 {
78 return Err("plugin hook batch deadline elapsed".to_string());
79 }
80 let value = host
81 .call(
82 CoreRequest::HookEvaluate(HookEvaluateParams {
83 handle: hook.handle,
84 event: hook.event.clone(),
85 payload: payload.clone(),
86 deadline_ms: remaining_ms,
87 }),
88 Some(hook.owner.plugin_id.clone()),
89 )
90 .await
91 .map_err(|_| "plugin hook did not answer".to_string())?;
92 // A late response cannot restore an owner revoked while the
93 // callback waited. Revalidate its receipt and generation too.
94 shared.live_host_for_hook(&hook).await?;
95 let still_desired = desired.revision.is_some_and(|revision| {
96 shared.selection_current(
97 revision,
98 &hook.owner.plugin_id,
99 &hook.content_hash,
100 hook.scope.as_ref(),
101 )
102 });
103 if !still_desired {
104 return Err("plugin hook was withdrawn".to_string());
105 }
106 let (verdict, stdout) = decode_verdict(value)?;
107 if let HookVerdictWire::Revise { input } = verdict {
108 payload.input = Value::Object(input);
109 }
110 Ok(stdout)
111 }
112 .await;
113 let answered = answer.is_ok();
114 let denies = answer.as_ref().is_ok_and(|stdout| {
115 crate::hooks::parse_tool_call_before_stdout(stdout).decision
116 == Some(crate::hooks::ToolCallDecision::Deny)
117 });
118 results.push(HookResult {
119 name: Some(format!("extension:{}:{result_label}", hook.plugin_name)),
120 success: answered,
121 background: false,
122 strict: true,
123 exit_code: answered.then_some(0),
124 stdout: answer.unwrap_or_default(),
125 stderr: String::new(),
126 duration: started.elapsed(),
127 error: (!answered).then(|| "plugin hook returned no valid verdict".to_string()),
128 });
129 if !answered || denies {
130 break;
131 }
132 }
133 results
134 }
135
136 pub fn spawn_tool_after_hooks(&self, payload: HookCallPayload) {
137 let manager = Arc::clone(&self.manager);
138 let id = self.id;
139 tokio::spawn(async move { tool_after_hooks(manager, id, payload).await });
140 }
141 }
142
143 async fn tool_after_hooks(manager: Arc<ExtensionHostManager>, id: u64, payload: HookCallPayload) {
144 {
145 let shared = &manager.shared;
146 let desired = shared
147 .attachments
148 .lock()
149 .expect("attachments lock")
150 .get(&id)
151 .map(|state| state.selection.clone())
152 .unwrap_or_default();
153 let hooks: Vec<_> = shared
154 .registry
155 .lock()
156 .expect("registry lock")
157 .live_hooks()
158 .into_iter()
159 .filter(|hook| {
160 hook.event == "tools/post-execute"
161 && desired.includes(
162 &hook.owner.plugin_id,
163 &hook.content_hash,
164 hook.scope.as_ref(),
165 )
166 })
167 .collect();
168 if hooks.is_empty() {
169 return;
170 }
171 let batch_started = Instant::now();
172 for hook in hooks {
173 let Ok(host) = shared.live_host_for_hook(&hook).await else {
174 continue;
175 };
176 let still_desired = desired.revision.is_some_and(|revision| {
177 shared.selection_current(
178 revision,
179 &hook.owner.plugin_id,
180 &hook.content_hash,
181 hook.scope.as_ref(),
182 )
183 });
184 if !still_desired {
185 continue;
186 }
187 let remaining_ms = HOOK_DEADLINE
188 .saturating_sub(batch_started.elapsed())
189 .as_millis() as u64;
190 if remaining_ms == 0 {
191 break;
192 }
193 let _ = host
194 .call(
195 CoreRequest::HookEvaluate(HookEvaluateParams {
196 handle: hook.handle,
197 event: hook.event.clone(),
198 payload: payload.clone(),
199 deadline_ms: remaining_ms,
200 }),
201 Some(hook.owner.plugin_id.clone()),
202 )
203 .await;
204 }
205 }
206 }
207
208 impl ManagerShared {
209 async fn live_host_for_hook(
210 &self,
211 hook: &super::registry::HookRegistration,
212 ) -> Result<std::sync::Arc<super::supervisor::HostProcess>, String> {
213 self.live_host(&hook.cohort, |registry| {
214 registry
215 .is_live_hook(hook.handle, &hook.owner)
216 .then(|| hook.owner.clone())
217 .ok_or_else(|| "plugin hook is no longer registered".to_string())
218 })
219 .await
220 }
221 }
222
223 struct LimitWriter {
224 written: usize,
225 limit: usize,
226 }
227
228 impl std::io::Write for LimitWriter {
229 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
230 self.written = self.written.saturating_add(buf.len());
231 if self.written > self.limit {
232 return Err(std::io::Error::other("size limit exceeded"));
233 }
234 Ok(buf.len())
235 }
236
237 fn flush(&mut self) -> std::io::Result<()> {
238 Ok(())
239 }
240 }
241
242 fn serialized_exceeds(value: &Value, limit: usize) -> bool {
243 serde_json::to_writer(LimitWriter { written: 0, limit }, value).is_err()
244 }
245
246 fn sanitize_verdict_text(text: &str) -> String {
247 let mut stripped =
248 String::with_capacity(text.len().min(crate::hooks::HOOK_TEXT_FIELD_MAX_CHARS));
249 codewhale_sanitize::sanitize::strip_ansi_into(text, &mut stripped);
250 crate::hooks::sanitize_hook_text(&stripped, crate::hooks::HOOK_TEXT_FIELD_MAX_CHARS)
251 }
252
253 fn validate_raw_verdict(value: &Value) -> Result<(), String> {
254 let Some(obj) = value.as_object() else {
255 return Err("plugin hook returned a malformed verdict".to_string());
256 };
257 match obj.get("kind").and_then(Value::as_str) {
258 Some("abstain") => {
259 if obj.len() != 1 {
260 return Err("plugin hook returned a malformed verdict".to_string());
261 }
262 }
263 Some("deny" | "ask" | "annotate") => {
264 if obj.len() != 2 {
265 return Err("plugin hook returned a malformed verdict".to_string());
266 }
267 }
268 Some("revise") => {
269 if let Some(input) = obj.get("input")
270 && serialized_exceeds(input, crate::hooks::HOOK_UPDATED_INPUT_MAX_BYTES)
271 {
272 return Err("plugin hook input revision exceeded the limit".to_string());
273 }
274 if obj.len() != 2 {
275 return Err("plugin hook returned a malformed verdict".to_string());
276 }
277 }
278 _ => return Err("plugin hook returned a malformed verdict".to_string()),
279 }
280 Ok(())
281 }
282
283 fn decode_verdict(value: Value) -> Result<(HookVerdictWire, String), String> {
284 validate_raw_verdict(&value)?;
285 let verdict: HookVerdictWire = serde_json::from_value(value)
286 .map_err(|_| "plugin hook returned a malformed verdict".to_string())?;
287 let stdout = verdict_stdout(&verdict)?;
288 Ok((verdict, stdout))
289 }
290
291 fn verdict_stdout(verdict: &HookVerdictWire) -> Result<String, String> {
292 let value = match verdict {
293 HookVerdictWire::Abstain => json!({}),
294 HookVerdictWire::Deny { reason } => {
295 let reason = sanitize_verdict_text(reason);
296 json!({"decision":"deny", "reason":reason})
297 }
298 HookVerdictWire::Ask { reason } => {
299 let reason = sanitize_verdict_text(reason);
300 json!({"decision":"ask", "reason":reason})
301 }
302 HookVerdictWire::Annotate { text } => {
303 let text = sanitize_verdict_text(text);
304 json!({"additionalContext":text})
305 }
306 HookVerdictWire::Revise { input } => {
307 if serialized_exceeds(
308 &Value::Object(input.clone()),
309 crate::hooks::HOOK_UPDATED_INPUT_MAX_BYTES,
310 ) {
311 return Err("plugin hook input revision exceeded the limit".to_string());
312 }
313 json!({"updatedInput":Value::Object(input.clone())})
314 }
315 };
316 let stdout =
317 serde_json::to_string(&value).map_err(|_| "plugin hook verdict is not JSON".to_string())?;
318 let parsed = crate::hooks::parse_tool_call_before_stdout(&stdout);
319 match verdict {
320 HookVerdictWire::Abstain | HookVerdictWire::Annotate { .. } => {}
321 HookVerdictWire::Deny { .. }
322 if parsed.decision != Some(crate::hooks::ToolCallDecision::Deny) =>
323 {
324 return Err("plugin hook returned a malformed verdict".to_string());
325 }
326 HookVerdictWire::Ask { .. }
327 if parsed.decision != Some(crate::hooks::ToolCallDecision::Ask) =>
328 {
329 return Err("plugin hook returned a malformed verdict".to_string());
330 }
331 HookVerdictWire::Revise { .. } if parsed.updated_input.is_none() => {
332 return Err("plugin hook input revision exceeded the limit".to_string());
333 }
334 _ => {}
335 }
336 Ok(stdout)
337 }
338
339 #[cfg(test)]
340 mod tests {
341 use super::*;
342 use crate::core::engine::turn_loop::run_tool_call_before_hooks;
343 use crate::extension_host::test_support::{FixturePlugins, node_for_tests};
344 use codewhale_config::AppMode;
345 use std::sync::Arc;
346
347 #[tokio::test]
348 async fn real_host_hook_timeout_and_owner_revocation_fail_closed_and_do_not_cross_workspaces() {
349 let Some(node) = node_for_tests("real_host_hook_timeout_and_revocation") else {
350 return;
351 };
352 let _policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(true);
353 let fixture = FixturePlugins::new(&["hook-policy"]).await;
354 let manager = Arc::new(super::super::ExtensionHostManager::new(
355 super::super::ExtensionHostOptions {
356 runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node,
357 node_override: Some(node),
358 root: Some(fixture.root.clone()),
359 supervision: super::super::SupervisionOptions {
360 heartbeat_interval: Duration::from_secs(60),
361 ..Default::default()
362 },
363 ..Default::default()
364 },
365 ));
366 let source = Arc::new(manager.attach(fixture.registry()));
367 source.sync().await.unwrap();
368 let timeout = run_tool_call_before_hooks(
369 None,
370 Some(&source),
371 "read",
372 "timeout",
373 &json!({"path":"timeout.txt"}),
374 AppMode::Agent,
375 fixture.workspace(),
376 "fixture",
377 )
378 .await;
379 assert!(
380 timeout
381 .unwrap_err()
382 .to_string()
383 .contains("returned no verdict")
384 );
385
386 let other_workspace = tempfile::tempdir().unwrap();
387 let other = manager.attach(Arc::new(codewhale_plugins::PluginRegistry::empty(
388 other_workspace.path(),
389 )));
390 other.sync().await.unwrap();
391 let unrelated = run_tool_call_before_hooks(
392 None,
393 Some(&other),
394 "read",
395 "other",
396 &json!({"path":"blocked.txt"}),
397 AppMode::Agent,
398 other_workspace.path(),
399 "fixture",
400 )
401 .await
402 .unwrap();
403 assert_eq!(
404 unrelated,
405 Default::default(),
406 "a workspace does not receive another workspace's listener"
407 );
408
409 let sent = manager.host_requests_started().unwrap();
410 let pending_source = Arc::clone(&source);
411 let workspace = fixture.workspace().to_path_buf();
412 let pending = tokio::spawn(async move {
413 run_tool_call_before_hooks(
414 None,
415 Some(&pending_source),
416 "read",
417 "held",
418 &json!({"path":"held.txt"}),
419 AppMode::Agent,
420 &workspace,
421 "fixture",
422 )
423 .await
424 });
425 tokio::time::timeout(Duration::from_secs(2), async {
426 while manager.host_requests_started() == Some(sent) {
427 tokio::task::yield_now().await;
428 }
429 })
430 .await
431 .unwrap();
432 source.set_plugins(fixture.disable("hook-policy"));
433 source.sync().await.unwrap();
434 let error = tokio::time::timeout(Duration::from_secs(2), pending)
435 .await
436 .expect("revocation cancels a held hook")
437 .unwrap()
438 .unwrap_err();
439 assert!(error.to_string().contains("returned no verdict"));
440 let after = run_tool_call_before_hooks(
441 None,
442 Some(&source),
443 "read",
444 "after",
445 &json!({"path":"before.txt"}),
446 AppMode::Agent,
447 fixture.workspace(),
448 "fixture",
449 )
450 .await
451 .unwrap();
452 assert_eq!(after, Default::default());
453 manager.shutdown().await;
454 }
455
456 #[test]
457 fn oversized_revise_rejected_before_deserialization_and_overlong_text_truncated_after_ansi_strip()
458 {
459 let oversized_revise = json!({
460 "kind": "revise",
461 "input": { "blob": "x".repeat(crate::hooks::HOOK_UPDATED_INPUT_MAX_BYTES + 1) },
462 "extra": 1,
463 });
464 let err = decode_verdict(oversized_revise).unwrap_err();
465 assert!(
466 err.contains("exceeded the limit"),
467 "expected pre-deserialize revise size guard, got: {err}"
468 );
469
470 let too_long = "r".repeat(crate::hooks::HOOK_TEXT_FIELD_MAX_CHARS + 500);
471 let (_, deny_stdout) =
472 decode_verdict(json!({ "kind": "deny", "reason": too_long })).unwrap();
473 let parsed_deny = crate::hooks::parse_tool_call_before_stdout(&deny_stdout);
474 assert_eq!(
475 parsed_deny.decision,
476 Some(crate::hooks::ToolCallDecision::Deny)
477 );
478 assert!(
479 parsed_deny
480 .reason
481 .as_deref()
482 .unwrap()
483 .ends_with("…[truncated]")
484 );
485 assert!(deny_stdout.len() <= crate::hooks::HOOK_TEXT_FIELD_MAX_CHARS + 96);
486
487 let (_, ask_stdout) = decode_verdict(json!({ "kind": "ask", "reason": too_long })).unwrap();
488 let parsed_ask = crate::hooks::parse_tool_call_before_stdout(&ask_stdout);
489 assert_eq!(
490 parsed_ask.decision,
491 Some(crate::hooks::ToolCallDecision::Ask)
492 );
493 assert!(
494 parsed_ask
495 .reason
496 .as_deref()
497 .unwrap()
498 .ends_with("…[truncated]")
499 );
500
501 let (_, annotate_stdout) =
502 decode_verdict(json!({ "kind": "annotate", "text": too_long })).unwrap();
503 let parsed_annotate = crate::hooks::parse_tool_call_before_stdout(&annotate_stdout);
504 assert!(
505 parsed_annotate
506 .additional_context
507 .as_deref()
508 .unwrap()
509 .ends_with("…[truncated]")
510 );
511 assert!(annotate_stdout.len() <= crate::hooks::HOOK_TEXT_FIELD_MAX_CHARS + 96);
512
513 // ANSI escape sequences are stripped before counting against HOOK_TEXT_FIELD_MAX_CHARS.
514 let ansi_at_limit = format!(
515 "\u{1b}[31m{}\u{1b}[0m",
516 "a".repeat(crate::hooks::HOOK_TEXT_FIELD_MAX_CHARS)
517 );
518 let (_, ansi_stdout) =
519 decode_verdict(json!({ "kind": "annotate", "text": ansi_at_limit })).unwrap();
520 let parsed_ansi = crate::hooks::parse_tool_call_before_stdout(&ansi_stdout);
521 let context = parsed_ansi.additional_context.unwrap();
522 assert_eq!(
523 context.chars().count(),
524 crate::hooks::HOOK_TEXT_FIELD_MAX_CHARS
525 );
526 assert!(!context.contains('\u{1b}'));
527 assert!(!context.ends_with("…[truncated]"));
528 }
529
530 #[test]
531 fn bounded_verdicts_decode_and_produce_bounded_stdout() {
532 let at_limit = "a".repeat(crate::hooks::HOOK_TEXT_FIELD_MAX_CHARS);
533 let (_, deny_stdout) =
534 decode_verdict(json!({ "kind": "deny", "reason": at_limit })).unwrap();
535 assert_eq!(
536 crate::hooks::parse_tool_call_before_stdout(&deny_stdout).decision,
537 Some(crate::hooks::ToolCallDecision::Deny)
538 );
539 assert!(deny_stdout.len() <= crate::hooks::HOOK_TEXT_FIELD_MAX_CHARS + 64);
540
541 let (_, annotate_stdout) =
542 decode_verdict(json!({ "kind": "annotate", "text": at_limit })).unwrap();
543 assert!(annotate_stdout.len() <= crate::hooks::HOOK_TEXT_FIELD_MAX_CHARS + 64);
544 }
545 }
546
546 lines RUST