返回 CodeWhale
test_cases_05.rs
根目录 / crates / engine / src / core / engine / tests / test_cases_05.rs
1 #[tokio::test]
2 async fn host_managed_engine_defers_idle_subagent_completion_to_explicit_turn() {
3 use crate::llm_client::mock::{MockLlmClient, canned};
4 use crate::tools::subagent::SubAgentCompletion;
5
6 let mut custom = HashMap::new();
7 custom.insert(
8 "custom-a".to_string(),
9 codewhale_runtime::config::ProviderConfig {
10 kind: Some("openai-compatible".to_string()),
11 base_url: Some("http://127.0.0.1:18181/v1".to_string()),
12 model: Some("local-model".to_string()),
13 api_key: Some("local-test-key".to_string()),
14 ..codewhale_runtime::config::ProviderConfig::default()
15 },
16 );
17 let config = {
18 let __cw_config_init_0_0 = Some("custom-a".to_string());
19 let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig {
20 custom,
21 ..codewhale_runtime::config::ProvidersConfig::default()
22 });
23 let mut __cw_config_init_0_value: Config = Config::default();
24 __cw_config_init_0_value.provider = __cw_config_init_0_0;
25 __cw_config_init_0_value.providers = __cw_config_init_0_1;
26 __cw_config_init_0_value
27 };
28 let runtime_services = crate::tools::spec::RuntimeToolServices {
29 active_thread_id: Some("thr_host_managed".to_string()),
30 ..crate::tools::spec::RuntimeToolServices::default()
31 };
32 let mut engine_config = EngineConfig {
33 max_steps: 0,
34 snapshots_enabled: false,
35 terminal_chrome_enabled: false,
36 runtime_services,
37 ..EngineConfig::default()
38 };
39 engine_config.features.disable(Feature::Mcp);
40 // This branch grants a zero-step host turn exactly one A2 report request
41 // (see host_managed_engine_does_not_self_dispatch_goal_continuation,
42 // which asserts that single dispatch). Script the response the same way
43 // so the turn completes deterministically instead of dialing the loopback
44 // route fixture that nothing serves in this test.
45 let mock = Arc::new(MockLlmClient::new(vec![canned::simple_text_turn(
46 "drained host turn",
47 )]));
48 let client: crate::core::model_client::SharedModelClient = mock.clone();
49 let (engine, handle) = Engine::new_with_model_client(engine_config, &config, client);
50 let owner_session_id = engine.session.id.clone();
51 let tx_subagent_completion = engine.tx_subagent_completion.clone();
52 let run_task = tokio::spawn(engine.run());
53
54 tx_subagent_completion
55 .try_send(SubAgentCompletion {
56 owner_session_id,
57 agent_id: "agent_deferred".to_string(),
58 payload: "deferred child result".to_string(),
59 })
60 .expect("queue sub-agent completion");
61 assert!(
62 tokio::time::timeout(Duration::from_millis(100), async {
63 handle.rx_event.write().await.recv().await
64 })
65 .await
66 .is_err(),
67 "an idle child completion must not create an unclaimed hosted turn"
68 );
69
70 handle
71 .send(Op::SendMessage(TurnSpec {
72 profile_constitution: None,
73 max_output_tokens: None,
74 content: "claim the next turn".to_string(),
75 images: Vec::new(),
76 mode: AppMode::Agent,
77 route: resolved_route_for_test(&config, "local-model"),
78 compaction: Box::new(CompactionConfig::default()),
79 initial_routed_usage: Box::default(),
80 goal_objective: None,
81 goal_token_budget: None,
82 goal_status: crate::tools::goal::GoalStatus::Active,
83 reasoning_effort: None,
84 reasoning_effort_auto: false,
85 auto_model: false,
86 allow_shell: false,
87 trust_mode: false,
88 auto_approve: false,
89 approval_mode: ApprovalMode::Suggest,
90 translation_enabled: false,
91 allowed_tools: None,
92 dynamic_tools: Vec::new(),
93 hook_executor: None,
94 verbosity: None,
95 provenance: UserInputProvenance::ExternalUser,
96 input_authorship: crate::core::ops::TurnInputAuthorship::NotPerson,
97 submission_id: None,
98 }))
99 .await
100 .expect("send explicit host turn");
101
102 let mut starts = 0;
103 let mut drained_completion = false;
104 loop {
105 let event = tokio::time::timeout(Duration::from_secs(3), async {
106 handle.rx_event.write().await.recv().await
107 })
108 .await
109 .expect("host engine event timeout")
110 .expect("host engine event");
111 match event {
112 Event::TurnStarted { .. } => starts += 1,
113 Event::Status { message } => {
114 drained_completion |= message.contains("1 queued sub-agent completion");
115 }
116 Event::TurnComplete { .. } => break,
117 _ => {}
118 }
119 }
120 assert_eq!(starts, 1);
121 assert!(
122 drained_completion,
123 "the next explicit turn must drain the queued child completion"
124 );
125
126 handle.send(Op::Shutdown).await.expect("shutdown engine");
127 run_task.await.expect("engine task");
128 }
129
130 /// A host-submitted turn echoes the correlation token it was submitted with,
131 /// while a runtime self-started turn (idle sub-agent completion resume) never
132 /// carries one. With this contract a host can tell "my pending submission
133 /// started" apart from "an autonomous follow-up overtook it in the event
134 /// stream" and only ever consume a deferred submit-window action on the
135 /// former.
136 #[tokio::test]
137 async fn turn_started_echoes_submission_id_and_self_starts_stay_none() {
138 use crate::llm_client::mock::{MockLlmClient, canned};
139 use crate::tools::subagent::SubAgentCompletion;
140
141 let workspace = tempdir().unwrap();
142 let config = Config::default();
143 let mock = Arc::new(MockLlmClient::new(vec![
144 canned::simple_text_turn("submitted turn finished."),
145 canned::simple_text_turn("self-started continuation finished."),
146 ]));
147 let (engine, handle) = Engine::new_with_model_client(
148 deterministic_engine_config(workspace.path()),
149 &config,
150 mock.clone(),
151 );
152 let owner_session_id = engine.session.id.clone();
153 let completion_tx = engine.tx_subagent_completion.clone();
154 let mut op = external_user_message_op("Watch the child agent.", AppMode::Agent, &config);
155 if let Op::SendMessage(TurnSpec { submission_id, .. }) = &mut op {
156 *submission_id = Some("sub-host-1".to_string());
157 }
158 let run_task = tokio::spawn(engine.run());
159 handle.send(op).await.expect("send correlated turn");
160
161 // The submitted turn's start echoes the token verbatim.
162 let submitted_turn_id = {
163 let mut rx = handle.rx_event.write().await;
164 loop {
165 let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
166 .await
167 .expect("timed out waiting for the submitted turn")
168 .expect("engine event");
169 if let Event::TurnStarted {
170 turn_id,
171 submission_id,
172 ..
173 } = event
174 {
175 assert_eq!(
176 submission_id.as_deref(),
177 Some("sub-host-1"),
178 "the submitted turn's TurnStarted must echo its correlation token"
179 );
180 break turn_id;
181 }
182 }
183 };
184 {
185 let mut rx = handle.rx_event.write().await;
186 loop {
187 let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
188 .await
189 .expect("timed out waiting for the submitted turn to complete")
190 .expect("engine event");
191 if let Event::TurnComplete {
192 turn_id,
193 submission_id,
194 compaction_id,
195 status,
196 error,
197 ..
198 } = event
199 {
200 assert_eq!(turn_id.as_deref(), Some(submitted_turn_id.as_str()));
201 assert_eq!(
202 submission_id.as_deref(),
203 Some("sub-host-1"),
204 "the submitted turn's terminal must echo its correlation token"
205 );
206 assert!(compaction_id.is_none());
207 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
208 break;
209 }
210 }
211 }
212
213 // An idle child completion self-starts the follow-up without any host
214 // submission; its start must not present a token.
215 completion_tx
216 .try_send(SubAgentCompletion {
217 owner_session_id,
218 agent_id: "idle-child".to_string(),
219 payload: "child finished its work".to_string(),
220 })
221 .expect("inject idle sub-agent completion");
222 let self_started_turn_id = {
223 let mut rx = handle.rx_event.write().await;
224 loop {
225 let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
226 .await
227 .expect("timed out waiting for the self-started turn")
228 .expect("engine event");
229 if let Event::TurnStarted {
230 turn_id,
231 submission_id,
232 ..
233 } = event
234 {
235 assert_ne!(
236 turn_id, submitted_turn_id,
237 "the idle child completion must self-start a new turn"
238 );
239 assert!(
240 submission_id.is_none(),
241 "a runtime self-started turn must not present a submission id"
242 );
243 break turn_id;
244 }
245 }
246 };
247 {
248 let mut rx = handle.rx_event.write().await;
249 loop {
250 let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
251 .await
252 .expect("timed out waiting for the self-started turn to complete")
253 .expect("engine event");
254 if let Event::TurnComplete {
255 turn_id,
256 submission_id,
257 compaction_id,
258 status,
259 error,
260 ..
261 } = event
262 {
263 assert_eq!(turn_id.as_deref(), Some(self_started_turn_id.as_str()));
264 assert!(
265 submission_id.is_none(),
266 "autonomous terminal must not inherit the preceding host token"
267 );
268 assert!(compaction_id.is_none());
269 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
270 break;
271 }
272 }
273 }
274
275 handle.send(Op::Shutdown).await.expect("shutdown engine");
276 run_task.await.expect("engine task");
277 assert_eq!(mock.call_count(), 2);
278 }
279
280 /// A composer shell turn never reaches the model; its terminal must still
281 /// carry its own turn id and nothing else — no host submission and no
282 /// compaction id.
283 #[tokio::test]
284 async fn composer_shell_terminal_carries_its_own_turn_and_nothing_else() {
285 use crate::llm_client::mock::MockLlmClient;
286
287 let workspace = tempdir().unwrap();
288 // The composer shell turn never reaches the model; the mock has no canned
289 // responses so any accidental dispatch fails loudly instead of passing.
290 let mock = Arc::new(MockLlmClient::new(vec![]));
291 let (engine, handle) = Engine::new_with_model_client(
292 deterministic_engine_config(workspace.path()),
293 &Config::default(),
294 mock.clone(),
295 );
296 let task = tokio::spawn(engine.run());
297 handle
298 .send(Op::RunShellCommand {
299 command: "echo composer-shell-terminal-attribution".to_string(),
300 mode: AppMode::Agent,
301 allow_shell: true,
302 trust_mode: false,
303 auto_approve: true,
304 approval_mode: ApprovalMode::Bypass,
305 })
306 .await
307 .expect("queue composer shell command");
308 {
309 let mut rx = handle.rx_event.write().await;
310 let started_turn_id = loop {
311 let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
312 .await
313 .expect("timed out waiting for the composer shell turn")
314 .expect("engine event");
315 if let Event::TurnStarted {
316 turn_id,
317 submission_id,
318 ..
319 } = event
320 {
321 assert!(
322 submission_id.is_none(),
323 "a composer shell turn has no host submission to echo"
324 );
325 break turn_id;
326 }
327 };
328 loop {
329 let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
330 .await
331 .expect("timed out waiting for the composer shell completion")
332 .expect("engine event");
333 if let Event::TurnComplete {
334 turn_id,
335 submission_id,
336 compaction_id,
337 status,
338 error,
339 ..
340 } = event
341 {
342 assert_eq!(turn_id.as_deref(), Some(started_turn_id.as_str()));
343 assert!(
344 submission_id.is_none(),
345 "a composer shell terminal must not present a submission id"
346 );
347 assert!(compaction_id.is_none());
348 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
349 break;
350 }
351 }
352 }
353 handle.send(Op::Shutdown).await.expect("shutdown engine");
354 task.await.expect("engine task");
355 assert_eq!(mock.call_count(), 0);
356 }
357
358 #[test]
359 fn idle_and_in_turn_subagent_delivery_claim_each_completion_once() {
360 use crate::tools::subagent::SubAgentCompletion;
361
362 let mut delivered = HashSet::new();
363 let first = SubAgentCompletion {
364 owner_session_id: "session-a".to_string(),
365 agent_id: "agent_same".to_string(),
366 payload: "first delivery".to_string(),
367 };
368 let duplicate = SubAgentCompletion {
369 owner_session_id: "session-a".to_string(),
370 agent_id: "agent_same".to_string(),
371 payload: "duplicate delivery".to_string(),
372 };
373 let second = SubAgentCompletion {
374 owner_session_id: "session-a".to_string(),
375 agent_id: "agent_other".to_string(),
376 payload: "other delivery".to_string(),
377 };
378
379 assert!(claim_subagent_completion(&mut delivered, first).is_some());
380 assert!(claim_subagent_completion(&mut delivered, duplicate).is_none());
381 assert!(claim_subagent_completion(&mut delivered, second).is_some());
382 assert_eq!(
383 delivered,
384 HashSet::from(["agent_same".to_string(), "agent_other".to_string()])
385 );
386 }
387
388 #[tokio::test]
389 async fn session_switch_drops_old_completion_before_deduplication() {
390 use crate::tools::subagent::SubAgentCompletion;
391
392 let workspace = tempdir().expect("tempdir");
393 let (mut engine, _handle) = Engine::new(
394 deterministic_engine_config(workspace.path()),
395 &Config::default(),
396 );
397 engine.session.id = "session-new".to_string();
398 let messages_before = engine.session.messages.len();
399
400 engine
401 .handle_idle_subagent_completion(SubAgentCompletion {
402 owner_session_id: "session-old".to_string(),
403 agent_id: "agent_same".to_string(),
404 payload: "foreign task state".to_string(),
405 })
406 .await;
407
408 assert_eq!(engine.session.messages.len(), messages_before);
409 assert!(engine.delivered_subagent_completion_ids.is_empty());
410 assert!(
411 claim_subagent_completion_for_session(
412 &mut engine.delivered_subagent_completion_ids,
413 "session-new",
414 SubAgentCompletion {
415 owner_session_id: "session-new".to_string(),
416 agent_id: "agent_same".to_string(),
417 payload: "current task state".to_string(),
418 },
419 )
420 .is_some(),
421 "the rejected foreign completion must not suppress the same id in the active session"
422 );
423 }
424
425 #[tokio::test]
426 async fn idle_subagent_delivery_releases_claim_when_route_fails_before_recording() {
427 use crate::tools::subagent::SubAgentCompletion;
428
429 let workspace = tempdir().expect("tempdir");
430 let api_config = Config::default().with_legacy_root(
431 Some("test-key".to_string()),
432 Some("http://127.0.0.1:1/v1".to_string()),
433 );
434 let (mut engine, _handle) =
435 Engine::new(deterministic_engine_config(workspace.path()), &api_config);
436 // Make the persisted exact identity structurally unresolvable. The
437 // completion is claimed before route resolution, so this exercises the
438 // early error branch before a transcript record can be written.
439 engine.api_provider = ProviderKind::Custom;
440 engine.api_provider_identity = None;
441
442 engine
443 .handle_idle_subagent_completion(SubAgentCompletion {
444 owner_session_id: engine.session.id.clone(),
445 agent_id: "agent_retryable".to_string(),
446 payload: "completed work".to_string(),
447 })
448 .await;
449
450 assert!(
451 !engine
452 .delivered_subagent_completion_ids
453 .contains("agent_retryable"),
454 "a completion that never reached the transcript must remain retryable"
455 );
456 let owner_session_id = engine.session.id.clone();
457 assert!(
458 claim_subagent_completion(
459 &mut engine.delivered_subagent_completion_ids,
460 SubAgentCompletion {
461 owner_session_id,
462 agent_id: "agent_retryable".to_string(),
463 payload: "retry".to_string(),
464 },
465 )
466 .is_some()
467 );
468 }
469
470 #[test]
471 fn subagent_mailbox_keeps_lifecycle_events_reliable() {
472 use crate::tools::subagent::MailboxMessage;
473 use codewhale_models::Usage;
474
475 assert!(subagent_mailbox_message_is_best_effort(
476 &MailboxMessage::progress("agent_a", "step 1")
477 ));
478 assert!(subagent_mailbox_message_is_best_effort(
479 &MailboxMessage::ToolCallStarted {
480 agent_id: "agent_a".to_string(),
481 tool_name: "read_file".to_string(),
482 step: 1,
483 }
484 ));
485 assert!(subagent_mailbox_message_is_best_effort(
486 &MailboxMessage::ToolCallCompleted {
487 agent_id: "agent_a".to_string(),
488 tool_name: "read_file".to_string(),
489 step: 1,
490 ok: true,
491 }
492 ));
493
494 assert!(!subagent_mailbox_message_is_best_effort(
495 &MailboxMessage::started("agent_a", codewhale_agent_contract::role::FleetRole::Scout)
496 ));
497 assert!(!subagent_mailbox_message_is_best_effort(
498 &MailboxMessage::Completed {
499 agent_id: "agent_a".to_string(),
500 summary: "done".to_string(),
501 }
502 ));
503 assert!(!subagent_mailbox_message_is_best_effort(
504 &MailboxMessage::Failed {
505 agent_id: "agent_a".to_string(),
506 error: "failed".to_string(),
507 }
508 ));
509 assert!(!subagent_mailbox_message_is_best_effort(
510 &MailboxMessage::TokenUsage {
511 record: None,
512 agent_id: "agent_a".to_string(),
513 source_id: "response-a".to_string(),
514 route: Box::new(crate::cost_status::EffectiveRouteEnvelope::capture(
515 None,
516 ProviderKind::Deepseek,
517 "deepseek",
518 "model",
519 Some(ProviderKind::Deepseek.provider().default_base_url()),
520 chrono::Utc::now(),
521 )),
522 usage: Usage::default(),
523 }
524 ));
525 }
526
527 #[test]
528 fn subagent_mailbox_samples_best_effort_events_per_agent() {
529 use crate::tools::subagent::MailboxMessage;
530
531 let mut last_sent_at = HashMap::new();
532 let start = Instant::now();
533 let first = MailboxMessage::ToolCallStarted {
534 agent_id: "agent_a".to_string(),
535 tool_name: "exec_shell".to_string(),
536 step: 1,
537 };
538 let second = MailboxMessage::ToolCallCompleted {
539 agent_id: "agent_a".to_string(),
540 tool_name: "exec_shell".to_string(),
541 step: 1,
542 ok: true,
543 };
544 let other_agent = MailboxMessage::ToolCallCompleted {
545 agent_id: "agent_b".to_string(),
546 tool_name: "exec_shell".to_string(),
547 step: 1,
548 ok: true,
549 };
550
551 assert!(subagent_mailbox_best_effort_send_permitted(
552 &mut last_sent_at,
553 &first,
554 start,
555 ));
556 assert!(
557 !subagent_mailbox_best_effort_send_permitted(
558 &mut last_sent_at,
559 &second,
560 start + Duration::from_millis(10),
561 ),
562 "same-agent telemetry inside the sampling window is dropped"
563 );
564 assert!(
565 subagent_mailbox_best_effort_send_permitted(
566 &mut last_sent_at,
567 &other_agent,
568 start + Duration::from_millis(10),
569 ),
570 "sampling is per agent, so one busy child cannot hide another"
571 );
572 assert!(
573 subagent_mailbox_best_effort_send_permitted(
574 &mut last_sent_at,
575 &second,
576 start + SUBAGENT_MAILBOX_BEST_EFFORT_MIN_INTERVAL,
577 ),
578 "the next same-agent update is allowed after the interval"
579 );
580 }
581
582 #[test]
583 fn subagent_mailbox_never_samples_lifecycle_or_usage_events() {
584 use crate::tools::subagent::MailboxMessage;
585 use codewhale_agent_contract::role::FleetRole;
586 use codewhale_models::Usage;
587
588 let mut last_sent_at = HashMap::new();
589 let start = Instant::now();
590
591 assert!(subagent_mailbox_best_effort_send_permitted(
592 &mut last_sent_at,
593 &MailboxMessage::started("agent_a", FleetRole::Scout),
594 start,
595 ));
596 assert!(subagent_mailbox_best_effort_send_permitted(
597 &mut last_sent_at,
598 &MailboxMessage::Completed {
599 agent_id: "agent_a".to_string(),
600 summary: "done".to_string(),
601 },
602 start,
603 ));
604 assert!(subagent_mailbox_best_effort_send_permitted(
605 &mut last_sent_at,
606 &MailboxMessage::TokenUsage {
607 record: None,
608 agent_id: "agent_a".to_string(),
609 source_id: "response-a".to_string(),
610 route: Box::new(crate::cost_status::EffectiveRouteEnvelope::capture(
611 None,
612 ProviderKind::Deepseek,
613 "deepseek",
614 "model",
615 Some(ProviderKind::Deepseek.provider().default_base_url()),
616 chrono::Utc::now(),
617 )),
618 usage: Usage::default(),
619 },
620 start,
621 ));
622 }
623
624 struct ScopedDeepSeekApiKey {
625 previous: Option<OsString>,
626 }
627
628 impl ScopedDeepSeekApiKey {
629 fn set(value: &str) -> Self {
630 let previous = std::env::var_os("DEEPSEEK_API_KEY");
631 // Safety: tests using this helper serialize with lock_test_env() and
632 // restore the original value in Drop.
633 unsafe {
634 std::env::set_var("DEEPSEEK_API_KEY", value);
635 }
636 Self { previous }
637 }
638 }
639
640 impl Drop for ScopedDeepSeekApiKey {
641 fn drop(&mut self) {
642 // Safety: tests using this helper serialize with lock_test_env().
643 unsafe {
644 if let Some(previous) = self.previous.take() {
645 std::env::set_var("DEEPSEEK_API_KEY", previous);
646 } else {
647 std::env::remove_var("DEEPSEEK_API_KEY");
648 }
649 }
650 }
651 }
652
653 fn catalog_tool(name: &str) -> Tool {
654 Tool {
655 tool_type: None,
656 name: name.to_string(),
657 description: String::new(),
658 input_schema: json!({"type": "object"}),
659 allowed_callers: None,
660 defer_loading: None,
661 input_examples: None,
662 strict: None,
663 cache_control: None,
664 }
665 }
666
667 #[test]
668 fn shell_denial_filters_search_catalog_without_expanding_allow_grants() {
669 let raw_names = [
670 "bash",
671 "Bash",
672 "exec_shell",
673 "task_shell_start",
674 "task_gate_run",
675 "terminal_run",
676 "terminal_send",
677 "terminal_reset",
678 "terminal/run",
679 "terminal/send",
680 "terminal/reset",
681 "exec_shell_interact",
682 "exec_interact",
683 "code_execution",
684 "rlm_eval",
685 "start_mcp_server",
686 "start_registry_mcp_server",
687 ];
688 for rule in ["Bash", "eXeC_sHeLl", "baSH*", "exec_shell*"] {
689 let surface = policy_for_catalog(
690 raw_names.into_iter().map(catalog_tool).collect(),
691 None,
692 Some(vec![rule.into()]),
693 );
694 for name in raw_names {
695 assert!(surface.denies_call(name, &json!({})), "{rule}: {name}");
696 assert!(
697 surface.catalog.iter().all(|tool| tool.name != name),
698 "{rule}: {name}"
699 );
700 }
701 }
702 let allowed = policy_for_catalog(
703 raw_names.into_iter().map(catalog_tool).collect(),
704 Some(vec!["Bash".into()]),
705 None,
706 );
707 for name in raw_names.into_iter().skip(3) {
708 assert!(
709 !allowed.passes_allow_list(name),
710 "Bash must not grant {name}"
711 );
712 }
713 }
714
715 #[test]
716 fn shell_denial_preserves_task_reads_and_denies_verification_actions() {
717 let mut tasks = catalog_tool("tasks");
718 tasks.input_schema =
719 json!({"type":"object", "properties":{"action":{"enum":["list", "read", "gate_run"]}}});
720 let surface = policy_for_catalog(
721 vec![
722 tasks,
723 catalog_tool("Run"),
724 catalog_tool("task_shell_wait"),
725 catalog_tool("terminal_cancel"),
726 catalog_tool("terminal/cancel"),
727 ],
728 None,
729 Some(vec!["Bash".into()]),
730 );
731 let tasks = surface
732 .catalog
733 .iter()
734 .find(|tool| tool.name == "tasks")
735 .unwrap();
736 assert_eq!(
737 tasks.input_schema["properties"]["action"]["enum"],
738 json!(["list", "read"])
739 );
740 assert!(!surface.denies_call("tasks", &json!({"action":"list"})));
741 assert!(surface.denies_call("tasks", &json!({"action":"gate_run"})));
742 assert!(!surface.denies_call("task_shell_wait", &json!({})));
743 assert!(!surface.denies_call("terminal_cancel", &json!({})));
744 assert!(!surface.denies_call("terminal/cancel", &json!({})));
745 for input in [
746 json!({"action":"tests"}),
747 json!({"action":"tests", "args":""}),
748 json!({"action":"tests", "args":"-p fixture selected_test"}),
749 json!({"action":"tests", "args":"--config build.rustc=malicious"}),
750 json!({"action":"verifiers"}),
751 json!({"action":"verifiers", "profile":"node"}),
752 ] {
753 assert!(surface.denies_call("Run", &input), "{input}");
754 }
755 for name in ["run_tests", "run_verifiers"] {
756 assert!(surface.denies_call(name, &json!({})), "{name}");
757 }
758 }
759
760 #[test]
761 fn shell_denial_covers_every_code_executing_action_or_names_an_exemption() {
762 use crate::tools::execution_envelope::{CallClass, classify_call, tool_call_denied};
763 use crate::tools::spec::ToolCapability;
764 use codewhale_agent_contract::worker_profile::ShellPolicy;
765
766 const EXEMPT: &[(&str, &str)] = &[
767 ("automation/pause", "stops a stored automation from firing"),
768 ("automation/delete", "removes a stored automation"),
769 ("send_later/cancel", "cancels a pending delayed message"),
770 ("tasks/cancel", "stops a durable task"),
771 ("tasks/suggest", "offers a task card and starts nothing"),
772 ("tasks/pr_attempt_record", "records a stored patch artifact"),
773 (
774 "tasks/pr_attempt_preflight",
775 "git apply --check of a stored patch",
776 ),
777 ("terminal_cancel", "stops an existing terminal session"),
778 ("terminal_wait", "reads an existing terminal session"),
779 (
780 "rlm/open",
781 "loads content into a context; running code in it is rlm/eval, and a url is gated by fetch_url",
782 ),
783 (
784 "workflow/start",
785 "runs sub-agents that inherit this deny list; verify and args.evaluator are denied by execution_envelope",
786 ),
787 (
788 "workflow/run",
789 "runs sub-agents that inherit this deny list; verify and args.evaluator are denied by execution_envelope",
790 ),
791 (
792 "workflow/cancel",
793 "stops a workflow run and starts nothing",
794 ),
795 ];
796 const EXECUTING_FLAGS: &[(&str, &str)] = &[("workflow", "verify")];
797
798 let tmp = tempdir().expect("tempdir");
799 let mut options = crate::tools::AgentToolSurfaceOptions::new(ShellPolicy::Full);
800 options.apply_patch_enabled = true;
801 options.web_search_enabled = true;
802 options.memory_tool_enabled = true;
803 let pool = std::sync::Arc::new(tokio::sync::Mutex::new(crate::mcp::McpPool::new(
804 codewhale_mcp::config::McpConfig::default(),
805 )));
806 let client = CodewhaleClient::new(
807 &Config::default().with_legacy_root(Some("test-key".to_string()), None),
808 )
809 .expect("stub client");
810 let manager = crate::tools::subagent::new_shared_subagent_manager(tmp.path().to_path_buf(), 4);
811 let runtime = SubAgentRuntime::new(
812 client.clone(),
813 "sweep-model".to_string(),
814 crate::tools::ToolContext::new(tmp.path().to_path_buf()),
815 true,
816 None,
817 manager.clone(),
818 );
819 let registry = crate::tools::ToolRegistryBuilder::new()
820 .with_full_agent_surface_options(
821 Some(client),
822 "sweep-model".to_string(),
823 manager,
824 runtime,
825 options,
826 crate::tools::todo::new_shared_todo_list(),
827 )
828 .with_registry_mcp_sync_tool()
829 .with_runtime_mcp_tool(pool.clone())
830 .with_registry_mcp_start_tool(pool)
831 .build(crate::tools::ToolContext::new(tmp.path().to_path_buf()));
832
833 let rules = vec!["Bash".to_string()];
834 for name in ["workflow", "agent", "Run"] {
835 assert!(
836 registry.all().iter().any(|tool| tool.name() == name),
837 "the sweep surface lacks {name}"
838 );
839 }
840 for (name, flag) in EXECUTING_FLAGS {
841 let tool = registry
842 .all()
843 .into_iter()
844 .find(|tool| tool.name() == *name)
845 .unwrap_or_else(|| panic!("{name} is not registered"));
846 assert_eq!(
847 tool.input_schema()
848 .pointer(&format!("/properties/{flag}/type"))
849 .and_then(Value::as_str),
850 Some("boolean"),
851 "{name} no longer declares a boolean {flag}"
852 );
853 assert!(
854 tool_call_denied(Some(&rules), name, &json!({"action":"run", (*flag): true})),
855 "{name} with {flag} starts workspace code and a Bash rule does not deny it"
856 );
857 }
858 let mut swept = 0usize;
859 let mut unaccounted = Vec::new();
860 let mut stale = Vec::new();
861 for tool in registry.all() {
862 let schema = tool.input_schema();
863 let actions: Vec<Option<String>> = schema
864 .pointer("/properties/action/enum")
865 .and_then(Value::as_array)
866 .map(|actions| {
867 actions
868 .iter()
869 .filter_map(|action| action.as_str().map(|action| Some(action.to_string())))
870 .collect()
871 })
872 .unwrap_or_else(|| vec![None]);
873 for action in actions {
874 let input = action
875 .as_ref()
876 .map_or_else(|| json!({}), |action| json!({"action": action}));
877 let label = match &action {
878 Some(action) => format!("{}/{action}", tool.name()),
879 None => tool.name().to_string(),
880 };
881 let denied = tool_call_denied(Some(&rules), tool.name(), &input);
882 let executes = tool.capabilities().contains(&ToolCapability::ExecutesCode)
883 && classify_call(tool.name(), &input, &*tool) != CallClass::Bounded;
884 let exempt = EXEMPT.iter().any(|(name, _)| *name == label);
885 if executes {
886 swept += 1;
887 }
888 if executes && !denied && !exempt {
889 unaccounted.push(label.clone());
890 }
891 if exempt && denied {
892 stale.push(label);
893 }
894 }
895 }
896 assert!(swept > 10, "the sweep found only {swept} executing actions");
897 assert!(
898 unaccounted.is_empty(),
899 "executing actions neither denied by a Bash rule nor exempt: {unaccounted:?}"
900 );
901 assert!(
902 stale.is_empty(),
903 "exempt actions a Bash rule already denies: {stale:?}"
904 );
905 }
906
907 #[test]
908 fn shell_denial_keeps_only_the_bounded_verifier_its_default_gate() {
909 use crate::tools::execution_envelope::{enforce_tool_denial, holds_bounded_verification};
910 use crate::tools::spec::{
911 ToolAuthorityEnvelope, ToolMutationAuthority, ToolShellAuthority,
912 ToolVerificationAuthority,
913 };
914 let tmp = tempdir().expect("tempdir");
915 let rules: Vec<String> = codewhale_agent_contract::role::RAW_SHELL_DENYLIST
916 .iter()
917 .map(|rule| (*rule).to_string())
918 .collect();
919
920 let mut operator = crate::tools::ToolContext::new(tmp.path().to_path_buf());
921 operator.disallowed_tools = rules.clone();
922 assert!(!holds_bounded_verification(&operator));
923
924 let mut verifier = crate::tools::ToolContext::new(tmp.path().to_path_buf())
925 .with_tool_authority(ToolAuthorityEnvelope {
926 schema_version: 1,
927 owner: "verifier-1".to_string(),
928 authority: ToolMutationAuthority::ReadOnly,
929 network_access: Some(false),
930 shell: ToolShellAuthority::None,
931 verification: ToolVerificationAuthority::Bounded,
932 writable_roots: Vec::new(),
933 writable_files: Vec::new(),
934 coordination_contracts: Vec::new(),
935 })
936 .expect("bounded verifier authority");
937 verifier.disallowed_tools = rules;
938 assert!(holds_bounded_verification(&verifier));
939
940 for input in [
941 json!({"action":"tests"}),
942 json!({"action":"tests", "args":"-p fixture selected_test"}),
943 json!({"action":"verifiers"}),
944 ] {
945 assert!(enforce_tool_denial(&operator, "Run", &input).is_err(), "{input}");
946 assert!(enforce_tool_denial(&verifier, "Run", &input).is_ok(), "{input}");
947 }
948 let unbounded = json!({"action":"tests", "args":"--config build.rustc=malicious"});
949 assert!(enforce_tool_denial(&operator, "Run", &unbounded).is_err());
950 assert!(enforce_tool_denial(&verifier, "Run", &unbounded).is_err());
951 let workflow_verify = json!({"action":"run", "script":"return 1;", "verify":true});
952 assert!(enforce_tool_denial(&operator, "workflow", &workflow_verify).is_err());
953 assert!(enforce_tool_denial(&verifier, "workflow", &workflow_verify).is_ok());
954 let workflow_evaluator = json!({
955 "action": "run",
956 "args": {
957 "strategy": "search",
958 "evaluator": {"manifestPath": "/trusted/evaluator.json"}
959 }
960 });
961 assert!(enforce_tool_denial(&operator, "workflow", &workflow_evaluator).is_err());
962 assert!(enforce_tool_denial(&verifier, "workflow", &workflow_evaluator).is_err());
963
964 let surface = ToolSurfacePolicy::new(
965 crate::tools::ToolRegistry::new(verifier.clone()),
966 Some(vec![catalog_tool("Run")]),
967 AppMode::Agent,
968 &HashSet::new(),
969 false,
970 None,
971 verifier.disallowed_tools.clone().into(),
972 None,
973 crate::core::engine::tool_catalog::ToolMode::Direct,
974 );
975 assert!(!surface.denies_call("Run", &json!({"action":"verifiers"})));
976 assert!(surface.denies_call("Run", &unbounded));
977 }
978
979 #[test]
980 fn shell_denial_covers_workflow_completion_verification_but_not_plain_runs() {
981 use crate::tools::execution_envelope::tool_call_denied;
982 let rules = vec!["Bash".to_string()];
983 for input in [
984 json!({"verify":true}),
985 json!({"action":"start", "verify":true}),
986 json!({"action":"spawn", "verify":true, "script":"return 1;"}),
987 json!({"action":"run", "verify":true, "script":"return 1;"}),
988 json!({"action":"wait", "verify":true}),
989 json!({"action":" RUN ", "verify":true}),
990 json!({"action":"run", "args":{"strategy":"search", "evaluator":{"manifestPath":"/trusted/evaluator.json"}}}),
991 json!({"action":"start", "args":{"evaluator":{"manifestPath":"/trusted/evaluator.json"}}}),
992 ] {
993 assert!(tool_call_denied(Some(&rules), "workflow", &input), "{input}");
994 }
995 for input in [
996 json!({"action":"run", "script":"return 1;"}),
997 json!({"action":"run", "verify":false}),
998 json!({"action":"run", "args":{"strategy":"search", "evaluator":null}}),
999 json!({"action":"status", "run_id":"workflow_1"}),
1000 json!({"action":"cancel", "run_id":"workflow_1"}),
1001 ] {
1002 assert!(!tool_call_denied(Some(&rules), "workflow", &input), "{input}");
1003 }
1004 assert!(!tool_call_denied(
1005 None,
1006 "workflow",
1007 &json!({"action":"run", "verify":true})
1008 ));
1009 }
1010
1011 #[test]
1012 fn shell_denial_covers_delayed_message_scheduling_but_not_its_management() {
1013 use crate::tools::execution_envelope::tool_call_denied;
1014 let rules = vec!["Bash".to_string()];
1015 assert!(tool_call_denied(
1016 Some(&rules),
1017 "send_later",
1018 &json!({"action":"schedule", "delay_minutes":5, "message":"go", "thread_id":""})
1019 ));
1020 for action in ["list", "read", "cancel"] {
1021 assert!(
1022 !tool_call_denied(Some(&rules), "send_later", &json!({"action": action})),
1023 "{action}"
1024 );
1025 }
1026 assert!(!tool_call_denied(
1027 None,
1028 "send_later",
1029 &json!({"action":"schedule"})
1030 ));
1031 }
1032
1033 #[test]
1034 fn shell_denial_applies_to_new_durable_execution_without_hiding_management() {
1035 use crate::tools::execution_envelope::tool_call_denied;
1036 let rules = vec!["Bash".to_string()];
1037 for (family, actions) in [
1038 ("tasks", vec!["create", "gate_run"]),
1039 ("automation", vec!["create", "update", "resume", "run"]),
1040 ] {
1041 for action in actions {
1042 assert!(
1043 tool_call_denied(Some(&rules), family, &json!({"action": action})),
1044 "{family}/{action}"
1045 );
1046 }
1047 }
1048 for (family, actions) in [
1049 ("tasks", vec!["list", "read", "cancel"]),
1050 ("automation", vec!["list", "read", "pause", "delete"]),
1051 ] {
1052 for action in actions {
1053 assert!(
1054 !tool_call_denied(Some(&rules), family, &json!({"action": action})),
1055 "{family}/{action}"
1056 );
1057 }
1058 }
1059 let fetch_rules = vec!["fetch_url".to_string()];
1060 for family in ["rlm", "rlm_open"] {
1061 assert!(tool_call_denied(
1062 Some(&fetch_rules),
1063 family,
1064 &json!({"action":"open", "url":"https://example.com/document"})
1065 ));
1066 assert!(!tool_call_denied(
1067 Some(&fetch_rules),
1068 family,
1069 &json!({"action":"open", "content":"local fixture"})
1070 ));
1071 }
1072 }
1073
1074 fn policy_for_catalog(
1075 catalog: Vec<Tool>,
1076 allowed_tools: Option<Vec<String>>,
1077 disallowed_tools: Option<Vec<String>>,
1078 ) -> ToolSurfacePolicy {
1079 ToolSurfacePolicy::new(
1080 crate::tools::ToolRegistry::new(crate::tools::ToolContext::new(PathBuf::from("."))),
1081 Some(catalog),
1082 AppMode::Agent,
1083 &HashSet::new(),
1084 false,
1085 allowed_tools,
1086 disallowed_tools,
1087 None,
1088 crate::core::engine::tool_catalog::ToolMode::Direct,
1089 )
1090 }
1091
1092 #[test]
1093 fn tool_catalog_scenario() {
1094 // Scenario consolidation of: tool_catalog_filter_applies_allow_and_deny_gates, tool_catalog_filter_is_inert_without_gates
1095 // from tool_catalog_filter_applies_allow_and_deny_gates
1096 {
1097 // #3027 AC1: the advertised catalog must not contain tools the execution
1098 // gates would deny; deny wins over allow.
1099 let catalog = vec![
1100 catalog_tool("read_file"),
1101 catalog_tool("exec_shell"),
1102 catalog_tool("grep_files"),
1103 ];
1104 let surface = policy_for_catalog(
1105 catalog,
1106 Some(vec!["read_file".to_string(), "exec_shell".to_string()]),
1107 Some(vec!["exec_shell".to_string()]),
1108 );
1109 let names: Vec<&str> = surface.catalog.iter().map(|t| t.name.as_str()).collect();
1110 assert_eq!(names, ["read_file"]);
1111 }
1112 // from tool_catalog_filter_is_inert_without_gates
1113 {
1114 let surface = policy_for_catalog(
1115 vec![catalog_tool("read_file"), catalog_tool("exec_shell")],
1116 None,
1117 None,
1118 );
1119 assert!(surface.catalog.iter().any(|tool| tool.name == "read_file"));
1120 assert!(surface.catalog.iter().any(|tool| tool.name == "exec_shell"));
1121 }
1122 }
1123
1124 #[test]
1125 fn tool_catalog_shell_only_benchmark_surface_hides_native_tools() {
1126 let catalog = vec![
1127 catalog_tool("exec_shell"),
1128 catalog_tool("exec_shell_wait"),
1129 catalog_tool("exec_shell_interact"),
1130 catalog_tool("read_file"),
1131 catalog_tool("write_file"),
1132 catalog_tool("list_dir"),
1133 catalog_tool("git_status"),
1134 catalog_tool("work_update"),
1135 ];
1136 let shell_only = [
1137 "exec_shell".to_string(),
1138 "exec_shell_wait".to_string(),
1139 "exec_shell_interact".to_string(),
1140 ];
1141
1142 let surface = policy_for_catalog(catalog, Some(shell_only.to_vec()), None);
1143
1144 let names: Vec<&str> = surface.catalog.iter().map(|t| t.name.as_str()).collect();
1145 assert_eq!(
1146 names,
1147 ["exec_shell", "exec_shell_wait", "exec_shell_interact"]
1148 );
1149 }
1150
1151 #[test]
1152 fn tool_surface_policy_never_reintroduces_denied_synthetic_tools() {
1153 let denied = vec![
1154 TOOL_SEARCH_NAME.to_string(),
1155 CODE_EXECUTION_TOOL_NAME.to_string(),
1156 ];
1157 let surface = policy_for_catalog(
1158 vec![
1159 catalog_tool("read_file"),
1160 catalog_tool(CODE_EXECUTION_TOOL_NAME),
1161 ],
1162 Some(vec![
1163 TOOL_SEARCH_NAME.to_string(),
1164 CODE_EXECUTION_TOOL_NAME.to_string(),
1165 ]),
1166 Some(denied),
1167 );
1168
1169 for denied_name in [TOOL_SEARCH_NAME, CODE_EXECUTION_TOOL_NAME] {
1170 assert!(surface.denies_tool(denied_name));
1171 assert!(surface.passes_allow_list(denied_name));
1172 assert!(
1173 !surface.allows_tool(denied_name),
1174 "deny must win over allow for {denied_name}"
1175 );
1176 assert!(
1177 surface.catalog.iter().all(|tool| tool.name != denied_name),
1178 "{denied_name} must not reappear after policy narrowing"
1179 );
1180 assert!(!surface.active_names.contains(denied_name));
1181 }
1182 }
1183
1184 #[tokio::test]
1185 async fn denied_synthetic_tool_is_blocked_by_the_same_turn_policy_at_execution() {
1186 use crate::llm_client::mock::{MockLlmClient, canned};
1187
1188 let workspace = tempdir().expect("tempdir");
1189 let mock = std::sync::Arc::new(MockLlmClient::new(vec![
1190 canned::tool_call_turn(
1191 "call-denied-search",
1192 TOOL_SEARCH_NAME,
1193 r#"{"query":"File"}"#,
1194 ),
1195 canned::simple_text_turn("Denied tool handled."),
1196 ]));
1197 let client: crate::core::model_client::SharedModelClient = mock;
1198 let (mut engine, handle) = Engine::new_with_model_client(
1199 deterministic_engine_config(workspace.path()),
1200 &Config::default(),
1201 client,
1202 );
1203 let policy = policy_for_catalog(
1204 vec![catalog_tool("read_file")],
1205 Some(vec![TOOL_SEARCH_NAME.to_string()]),
1206 Some(vec![TOOL_SEARCH_NAME.to_string()]),
1207 );
1208 assert!(!policy.allows_tool(TOOL_SEARCH_NAME));
1209 let mut turn = crate::core::turn::TurnContext::new(4);
1210
1211 let (status, error) = engine.run_turn(&mut turn, policy, None, None).await;
1212 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
1213
1214 let mut events = handle.rx_event.write().await;
1215 let denied = std::iter::from_fn(|| events.try_recv().ok()).find_map(|event| match event {
1216 Event::ToolCallComplete { name, result, .. } if name == TOOL_SEARCH_NAME => Some(result),
1217 _ => None,
1218 });
1219 let error = denied
1220 .expect("denied synthetic tool completion")
1221 .expect_err("denied synthetic tool must not execute");
1222 assert!(
1223 error.to_string().contains("disallowed-tools list"),
1224 "{error:?}"
1225 );
1226 }
1227
1228 #[tokio::test]
1229 async fn healthy_owned_children_do_not_force_another_parent_model_turn() {
1230 use crate::llm_client::mock::{MockLlmClient, canned};
1231
1232 for max_steps in [1, 4] {
1233 let workspace = tempdir().expect("tempdir");
1234 let mock = Arc::new(MockLlmClient::new(vec![
1235 canned::simple_text_turn("The workflow is running; I will report its result."),
1236 canned::tool_call_turn("must-not-run", "read_file", r#"{"path":"state.txt"}"#),
1237 ]));
1238 let client: crate::core::model_client::SharedModelClient = mock.clone();
1239 let config = EngineConfig {
1240 max_steps,
1241 ..deterministic_engine_config(workspace.path())
1242 };
1243 let (mut engine, _handle) =
1244 Engine::new_with_model_client(config, &Config::default(), client);
1245 let registry = crate::tools::ToolRegistry::new(crate::tools::ToolContext::new(
1246 workspace.path().to_path_buf(),
1247 ));
1248 let surface = test_tool_surface(&engine, registry, None, AppMode::Agent);
1249 let children = Arc::new(ForegroundChildRegistry::new());
1250 let child_cancel = CancellationToken::new();
1251 let registration = children
1252 .register(child_cancel.clone(), "agent_child")
1253 .expect("child registered");
1254 let mut turn = crate::core::turn::TurnContext::new(max_steps);
1255
1256 let (status, error) = engine
1257 .run_turn(&mut turn, surface, Some(Arc::clone(&children)), None)
1258 .await;
1259
1260 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
1261 assert_eq!(mock.call_count(), 1, "no forced coordination request");
1262 assert_eq!(mock.remaining_turns(), 1, "extra tool turn remains unused");
1263 assert_eq!(children.active_count(), 1);
1264 assert!(!child_cancel.is_cancelled());
1265 assert!(!engine.session.messages.iter().any(|message| {
1266 message.content.iter().any(|block| {
1267 matches!(block, ContentBlock::Text { text, .. }
1268 if text.contains("turn_owned_children_active"))
1269 })
1270 }));
1271 drop(registration);
1272 }
1273 }
1274
1275 #[tokio::test]
1276 async fn user_steer_during_parent_answer_still_gets_a_reply_with_healthy_children() {
1277 use crate::core::model_client::ModelClient;
1278 use crate::llm_client::mock::{MockLlmClient, canned};
1279 use std::sync::atomic::{AtomicUsize, Ordering};
1280
1281 struct SteeredClient {
1282 mock: Arc<MockLlmClient>,
1283 requests: StdMutex<Vec<codewhale_models::MessageRequest>>,
1284 calls: AtomicUsize,
1285 opening: bool,
1286 first_events: Vec<StreamEvent>,
1287 entered: Arc<tokio::sync::Notify>,
1288 dropped: Arc<std::sync::atomic::AtomicBool>,
1289 }
1290 #[async_trait::async_trait]
1291 impl ModelClient for SteeredClient {
1292 fn provider_name(&self) -> &str {
1293 "mock"
1294 }
1295 fn model(&self) -> &str {
1296 "mock-model"
1297 }
1298 async fn create_message(
1299 &self,
1300 request: codewhale_models::MessageRequest,
1301 ) -> anyhow::Result<codewhale_models::MessageResponse> {
1302 ModelClient::create_message(self.mock.as_ref(), request).await
1303 }
1304 async fn create_message_stream(
1305 &self,
1306 request: codewhale_models::MessageRequest,
1307 ) -> anyhow::Result<crate::llm_client::StreamEventBox> {
1308 self.requests.lock().unwrap().push(request.clone());
1309 if self.calls.fetch_add(1, Ordering::SeqCst) == 0 {
1310 let drop_signal = DropSignal(Arc::clone(&self.dropped));
1311 if self.opening {
1312 self.entered.notify_one();
1313 let _drop_signal = drop_signal;
1314 return std::future::pending().await;
1315 }
1316 let events = self.first_events.clone();
1317 let entered = Arc::clone(&self.entered);
1318 return Ok(Box::pin(async_stream::try_stream! {
1319 let _drop_signal = drop_signal;
1320 for event in events { yield event; }
1321 entered.notify_one();
1322 std::future::pending::<()>().await;
1323 }));
1324 }
1325 ModelClient::create_message_stream(self.mock.as_ref(), request).await
1326 }
1327 async fn health_check(&self) -> anyhow::Result<bool> {
1328 Ok(true)
1329 }
1330 }
1331
1332 for phase in ["opening", "silent", "reasoning", "text", "partial_tool"] {
1333 let workspace = tempdir().expect("tempdir");
1334 fs::write(workspace.path().join("state.txt"), "steer-proof\n").expect("fixture");
1335 let mock = Arc::new(MockLlmClient::new(vec![
1336 canned::tool_call_turn("call-steer-read", "read_file", r#"{"path":"state.txt"}"#),
1337 canned::simple_text_turn("The user-requested evidence is steer-proof."),
1338 ]));
1339 let first_events = match phase {
1340 "reasoning" => vec![
1341 canned::message_start("interrupted"),
1342 StreamEvent::ContentBlockStart {
1343 index: 0,
1344 content_block: codewhale_models::ContentBlockStart::Thinking {
1345 thinking: String::new(),
1346 },
1347 },
1348 canned::thinking_delta(0, "unfinished reasoning"),
1349 ],
1350 "text" => vec![
1351 canned::message_start("interrupted"),
1352 canned::text_block_start(0),
1353 canned::text_delta(0, "The workflow is still running."),
1354 ],
1355 "partial_tool" => vec![
1356 canned::message_start("interrupted"),
1357 canned::tool_use_block_start(0, "call-must-not-run", "read_file"),
1358 canned::tool_input_delta(0, r#"{"path":"state.txt""#),
1359 ],
1360 _ => Vec::new(),
1361 };
1362 let entered = Arc::new(tokio::sync::Notify::new());
1363 let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false));
1364 let client = Arc::new(SteeredClient {
1365 mock: Arc::clone(&mock),
1366 requests: StdMutex::new(Vec::new()),
1367 calls: AtomicUsize::new(0),
1368 opening: phase == "opening",
1369 first_events,
1370 entered: Arc::clone(&entered),
1371 dropped: Arc::clone(&dropped),
1372 });
1373 let (mut engine, handle) = Engine::new_with_model_client(
1374 deterministic_engine_config(workspace.path()),
1375 &Config::default(),
1376 client.clone(),
1377 );
1378 let mut registry = crate::tools::ToolRegistry::new(crate::tools::ToolContext::new(
1379 workspace.path().to_path_buf(),
1380 ));
1381 registry.register(Arc::new(crate::tools::file::ReadFileTool));
1382 let tools = Some(registry.to_api_tools_with_cache(true));
1383 let surface = test_tool_surface(&engine, registry, tools, AppMode::Agent);
1384 let children = Arc::new(ForegroundChildRegistry::new());
1385 let child_cancel = CancellationToken::new();
1386 let registration = children
1387 .register(child_cancel.clone(), "agent_child")
1388 .expect("child registered");
1389 let mut turn = crate::core::turn::TurnContext::new(8);
1390 let steer = async {
1391 entered.notified().await;
1392 let turn_id = handle
1393 .turn_controls
1394 .lock()
1395 .unwrap()
1396 .active
1397 .as_ref()
1398 .map(|control| control.id);
1399 let (outcome, accepted) = tokio::sync::oneshot::channel();
1400 handle
1401 .tx_steer
1402 .send(handle::SteerInput {
1403 replace_pending: false,
1404 turn_id,
1405 content: "Also read state.txt and include its evidence.".to_string(),
1406 person_text: None,
1407 outcome: Some(outcome),
1408 owner_steer: false,
1409 })
1410 .await
1411 .expect("steer channel open");
1412 let outcome = tokio::time::timeout(Duration::from_secs(5), accepted)
1413 .await
1414 .unwrap_or_else(|_| {
1415 panic!("{phase}: steering must preempt an indefinitely silent request")
1416 })
1417 .unwrap();
1418 assert_eq!(outcome, handle::SteerOutcome::Accepted);
1419 assert!(
1420 dropped.load(Ordering::SeqCst),
1421 "{phase}: obsolete request must close before steer acceptance"
1422 );
1423 };
1424 let ((status, error), ()) = tokio::time::timeout(Duration::from_secs(60), async {
1425 tokio::join!(
1426 engine.run_turn(&mut turn, surface, Some(Arc::clone(&children)), None),
1427 steer
1428 )
1429 })
1430 .await
1431 .unwrap_or_else(|_| panic!("{phase}: steered turn must finish"));
1432 assert_eq!(status, TurnOutcomeStatus::Completed, "{phase}: {error:?}");
1433 assert_eq!(client.calls.load(Ordering::SeqCst), 3, "{phase}");
1434 let requests = client.requests.lock().unwrap().clone();
1435 assert!(requests[1].messages.iter().any(|message| message.content.iter().any(|block| {
1436 matches!(block, ContentBlock::Text { text, .. } if text.contains("Also read state.txt and include its evidence."))
1437 })), "{phase}");
1438 assert!(requests[2].messages.iter().any(|message| message.content.iter().any(|block| {
1439 matches!(block, ContentBlock::ToolResult { tool_use_id, .. } if tool_use_id == "call-steer-read")
1440 })), "{phase}");
1441 assert!(
1442 requests.iter().all(|request| {
1443 request.messages.iter().all(|message| {
1444 message.content.iter().all(|block| {
1445 !matches!(block, ContentBlock::ToolUse { id, .. } if id == "call-must-not-run")
1446 })
1447 })
1448 }),
1449 "{phase}"
1450 );
1451 assert!(
1452 !serde_json::to_string(&requests[1])
1453 .unwrap()
1454 .contains("unfinished reasoning"),
1455 "{phase}"
1456 );
1457 assert_eq!(
1458 requests[0].system, requests[1].system,
1459 "{phase}: pinned system prefix changed"
1460 );
1461 let mut events = handle.rx_event.write().await;
1462 let events = std::iter::from_fn(|| events.try_recv().ok()).collect::<Vec<_>>();
1463 assert!(events.iter().all(|event| !matches!(event, Event::ToolCallStarted { model_call: Some(call), .. } if call.provider_id == "call-must-not-run")), "{phase}");
1464 assert!(events.iter().any(|event| matches!(event, Event::ProviderRequestReceipt { receipt } if receipt["outcome"] == if phase == "opening" { "steered_before_stream" } else { "steered" })), "{phase}");
1465 if phase == "text" {
1466 assert!(
1467 engine
1468 .session
1469 .messages
1470 .iter()
1471 .any(|message| message.role == Role::InterruptedAssistant)
1472 );
1473 }
1474 assert_eq!(children.active_count(), 1);
1475 assert!(!child_cancel.is_cancelled());
1476 assert_eq!(mock.remaining_turns(), 0);
1477 drop(registration);
1478 }
1479 }
1480
1481 /// Compose one assistant turn that proposes `calls` as a single parallel
1482 /// tool-call batch: `(call_id, tool_name, args_json)` per block, in order.
1483 fn tool_batch_turn(calls: &[(&str, &str, &str)]) -> Vec<codewhale_models::StreamEvent> {
1484 use crate::llm_client::mock::canned;
1485
1486 let mut events = vec![canned::message_start("mock_tool_batch")];
1487 for (index, (call_id, tool_name, args_json)) in calls.iter().enumerate() {
1488 let index = u32::try_from(index).expect("test batch index fits u32");
1489 events.push(canned::tool_use_block_start(index, call_id, tool_name));
1490 events.push(canned::tool_input_delta(index, args_json));
1491 events.push(canned::block_stop(index));
1492 }
1493 events.push(canned::message_delta("tool_use", None));
1494 events.push(canned::message_stop());
1495 events
1496 }
1497
1498 /// Drive one engine turn against the scripted `mock` turns with a registry
1499 /// that only serves `read_file`, collecting every `ToolCallComplete` event as
1500 /// `(call_id, result)` in emission order.
1501 async fn run_budgeted_read_turn(
1502 workspace: &Path,
1503 max_tool_calls: Option<u32>,
1504 mock: std::sync::Arc<crate::llm_client::mock::MockLlmClient>,
1505 ) -> (
1506 TurnOutcomeStatus,
1507 Option<String>,
1508 Vec<(String, Result<ToolResult, ToolError>)>,
1509 ) {
1510 let mut engine_config = deterministic_engine_config(workspace);
1511 engine_config.max_tool_calls = max_tool_calls;
1512 let client: crate::core::model_client::SharedModelClient = mock;
1513 let (mut engine, handle) =
1514 Engine::new_with_model_client(engine_config, &Config::default(), client);
1515 let context = crate::tools::ToolContext::new(workspace.to_path_buf());
1516 let mut registry = crate::tools::ToolRegistry::new(context);
1517 registry.register(std::sync::Arc::new(crate::tools::file::ReadFileTool));
1518 let tools = Some(registry.to_api_tools_with_cache(true));
1519 let surface = test_tool_surface(&engine, registry, tools, AppMode::Agent);
1520 let mut turn = crate::core::turn::TurnContext::new(4);
1521
1522 let (status, error) = engine.run_turn(&mut turn, surface, None, None).await;
1523 let mut events = handle.rx_event.write().await;
1524 let completions = std::iter::from_fn(|| events.try_recv().ok())
1525 .filter_map(|event| match event {
1526 Event::ToolCallComplete {
1527 model_call: Some(model_call),
1528 result,
1529 ..
1530 } => Some((model_call.provider_id, result)),
1531 _ => None,
1532 })
1533 .collect::<Vec<_>>();
1534 (status, error, completions)
1535 }
1536
1537 #[tokio::test]
1538 async fn provider_id_reuse_mints_distinct_execution_identity_in_all_dispatch_modes() {
1539 use crate::llm_client::mock::{MockLlmClient, canned};
1540 use crate::tools::spec::{ToolCapability, ToolSpec};
1541
1542 struct IdentityTool {
1543 parallel: bool,
1544 observed: Arc<StdMutex<Vec<String>>>,
1545 }
1546 #[async_trait::async_trait]
1547 impl ToolSpec for IdentityTool {
1548 fn name(&self) -> &str {
1549 "fixture_identity"
1550 }
1551 fn description(&self) -> &str {
1552 "Record the admitted execution identity."
1553 }
1554 fn input_schema(&self) -> Value {
1555 json!({"type": "object"})
1556 }
1557 fn capabilities(&self) -> Vec<ToolCapability> {
1558 vec![ToolCapability::ReadOnly]
1559 }
1560 fn supports_parallel(&self) -> bool {
1561 self.parallel
1562 }
1563 async fn execute(&self, _: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
1564 let id = context
1565 .origin_tool_call_id
1566 .as_ref()
1567 .expect("host origin")
1568 .clone();
1569 self.observed.lock().unwrap().push(id.clone());
1570 Ok(ToolResult::success(id))
1571 }
1572 }
1573 for parallel in [false, true] {
1574 let workspace = tempdir().unwrap();
1575 let calls = [
1576 ("reused", "fixture_identity", "{}"),
1577 ("peer", "fixture_identity", "{}"),
1578 ];
1579 let mock = Arc::new(MockLlmClient::new(vec![
1580 tool_batch_turn(&calls),
1581 tool_batch_turn(&calls),
1582 canned::simple_text_turn("done"),
1583 ]));
1584 let (mut engine, handle) = Engine::new_with_model_client(
1585 deterministic_engine_config(workspace.path()),
1586 &Config::default(),
1587 mock.clone(),
1588 );
1589 let observed = Arc::new(StdMutex::new(Vec::new()));
1590 let mut registry =
1591 crate::tools::ToolRegistry::new(ToolContext::new(workspace.path().to_path_buf()));
1592 registry.register(Arc::new(IdentityTool {
1593 parallel,
1594 observed: observed.clone(),
1595 }));
1596 let tools = Some(registry.to_api_tools_with_cache(true));
1597 let surface = test_tool_surface(&engine, registry, tools, AppMode::Agent);
1598 let mut turn = crate::core::turn::TurnContext::new(4);
1599 let (status, error) = engine.run_turn(&mut turn, surface, None, None).await;
1600 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
1601 let ids: HashSet<_> = observed.lock().unwrap().iter().cloned().collect();
1602 assert_eq!(ids.len(), 4);
1603 assert!(ids.iter().all(|id| uuid::Uuid::parse_str(id).is_ok()));
1604 let mut starts = HashMap::new();
1605 let mut completes = HashMap::new();
1606 let mut events = handle.rx_event.write().await;
1607 while let Ok(event) = events.try_recv() {
1608 match event {
1609 Event::ToolCallStarted {
1610 id,
1611 model_call: Some(correlation),
1612 ..
1613 } => {
1614 assert!(starts.insert(id, correlation).is_none());
1615 }
1616 Event::ToolCallComplete {
1617 id,
1618 model_call: Some(correlation),
1619 result,
1620 ..
1621 } => {
1622 assert_eq!(result.unwrap().content, id);
1623 assert!(completes.insert(id, correlation).is_none());
1624 }
1625 _ => {}
1626 }
1627 }
1628 assert_eq!(starts, completes);
1629 assert_eq!(starts.keys().cloned().collect::<HashSet<_>>(), ids);
1630 let requests = mock.captured_requests();
1631 let history = &requests[2].messages;
1632 let mut pairs = HashMap::<String, (usize, usize)>::new();
1633 for block in history.iter().flat_map(|message| &message.content) {
1634 match block {
1635 ContentBlock::ToolUse {
1636 id,
1637 execution_id: Some(local),
1638 ..
1639 } => {
1640 assert_eq!(starts[local].provider_id, *id);
1641 pairs.entry(local.clone()).or_default().0 += 1;
1642 }
1643 ContentBlock::ToolResult {
1644 tool_use_id,
1645 execution_id: Some(local),
1646 ..
1647 } => {
1648 assert_eq!(starts[local].provider_id, *tool_use_id);
1649 pairs.entry(local.clone()).or_default().1 += 1;
1650 }
1651 _ => {}
1652 }
1653 }
1654 assert_eq!(pairs.len(), 4);
1655 assert!(pairs.values().all(|pair| *pair == (1, 1)));
1656 }
1657 }
1658
1659 #[tokio::test]
1660 async fn invalid_provider_tool_batch_is_rejected_before_observation_or_history() {
1661 use crate::llm_client::mock::MockLlmClient;
1662 for ids in [["duplicate", "duplicate"], ["valid", ""], ["valid", " "]] {
1663 let workspace = tempdir().unwrap();
1664 let mock = Arc::new(MockLlmClient::new(vec![tool_batch_turn(&[
1665 (ids[0], "read_file", r#"{"path":"never-read"}"#),
1666 (ids[1], "read_file", r#"{"path":"never-read"}"#),
1667 ])]));
1668 let (mut engine, handle) = Engine::new_with_model_client(
1669 deterministic_engine_config(workspace.path()),
1670 &Config::default(),
1671 mock.clone(),
1672 );
1673 let mut registry =
1674 crate::tools::ToolRegistry::new(ToolContext::new(workspace.path().to_path_buf()));
1675 registry.register(Arc::new(crate::tools::file::ReadFileTool));
1676 let tools = Some(registry.to_api_tools_with_cache(true));
1677 let surface = test_tool_surface(&engine, registry, tools, AppMode::Agent);
1678 let mut turn = crate::core::turn::TurnContext::new(4);
1679 let (status, error) = engine.run_turn(&mut turn, surface, None, None).await;
1680 assert_eq!(status, TurnOutcomeStatus::Failed);
1681 assert!(error.unwrap().contains("pairing id"));
1682 assert_eq!(mock.call_count(), 1);
1683 let mut events = handle.rx_event.write().await;
1684 while let Ok(event) = events.try_recv() {
1685 assert!(!matches!(
1686 event,
1687 Event::ToolCallStarted { .. }
1688 | Event::ToolCallComplete { .. }
1689 | Event::ApprovalRequired { .. }
1690 | Event::ToolGateDecision { .. }
1691 ));
1692 }
1693 assert!(
1694 !engine
1695 .session
1696 .messages
1697 .iter()
1698 .flat_map(|message| &message.content)
1699 .any(|block| matches!(
1700 block,
1701 ContentBlock::ToolUse { .. } | ContentBlock::ToolResult { .. }
1702 ))
1703 );
1704 }
1705 }
1706
1707 /// B1: tool output is redacted once, as it enters the transcript, so the
1708 /// session messages (and the session JSON built from them) never hold a live
1709 /// credential a tool printed.
1710 #[tokio::test]
1711 async fn tool_output_credentials_are_redacted_when_they_enter_the_transcript() {
1712 use crate::llm_client::mock::{MockLlmClient, canned};
1713
1714 const TOKEN: &str = "sk-ant-oat01-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789abcdefghij";
1715 let workspace = tempdir().expect("tempdir");
1716 fs::write(
1717 workspace.path().join("auth.json"),
1718 format!("{{\n \"access_token\": \"{TOKEN}\",\n \"note\": \"keep me\"\n}}\n"),
1719 )
1720 .expect("write fixture");
1721 let mock = std::sync::Arc::new(MockLlmClient::new(vec![
1722 canned::tool_call_turn("call-read", "read_file", r#"{"path":"auth.json"}"#),
1723 canned::simple_text_turn("done"),
1724 ]));
1725 let client: crate::core::model_client::SharedModelClient = mock;
1726 let (mut engine, _handle) = Engine::new_with_model_client(
1727 deterministic_engine_config(workspace.path()),
1728 &Config::default(),
1729 client,
1730 );
1731 let context = crate::tools::ToolContext::new(workspace.path().to_path_buf());
1732 let mut registry = crate::tools::ToolRegistry::new(context);
1733 registry.register(std::sync::Arc::new(crate::tools::file::ReadFileTool));
1734 let tools = Some(registry.to_api_tools_with_cache(true));
1735 let surface = test_tool_surface(&engine, registry, tools, AppMode::Agent);
1736 let mut turn = crate::core::turn::TurnContext::new(4);
1737 let (status, error) = engine.run_turn(&mut turn, surface, None, None).await;
1738 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
1739
1740 let stored = engine
1741 .session
1742 .messages
1743 .iter()
1744 .flat_map(|message| message.content.iter())
1745 .find_map(|block| match block {
1746 ContentBlock::ToolResult { content, .. } => Some(content.clone()),
1747 _ => None,
1748 })
1749 .expect("the read result is in the transcript");
1750 assert!(!stored.contains(TOKEN), "{stored}");
1751 assert!(stored.contains("keep me"), "ordinary bytes stay: {stored}");
1752 let serialized = serde_json::to_string(&engine.session.messages.iter().collect::<Vec<_>>())
1753 .expect("serialize");
1754 assert!(!serialized.contains(TOKEN));
1755 }
1756
1757 /// #4415 AC(a): an 8-call cap admits exactly 8 calls; the 9th is rejected
1758 /// with the typed reason carrying `remaining=0` and is never executed.
1759 #[tokio::test]
1760 async fn tool_call_budget_admits_exactly_the_cap_and_rejects_the_ninth() {
1761 use crate::llm_client::mock::{MockLlmClient, canned};
1762
1763 let workspace = tempdir().expect("tempdir");
1764 let mut calls = Vec::new();
1765 for index in 1..=9 {
1766 let name = format!("fixture-{index}.txt");
1767 fs::write(workspace.path().join(&name), format!("fixture-{index}\n"))
1768 .expect("write fixture");
1769 calls.push((
1770 format!("call-{index}"),
1771 "read_file".to_string(),
1772 format!(r#"{{"path":"{name}"}}"#),
1773 ));
1774 }
1775 let call_refs = calls
1776 .iter()
1777 .map(|(id, name, args)| (id.as_str(), name.as_str(), args.as_str()))
1778 .collect::<Vec<_>>();
1779 let mock = std::sync::Arc::new(MockLlmClient::new(vec![
1780 tool_batch_turn(&call_refs),
1781 canned::simple_text_turn("done"),
1782 ]));
1783
1784 let (status, error, completions) =
1785 run_budgeted_read_turn(workspace.path(), Some(8), mock.clone()).await;
1786 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
1787 assert_eq!(mock.call_count(), 2, "batch turn then the final text turn");
1788 assert_eq!(
1789 completions.len(),
1790 9,
1791 "every proposed call reports a completion"
1792 );
1793
1794 for (id, result) in &completions {
1795 let index = id.strip_prefix("call-").expect("call id");
1796 if index == "9" {
1797 let rejection = result.as_ref().expect_err("the 9th call must be rejected");
1798 let reason = rejection.to_string();
1799 assert!(reason.contains("budget of 8"), "{reason}");
1800 assert!(reason.contains("remaining=0"), "{reason}");
1801 assert!(reason.contains("not executed"), "{reason}");
1802 } else {
1803 let outcome = result.as_ref().expect("calls within budget execute");
1804 assert!(
1805 outcome.content.contains(&format!("fixture-{index}")),
1806 "call {id} must return its file contents: {outcome:?}"
1807 );
1808 }
1809 }
1810 }
1811
1812 /// #5170: a call stopped by an admission gate never executes, so its
1813 /// debited budget slot is refunded — the cap counts admitted calls only.
1814 /// With a cap of 1, a blocked first proposal must leave room for the
1815 /// second proposal to run.
1816 #[tokio::test]
1817 async fn tool_call_budget_refunds_calls_blocked_by_admission_gates() {
1818 use crate::llm_client::mock::{MockLlmClient, canned};
1819
1820 let workspace = tempdir().expect("tempdir");
1821 fs::write(workspace.path().join("fixture.txt"), "fixture\n").expect("write fixture");
1822 let mock = std::sync::Arc::new(MockLlmClient::new(vec![
1823 tool_batch_turn(&[
1824 (
1825 "call-blocked",
1826 "definitely_not_a_tool",
1827 r#"{"path":"fixture.txt"}"#,
1828 ),
1829 ("call-admitted", "read_file", r#"{"path":"fixture.txt"}"#),
1830 ]),
1831 canned::simple_text_turn("done"),
1832 ]));
1833
1834 let (status, error, completions) =
1835 run_budgeted_read_turn(workspace.path(), Some(1), mock.clone()).await;
1836 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
1837 assert_eq!(
1838 completions.len(),
1839 2,
1840 "every proposed call reports a completion"
1841 );
1842
1843 let blocked = completions[0]
1844 .1
1845 .as_ref()
1846 .expect_err("the unknown tool must be blocked by the missing-tool gate");
1847 assert!(
1848 blocked.to_string().contains("definitely_not_a_tool"),
1849 "{blocked}"
1850 );
1851 let admitted = completions[1]
1852 .1
1853 .as_ref()
1854 .expect("a gate-blocked call refunds its slot, so the second call still fits the cap of 1");
1855 assert!(
1856 admitted.content.contains("fixture"),
1857 "the admitted call must return its file contents: {admitted:?}"
1858 );
1859 }
1860
1861 /// An approval card that expires unanswered is a timeout, not the user's
1862 /// denial: the model is told so, and the call — which never ran — gives its
1863 /// tool-call budget slot back, so a cap of 1 still admits the next call.
1864 #[tokio::test]
1865 async fn approval_timeout_is_reported_as_timeout_and_refunds_the_budget() {
1866 use crate::llm_client::mock::{MockLlmClient, canned};
1867
1868 let workspace = tempdir().expect("tempdir");
1869 fs::write(workspace.path().join("fixture.txt"), "fixture\n").expect("write fixture");
1870 let mock = std::sync::Arc::new(MockLlmClient::new(vec![
1871 canned::tool_call_turn("call-timeout", "bash", r#"{"command":"echo first"}"#),
1872 canned::tool_call_turn("call-after", "read_file", r#"{"path":"fixture.txt"}"#),
1873 canned::simple_text_turn("done"),
1874 ]));
1875 let client: crate::core::model_client::SharedModelClient = mock.clone();
1876 let mut config = Config::default();
1877 config.approval = Some(codewhale_runtime::config::ApprovalConfig { timeout_seconds: Some(1), ..Default::default() });
1878 let mut engine_config = deterministic_engine_config(workspace.path());
1879 engine_config.exec_policy_engine = ask_rule_engine("echo first");
1880 engine_config.max_tool_calls = Some(1);
1881 let (engine, handle) = Engine::new_with_model_client(engine_config, &config, client);
1882 let task = tokio::spawn(engine.run());
1883 handle
1884 .send(external_user_message_op(
1885 "Run the command, then read the fixture.",
1886 AppMode::Agent,
1887 &config,
1888 ))
1889 .await
1890 .expect("send turn");
1891
1892 let mut timed_out = None;
1893 let mut after = None;
1894 let mut rx = handle.rx_event.write().await;
1895 loop {
1896 let event = tokio::time::timeout(model_turn_event_timeout(), rx.recv())
1897 .await
1898 .expect("timed out waiting for the turn")
1899 .expect("engine event stream closed");
1900 match event {
1901 Event::ApprovalRequired { id, tool_name, .. }
1902 if matches!(tool_name.as_str(), "bash" | "Bash") =>
1903 {
1904 handle
1905 .deny_tool_call_timed_out(&id)
1906 .await
1907 .expect("expire the approval card");
1908 }
1909 Event::ApprovalRequired { id, .. } => {
1910 handle.approve_tool_call(&id).await.expect("approve");
1911 }
1912 Event::ToolCallComplete {
1913 model_call: Some(model_call),
1914 result,
1915 ..
1916 } if model_call.provider_id == "call-timeout" => {
1917 timed_out = Some(result);
1918 }
1919 Event::ToolCallComplete {
1920 model_call: Some(model_call),
1921 result,
1922 ..
1923 } if model_call.provider_id == "call-after" => {
1924 after = Some(result);
1925 }
1926 Event::TurnComplete { status, error, .. } => {
1927 assert_eq!(status, TurnOutcomeStatus::Completed, "{error:?}");
1928 break;
1929 }
1930 _ => {}
1931 }
1932 }
1933 drop(rx);
1934
1935 let timeout = timed_out
1936 .expect("the expired call reports a completion")
1937 .expect_err("an expired approval never runs the call")
1938 .to_string();
1939 assert!(timeout.contains("timed out"), "{timeout}");
1940 assert!(timeout.contains("did not deny"), "{timeout}");
1941 assert!(
1942 !timeout.contains("denied by user"),
1943 "a timeout must not read as the user's refusal: {timeout}"
1944 );
1945 let after = after
1946 .expect("the next call reports a completion")
1947 .expect("the expired call refunded its slot, so the cap of 1 admits this call");
1948 assert!(after.content.contains("fixture"), "{after:?}");
1949 handle.send(Op::Shutdown).await.expect("shutdown engine");
1950 task.await.expect("engine task");
1951 }
1952
1952 lines RUST