返回 CodeWhale
child_host.rs
根目录 / crates / engine / src / core / engine / child_host.rs
1 //! Private captured child configuration for the canonical Engine.
2 use super::*;
3 use crate::core::ops::TurnInputAuthorship;
4 use crate::tools::subagent::engine::ChildAuthority;
5 use anyhow::anyhow;
6
7 pub(super) struct ChildHostSetup {
8 pub authority: Arc<ChildAuthority>,
9 pub system_prompt: SystemPrompt,
10 pub attachment: Option<crate::extension_host::HostAttachment>,
11 }
12 pub(super) struct ChildHostState {
13 pub authority: Arc<ChildAuthority>,
14 pub system_prompt: SystemPrompt,
15 job: Option<Arc<crate::tools::subagent::engine::ChildJob>>,
16 handle: Option<EngineHandle>,
17 route_runtime: crate::tools::subagent::SubAgentRuntime,
18 replacements_tried: usize,
19 pin_fallback_used: bool,
20 pending_route: Option<(
21 crate::tools::subagent::SubAgentRuntime,
22 ValidatedRuntimeRoute,
23 )>,
24 pub(super) request_stop_reason: Option<&'static str>,
25 }
26 impl From<ChildHostSetup> for ChildHostState {
27 fn from(setup: ChildHostSetup) -> Self {
28 let route_runtime = setup.authority.runtime.clone();
29 Self {
30 route_runtime,
31 replacements_tried: 0,
32 pin_fallback_used: false,
33 pending_route: None,
34 request_stop_reason: None,
35 authority: setup.authority,
36 system_prompt: setup.system_prompt,
37 job: None,
38 handle: None,
39 }
40 }
41 }
42 impl ChildHostState {
43 pub(super) fn record_executed_action(&self, tool_name: &str, tool_input: &Value) {
44 let action = crate::core::authority::auto_review::AutoReviewChildAction::from_tool_call(
45 tool_name, tool_input,
46 );
47 self.authority
48 .executed_actions
49 .lock()
50 .unwrap_or_else(std::sync::PoisonError::into_inner)
51 .push(action);
52 }
53 }
54 impl Engine {
55 pub(super) fn new_tool_execution_id(&self) -> String {
56 self.child_host.as_ref().map_or_else(
57 || uuid::Uuid::new_v4().to_string(),
58 |child| child.authority.new_execution_id(),
59 )
60 }
61
62 pub fn new_child_admitted(
63 mut config: EngineConfig,
64 api_config: &Config,
65 authority: Arc<ChildAuthority>,
66 system_prompt: SystemPrompt,
67 attachment: Option<crate::extension_host::HostAttachment>,
68 ) -> Result<(Self, EngineHandle)> {
69 anyhow::ensure!(
70 config.workspace == authority.runtime.context.workspace,
71 "child Engine workspace differs from its captured caller"
72 );
73 anyhow::ensure!(
74 !authority.runtime.context.state_namespace.trim().is_empty(),
75 "child Engine needs its captured root session namespace"
76 );
77 config.session_id = Some(authority.runtime.context.state_namespace.clone());
78 config.plugin_registry = authority.runtime.context.plugin_registry.clone();
79 config.runtime_services = authority.runtime.context.runtime.clone();
80 config.mcp_auth_context =
81 crate::mcp::McpAuthContext(Arc::clone(&authority.runtime.mcp_auth_context));
82 config.todos = authority.runtime.todos.clone();
83 config.max_spawn_depth = authority.runtime.max_spawn_depth;
84 config.allow_shell = authority.runtime.allow_shell;
85 config.trust_mode = authority.runtime.context.trust_mode;
86 config.network_policy = authority.runtime.context.network_policy.clone();
87 if let Some(skills_dir) = authority.runtime.context.skills_dir.as_ref() {
88 config.skills_dir = skills_dir.clone();
89 }
90 config.skills_config = authority.runtime.context.skills_config.clone();
91 config.features = authority.runtime.context.features.clone();
92 config.snapshots_enabled = false;
93 config.memory_enabled = false;
94 config.terminal_chrome_enabled = false;
95 config.advisor_config = crate::tools::subagent::AdvisorConfig::disabled();
96 config.goal_objective = None;
97 config.goal_status = GoalStatus::Paused;
98 config.tools = api_config.tools.clone();
99 config.exec_policy_engine = api_config.exec_policy_engine.clone();
100 let (mut engine, handle) = Self::new_admitted(
101 config,
102 api_config,
103 Some(EngineHostSetup::Child(ChildHostSetup {
104 authority,
105 system_prompt,
106 attachment,
107 })),
108 );
109 engine
110 .child_host
111 .as_mut()
112 .expect("captured child setup")
113 .handle = Some(handle.clone());
114 // The actual caller supplied this frozen concrete client. Route
115 // identity is still resolved and installed by the same Core seam.
116 engine.model_client_injected = true;
117 let posture = engine.runtime_authority_snapshot();
118 engine.apply_runtime_mode_policy(&TurnAuthority::from_effective_fields(
119 posture.mode,
120 posture.allow_shell,
121 posture.trust_mode,
122 posture.auto_approve,
123 posture.approval_mode,
124 ));
125 Ok((engine, handle))
126 }
127 }
128
129 impl Engine {
130 pub fn install_child_job(
131 &mut self,
132 job: Arc<crate::tools::subagent::engine::ChildJob>,
133 seed: Vec<Message>,
134 ) -> Result<()> {
135 let state = self
136 .child_host
137 .as_mut()
138 .ok_or_else(|| anyhow!("not a captured child Engine"))?;
139 anyhow::ensure!(
140 Arc::ptr_eq(&state.authority, &job.authority),
141 "child job changed captured authority"
142 );
143 anyhow::ensure!(state.job.is_none(), "child assignment is already installed");
144 let system = state.system_prompt.clone();
145 state.job = Some(job);
146 self.restore_session_history(seed, Some(system), true);
147 if let Some(state) = self.child_host.as_ref() {
148 Self::apply_child_parent_intent(&mut self.session, &state.authority.runtime);
149 }
150 Ok(())
151 }
152
153 pub fn child_turn_spec(
154 &self,
155 content: String,
156 allowed_tools: Option<Vec<String>>,
157 ) -> Result<TurnSpec> {
158 let state = self
159 .child_host
160 .as_ref()
161 .ok_or_else(|| anyhow!("not a captured child Engine"))?;
162 state
163 .authority
164 .validate_context(&state.authority.context())?;
165 let posture = self.runtime_authority_snapshot();
166 Ok(TurnSpec {
167 profile_constitution: None,
168 content,
169 images: Vec::new(),
170 mode: posture.mode,
171 route: Box::new(self.current_runtime_route().map_err(anyhow::Error::msg)?),
172 compaction: Box::new(self.config.compaction.clone()),
173 initial_routed_usage: Box::default(),
174 goal_objective: None,
175 goal_token_budget: None,
176 goal_status: GoalStatus::Paused,
177 reasoning_effort: state.route_runtime.reasoning_effort.clone(),
178 reasoning_effort_auto: false,
179 auto_model: false,
180 allow_shell: state.authority.runtime.allow_shell && posture.allow_shell,
181 trust_mode: state.authority.runtime.context.trust_mode,
182 auto_approve: posture.auto_approve,
183 approval_mode: posture.approval_mode,
184 translation_enabled: false,
185 allowed_tools,
186 dynamic_tools: Vec::new(),
187 hook_executor: self.config.hook_executor.clone(),
188 verbosity: None,
189 provenance: UserInputProvenance::Runtime,
190 input_authorship: TurnInputAuthorship::NotPerson,
191 submission_id: state
192 .job
193 .as_ref()
194 .and_then(|job| job.take_initial_submission_id()),
195 max_output_tokens: None,
196 })
197 }
198
199 pub(super) fn child_job(&self) -> Option<Arc<crate::tools::subagent::engine::ChildJob>> {
200 self.child_host.as_ref().and_then(|state| state.job.clone())
201 }
202 pub(super) fn child_request_protocol(&self) -> Option<codewhale_config::provider::WireFormat> {
203 self.child_host
204 .as_ref()
205 .map(|state| state.route_runtime.client.wire_format())
206 }
207 pub(super) async fn handle_child_send_message(
208 &mut self,
209 spec: TurnSpec,
210 ) -> Result<Option<crate::tools::subagent::SubAgentResult>> {
211 use crate::tools::subagent::SubAgentStatus;
212 let job = self
213 .child_job()
214 .ok_or_else(|| anyhow!("child Engine has no admitted assignment"))?;
215 self.child_host
216 .as_mut()
217 .expect("captured child")
218 .request_stop_reason = None;
219 let replay_content = spec.content.clone();
220 let replay_scope = spec.allowed_tools.clone();
221 let deadline = job.deadline;
222 let admitted = self
223 .admitted_turn_control
224 .as_ref()
225 .map(|control| control.cancel.clone());
226 let timer = deadline.zip(admitted).map(|(deadline, cancel)| {
227 let job = job.clone();
228 turn_heartbeat::AbortOnDrop(tokio::spawn(async move {
229 tokio::time::sleep_until(deadline.into()).await;
230 job.stop_for_limit(codewhale_protocol::agent_run::AgentLimitKind::WallTime);
231 cancel.cancel();
232 }))
233 });
234 let outcome = Box::pin(self.handle_send_message(spec)).await;
235 drop(timer);
236 job.project(&self.session.messages, job.steps()).await?;
237 if job.authority.runtime.cancel_token.is_cancelled() {
238 return job
239 .finish(
240 &self.session.messages,
241 job.steps(),
242 SubAgentStatus::Cancelled,
243 None,
244 None,
245 )
246 .await
247 .map(Some);
248 }
249 let pending_route = self
250 .child_host
251 .as_mut()
252 .and_then(|state| state.pending_route.take());
253 if let Some((runtime, route)) = pending_route {
254 // The old request failed before a response. A fresh admitted turn
255 // reuses the exact original task on this same Engine/FIFO; it rebuilds
256 // tools, Native prompt sections and Core dispatch receipts together.
257 let client = runtime.client.clone();
258 self.install_validated_runtime_route(route);
259 self.model_client = Some(Arc::new(client));
260 self.session.reasoning_effort = runtime.reasoning_effort.clone();
261 self.session.reasoning_effort_auto = runtime.reasoning_effort_auto;
262 job.installed_replacement(&runtime.model);
263 self.child_host
264 .as_mut()
265 .expect("captured child")
266 .route_runtime = runtime;
267 let spec = self.child_turn_spec(replay_content, replay_scope)?;
268 self.child_host
269 .as_ref()
270 .expect("captured child")
271 .handle
272 .as_ref()
273 .expect("same Engine handle")
274 .send(Op::SendMessage(spec))
275 .await?;
276 return Ok(None);
277 }
278 let (status, error) = match outcome {
279 SendMessageOutcome::Finished { status, error } => (status, error),
280 SendMessageOutcome::NotStarted { error } => (TurnOutcomeStatus::Failed, error),
281 };
282 let own_start = self
283 .session
284 .messages
285 .iter()
286 .rposition(|message| {
287 message.role == codewhale_models::Role::System
288 && message.content.iter().any(|block| {
289 matches!(block, ContentBlock::Text { text, .. }
290 if text.starts_with(crate::tools::subagent::SUBAGENT_CONTEXT_OPEN))
291 })
292 })
293 .map_or(0, |index| index + 1);
294 let text = self.session.messages[own_start..]
295 .iter()
296 .rev()
297 .find(|message| {
298 message.role == codewhale_models::Role::Assistant
299 || (matches!(
300 status,
301 TurnOutcomeStatus::Interrupted | TurnOutcomeStatus::Failed
302 ) && message.role == codewhale_models::Role::InterruptedAssistant)
303 })
304 .map(|message| {
305 message
306 .content
307 .iter()
308 .filter_map(|block| match block {
309 ContentBlock::Text { text, .. } if !text.trim().is_empty() => {
310 Some(text.as_str())
311 }
312 _ => None,
313 })
314 .collect::<Vec<_>>()
315 .join("\n")
316 })
317 .filter(|text| !text.trim().is_empty());
318 if let Some(cause) = job.budget_reason() {
319 let partial = crate::tools::subagent::budget_handback::fallback_partial_text(
320 &self.session.messages,
321 );
322 return job
323 .finish(
324 &self.session.messages,
325 job.steps(),
326 SubAgentStatus::BudgetExhausted,
327 Some(partial),
328 Some(&cause),
329 )
330 .await
331 .map(Some);
332 }
333 let child_status = match (status, error.as_ref(), text.as_ref()) {
334 (TurnOutcomeStatus::Completed, None, Some(_)) => SubAgentStatus::Completed,
335 (TurnOutcomeStatus::Interrupted, _, _) => SubAgentStatus::Interrupted(
336 error
337 .clone()
338 .unwrap_or_else(|| "Core child turn interrupted".into()),
339 ),
340 (TurnOutcomeStatus::Failed, _, _)
341 if self
342 .child_host
343 .as_ref()
344 .and_then(|state| state.request_stop_reason)
345 == Some("request_outcome_unknown") =>
346 {
347 SubAgentStatus::Interrupted(error.clone().unwrap_or_else(|| {
348 "provider request outcome unknown; checkpoint preserved".into()
349 }))
350 }
351 (TurnOutcomeStatus::Failed, Some(reason), _)
352 if reason == super::dispatch::FLEET_NO_PROGRESS_STOP =>
353 {
354 // Core's terminal no-progress report stays Failed even after
355 // earlier steps; checkpoint preservation cannot erase its cause.
356 SubAgentStatus::Failed(reason.clone())
357 }
358 (TurnOutcomeStatus::Failed, _, _) if job.steps() > 1 => {
359 SubAgentStatus::Interrupted(error.clone().unwrap_or_else(|| {
360 "child stopped after prior work; checkpoint preserved".into()
361 }))
362 }
363 _ => SubAgentStatus::Failed(
364 error
365 .clone()
366 .unwrap_or_else(|| "child stopped without a final summary".into()),
367 ),
368 };
369 job.finish(
370 &self.session.messages,
371 job.steps(),
372 child_status,
373 text,
374 self.child_host
375 .as_ref()
376 .and_then(|state| state.request_stop_reason)
377 .or(error.as_deref()),
378 )
379 .await
380 .map(Some)
381 }
382
383 pub(super) fn clear_child_pending_route(&mut self) {
384 if let Some(state) = self.child_host.as_mut() {
385 state.pending_route = None;
386 }
387 }
388
389 pub(super) async fn retract_child_unsent_message(
390 &mut self,
391 mark: crate::core::turn::UnansweredUserMessage,
392 ) -> Result<bool> {
393 if !self.can_retract_unanswered_user_message(&mark) {
394 return Ok(false);
395 }
396 if let Some(job) = self.child_job() {
397 let old = self.session.messages.to_vec();
398 // Preserve durable dispatch/history evidence before changing the
399 // live projection. The one actor owns both sides of this await.
400 if let Err(error) = job.before_replace(&old, &old[..mark.index]).await {
401 self.child_host
402 .as_mut()
403 .expect("captured child")
404 .pending_route = None;
405 return Err(error);
406 }
407 }
408 Ok(self.retract_unanswered_user_message(mark))
409 }
410
411 pub(super) async fn admit_child_first_request_replacement(
412 &mut self,
413 error: &anyhow::Error,
414 ) -> Result<bool> {
415 let Some(job) = self.child_job() else {
416 return Ok(false);
417 };
418 if !job.can_replace_first_request() {
419 return Ok(false);
420 }
421 let state = self.child_host.as_mut().expect("captured child");
422 let Some((next, source, note)) =
423 crate::tools::subagent::engine::approved_first_request_replacement(
424 &job,
425 &state.route_runtime,
426 &mut state.replacements_tried,
427 &mut state.pin_fallback_used,
428 error,
429 )?
430 else {
431 return Ok(false);
432 };
433 let api = next
434 .api_config
435 .as_deref()
436 .ok_or_else(|| anyhow!("approved child replacement has no captured config"))?;
437 let resolved = crate::route_runtime::resolve_runtime_route_for_identity(
438 api,
439 next.client.admitted_provider_identity(),
440 Some(&next.model),
441 )
442 .map_err(anyhow::Error::msg)?;
443 let mut route = resolved
444 .validate_async()
445 .await
446 .map_err(anyhow::Error::msg)?;
447 anyhow::ensure!(
448 next.client.admitted_provider_identity() == &route.identity
449 && route.candidate.endpoint().base_url == next.client.base_url(),
450 "approved child replacement client differs from its exact route"
451 );
452 route.client = next.client.clone();
453 job.authority.validate_context(&job.authority.context())?;
454 job.record_route_replacement(&state.route_runtime, &next, source, note.clone(), error)
455 .await;
456 state.pending_route = Some((next, route));
457 let _ = self.send_event(Event::status(note)).await;
458 Ok(true)
459 }
460
461 pub async fn run_child(self) -> Result<crate::tools::subagent::SubAgentResult> {
462 self.run_owned().await.ok_or_else(|| {
463 anyhow!("child Core actor stopped without a terminal assignment receipt")
464 })?
465 }
466 }
467
468 /// Test observer of Core's actual surface policy and activation cache. It has
469 /// no executor, permission policy or request producer of its own.
470 #[cfg(any(test, feature = "test-support"))]
471 pub struct ChildSurfaceProbe {
472 pub(super) policy: ToolSurfacePolicy,
473 pub(super) cache: crate::core::session::ToolActivationCache,
474 }
475 #[cfg(any(test, feature = "test-support"))]
476 impl ChildSurfaceProbe {
477 pub fn new(catalog: Vec<codewhale_models::Tool>, warm: &[String]) -> Self {
478 let policy = ToolSurfacePolicy::new(
479 crate::tools::ToolRegistry::new(ToolContext::for_empty_registry()),
480 Some(catalog),
481 AppMode::Agent,
482 &HashSet::new(),
483 false,
484 None,
485 None,
486 None,
487 tool_catalog::ToolMode::Direct,
488 );
489 let mut probe = Self {
490 policy,
491 cache: Default::default(),
492 };
493 let activated = probe.cache.activate(&probe.policy.catalog, warm);
494 probe.policy.active_names.extend(activated.admitted);
495 probe
496 }
497 pub fn catalog(&self) -> &[codewhale_models::Tool] {
498 &self.policy.catalog
499 }
500 pub fn catalog_mut(&mut self) -> &mut Vec<codewhale_models::Tool> {
501 &mut self.policy.catalog
502 }
503 pub fn active_names(&self) -> &HashSet<String> {
504 &self.policy.active_names
505 }
506 pub fn request_tools(
507 &mut self,
508 catalog: Vec<codewhale_models::Tool>,
509 strict: bool,
510 ) -> Vec<codewhale_models::Tool> {
511 self.policy.catalog = catalog;
512 self.cache.revalidate(&self.policy.catalog);
513 self.policy.active_names = tool_catalog::initial_active_tools(&self.policy.catalog);
514 self.policy
515 .active_names
516 .extend(self.cache.names().map(str::to_owned));
517 tool_catalog::active_tools_for_request(
518 &self.policy.catalog,
519 &self.policy.active_names,
520 strict,
521 )
522 .unwrap_or_default()
523 }
524 /// Pure cache admission probe; execution still runs Core's planner below.
525 pub fn hydrate(&mut self, name: &str, input: &serde_json::Value) -> Result<Option<String>> {
526 let activation = self
527 .cache
528 .activate(&self.policy.catalog, &[name.to_owned()]);
529 tool_catalog::remove_evicted_cache_activations(
530 &self.policy.catalog,
531 &mut self.policy.active_names,
532 activation.evicted,
533 );
534 self.policy
535 .active_names
536 .extend(activation.admitted.iter().cloned());
537 anyhow::ensure!(
538 activation.admitted.iter().any(|admitted| admitted == name),
539 "tool was not admitted by Core's bounded activation cache"
540 );
541 let definition = self
542 .policy
543 .catalog
544 .iter()
545 .find(|tool| tool.name == name)
546 .ok_or_else(|| anyhow!("tool left the Core catalog"))?;
547 Ok(
548 (!tool_catalog::deferred_first_call_matches_schema(definition, input)).then(|| {
549 tool_catalog::deferred_tool_schema_hydration_result(definition, input).content
550 }),
551 )
552 }
553 }
554 #[cfg(any(test, feature = "test-support"))]
555 pub struct ChildProbeCall {
556 pub id: String,
557 pub execution_id: String,
558 pub name: String,
559 pub input: serde_json::Value,
560 }
561
562 #[cfg(any(test, feature = "test-support"))]
563 impl Engine {
564 /// Direct tests use the real admitted Core planner/executor and approval
565 /// inbox. The loop below only observes/relays those Core events.
566 pub async fn probe_child_call(
567 authority: Arc<ChildAuthority>,
568 registry: crate::tools::ToolRegistry,
569 surface: &mut ChildSurfaceProbe,
570 call: ChildProbeCall,
571 ) -> Result<crate::tools::spec::RichToolResult> {
572 let runtime = authority.runtime.clone();
573 let owner = authority.owner_agent_id.clone();
574 let api = runtime
575 .api_config
576 .as_deref()
577 .ok_or_else(|| anyhow!("fixture needs its explicit captured Config"))?;
578 let (mut engine, handle) = Self::new_child_admitted(
579 EngineConfig {
580 workspace: runtime.context.workspace.clone(),
581 model: runtime.model.clone(),
582 max_steps: 1,
583 auto_review_policy: runtime.auto_review_policy.as_ref().clone(),
584 ..Default::default()
585 },
586 api,
587 authority,
588 SystemPrompt::Text("Core child batch probe".into()),
589 None,
590 )?;
591 surface.policy.registry = registry;
592 let mut events = handle.rx_event.write().await;
593 let mut approvals = futures_util::stream::FuturesUnordered::new();
594 let mut approval_deliveries = futures_util::stream::FuturesUnordered::<
595 std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>>,
596 >::new();
597 use futures_util::StreamExt;
598 let answer = {
599 let execute = engine.probe_child_tool_batch(surface, call);
600 tokio::pin!(execute);
601 loop {
602 tokio::select! {
603 biased;
604 result = &mut execute => break result,
605 () = runtime.cancel_token.cancelled(), if !handle.is_cancelled() => handle.cancel(),
606 Some((id, decision)) = approvals.next(), if !approvals.is_empty() => {
607 if runtime.cancel_token.is_cancelled() || handle.is_cancelled() {
608 handle.cancel();
609 } else {
610 let handle = handle.clone();
611 approval_deliveries.push(Box::pin(async move {
612 match decision {
613 Ok(reply) => handle.accept_child_approval(id, reply).await,
614 Err(error) => {
615 tracing::warn!(
616 %error,
617 %id,
618 "child approval decision failed; denying as unavailable"
619 );
620 handle.deny_tool_call_unavailable(id).await
621 }
622 }
623 }));
624 }
625 }
626 Some(delivered) = approval_deliveries.next(), if !approval_deliveries.is_empty() => {
627 if let Err(error) = delivered {
628 tracing::warn!(%error, "child approval did not match a durable Core decision");
629 }
630 },
631 event = events.recv() => {
632 let Some(event) = event else { break Err(anyhow!("Core probe event stream closed")) };
633 match &event {
634 Event::ApprovalRequired { id, tool_name, description, publication, .. } => {
635 let (_, receiver) = runtime.manager.write().await.register_child_approval(&owner, id, tool_name, description, publication.clone())?;
636 let key = id.clone(); approvals.push(async move { (key, receiver.await) });
637 if let Some(tx) = runtime.event_tx.as_ref().filter(|_| runtime.parent_can_prompt) {
638 let sent = tokio::select! {
639 biased;
640 () = runtime.cancel_token.cancelled() => false,
641 result = tx.send(event.clone()) => result.is_ok(),
642 };
643 if !sent {
644 runtime.manager.write().await.cancel_child_approval(id);
645 {
646 let handle = handle.clone();
647 let id = id.clone();
648 approval_deliveries.push(Box::pin(async move { handle.deny_tool_call_unavailable(id).await }));
649 }
650 }
651 } else {
652 runtime.manager.write().await.cancel_child_approval(id);
653 {
654 let handle = handle.clone();
655 let id = id.clone();
656 approval_deliveries.push(Box::pin(async move { handle.deny_tool_call_unavailable(id).await }));
657 }
658 }
659 }
660 Event::ApprovalWithdrawn { id } => {
661 runtime.manager.write().await.cancel_child_approval(id);
662 if let Some(tx) = &runtime.event_tx {
663 tokio::select! {
664 biased;
665 () = runtime.cancel_token.cancelled() => { let _ = tx.try_send(event.clone()); },
666 _ = tx.send(event.clone()) => {},
667 }
668 }
669 }
670 Event::ToolGateDecision { .. } => {
671 crate::tools::subagent::engine::forward_child_gate_observation(
672 &runtime,
673 &owner,
674 event,
675 &handle.captured_turn_cancel(),
676 runtime.context.turn_deadline,
677 ).await;
678 }
679 _ => {}
680 }
681 }
682 }
683 }
684 };
685 while let Some(delivered) = approval_deliveries.next().await {
686 if let Err(error) = delivered {
687 tracing::warn!(%error, "child approval did not match a durable Core decision");
688 }
689 }
690 // The canonical batch may settle immediately after enqueueing its
691 // last receipt. Observe those exact queued decisions before handback.
692 while let Ok(event) = events.try_recv() {
693 if let Event::ApprovalWithdrawn { id } = &event {
694 runtime.manager.write().await.cancel_child_approval(id);
695 if let Some(tx) = &runtime.event_tx {
696 let _ = tx.try_send(event);
697 }
698 } else if matches!(event, Event::ToolGateDecision { .. }) {
699 crate::tools::subagent::engine::forward_child_gate_observation(
700 &runtime,
701 &owner,
702 event,
703 &handle.captured_turn_cancel(),
704 runtime.context.turn_deadline,
705 )
706 .await;
707 }
708 }
709 let pending = runtime
710 .manager
711 .read()
712 .await
713 .pending_requests_for_agent(&owner);
714 for pending in pending {
715 runtime
716 .manager
717 .write()
718 .await
719 .cancel_child_approval(&pending.approval_id);
720 if let Some(tx) = &runtime.event_tx {
721 let _ = tx.try_send(Event::ApprovalWithdrawn {
722 id: pending.approval_id,
723 });
724 }
725 }
726 answer
727 }
728 }
729
730 #[cfg(any(test, feature = "test-support"))]
731 impl Engine {
732 pub fn probe_child_catalog(
733 authority: &ChildAuthority,
734 registry: &crate::tools::ToolRegistry,
735 ) -> Vec<codewhale_models::Tool> {
736 let mut always_load = HashSet::new();
737 if let Some(scope) = authority.grant.scope.as_deref() {
738 tool_catalog::extend_always_load_from_exact_rules(&mut always_load, scope);
739 }
740 let catalog = tool_catalog::build_model_tool_catalog(
741 authority.tools_for_model(registry, &authority.agent_type),
742 Vec::new(),
743 AppMode::Agent,
744 &always_load,
745 );
746 let mut copied = crate::tools::ToolRegistry::new(ToolContext::for_empty_registry());
747 copied.register_all(registry.all());
748 let mut policy = ToolSurfacePolicy::new(
749 copied,
750 Some(catalog),
751 AppMode::Agent,
752 &always_load,
753 false,
754 None,
755 None,
756 None,
757 tool_catalog::ToolMode::CodeMode,
758 );
759 Self::narrow_child_surface(authority, &mut policy);
760 policy.catalog
761 }
762 }
763 impl Engine {
764 pub(super) fn narrow_child_surface(
765 authority: &ChildAuthority,
766 surface: &mut ToolSurfacePolicy,
767 ) {
768 let discoverable = match authority.grant.scope.as_deref() {
769 None => true,
770 Some(scope) => scope
771 .iter()
772 .any(|rule| tool_catalog::is_wildcard_tool_rule(rule)),
773 };
774 let code_mode = authority
775 .validate(
776 &surface.registry,
777 tool_catalog::EXECUTE_TOOLS_TOOL_NAME,
778 &serde_json::json!({}),
779 )
780 .is_ok();
781 let restore_tool_search =
782 discoverable && surface.allows_tool(codewhale_tools::names::TOOL_SEARCH_NAME);
783 let had_cache_control = surface
784 .catalog
785 .iter()
786 .any(|tool| tool.cache_control.is_some());
787 let admitted_mcp: HashSet<_> = authority
788 .tools_for_model(&surface.registry, &authority.agent_type)
789 .into_iter()
790 .filter(|tool| crate::mcp::McpPool::is_mcp_tool(&tool.name))
791 .map(|tool| tool.name)
792 .collect();
793 surface.catalog.retain(|tool| {
794 (surface.registry.contains(&tool.name)
795 && (!crate::mcp::McpPool::is_mcp_tool(&tool.name)
796 || admitted_mcp.contains(&tool.name)))
797 || (discoverable && codewhale_tools::names::is_tool_search_tool(&tool.name))
798 || (code_mode && tool.name == tool_catalog::EXECUTE_TOOLS_TOOL_NAME)
799 });
800 tool_catalog::settle_discovery_surface(
801 &mut surface.catalog,
802 restore_tool_search,
803 had_cache_control,
804 );
805 surface
806 .active_names
807 .retain(|name| surface.catalog.iter().any(|tool| &tool.name == name));
808 if surface
809 .catalog
810 .iter()
811 .any(|tool| tool.name == codewhale_tools::names::TOOL_SEARCH_NAME)
812 {
813 surface
814 .active_names
815 .insert(codewhale_tools::names::TOOL_SEARCH_NAME.to_string());
816 }
817 surface.active = tool_catalog::active_tools_for_request(
818 &surface.catalog,
819 &surface.active_names,
820 surface.strict_tool_mode,
821 );
822 }
823 }
824
824 lines RUST