返回 CodeWhale
engine.rs
根目录 / crates / engine / src / tools / subagent / engine.rs
1 //! Captured child authority projected onto the canonical Engine registry.
2 //! This module owns no model loop, tool registry, approval decision or history.
3 use super::*;
4
5 /// Captured billing origin and the existing worker projection only. This
6 /// carries no ChildGrant, tool/config authority, job, kernel or new ledger.
7 #[derive(Clone)]
8 pub struct ChildAccountingProjection {
9 cost_scope: crate::cost_status::CostScopeToken,
10 accounting_origin: Option<crate::cost_status::NativeUsageOrigin>,
11 manager: SharedSubAgentManager,
12 mailbox: Option<Mailbox>,
13 owner: String,
14 }
15 impl ChildAccountingProjection {
16 pub(super) fn capture(runtime: &SubAgentRuntime, owner: &str) -> Self {
17 let accounting_origin = {
18 let origin = runtime.context.accounting_origin.clone();
19 #[cfg(any(test, feature = "test-support"))]
20 let origin = origin.or_else(|| runtime.accounting_origin.test_session_origin());
21 origin
22 };
23 let cost_scope = accounting_origin.as_ref().map_or(
24 runtime.accounting_origin.cost_scope,
25 crate::cost_status::NativeUsageOrigin::scope,
26 );
27 Self {
28 cost_scope,
29 accounting_origin,
30 manager: runtime.manager.clone(),
31 mailbox: runtime.mailbox.clone(),
32 owner: owner.to_owned(),
33 }
34 }
35 pub fn publish(
36 &self,
37 record: &crate::cost_status::RuntimeUsageRecord,
38 ) -> std::io::Result<Option<u64>> {
39 crate::cost_status::record_runtime_usage(
40 self.cost_scope,
41 self.accounting_origin.as_ref(),
42 record,
43 );
44 let reported = record.settlement.as_ref().is_some_and(|revision| {
45 revision.coverage == crate::llm_client::ProviderUsageCoverage::Reported
46 || (revision.coverage == crate::llm_client::ProviderUsageCoverage::Incomplete
47 && record.usage.usage != Usage::default())
48 });
49 if reported && let Some(mailbox) = &self.mailbox {
50 let _ = mailbox.send(MailboxMessage::usage_record(&self.owner, record.clone()));
51 }
52 Ok(reported
53 .then(|| priced_usd_microusd(&record.usage.route.audit_frozen(&record.usage.usage)))
54 .flatten())
55 }
56
57 async fn publish_async(
58 &self,
59 record: &crate::cost_status::RuntimeUsageRecord,
60 ) -> std::io::Result<Option<u64>> {
61 let accounting = self.clone();
62 let record = record.clone();
63 #[cfg(any(test, feature = "test-support"))]
64 let origin = crate::cost_status::test_cost_scope_id();
65 codewhale_runtime::runtime_control::owner_work(move || {
66 #[cfg(any(test, feature = "test-support"))]
67 let _origin = crate::cost_status::bind_test_cost_scope(origin);
68 accounting.publish(&record).map_err(anyhow::Error::from)
69 })
70 .await
71 .map_err(std::io::Error::other)
72 }
73
74 pub async fn project_settled(
75 &self,
76 record: &crate::cost_status::RuntimeUsageRecord,
77 ) -> std::io::Result<()> {
78 let manager = self.manager.clone();
79 let owner = self.owner.clone();
80 let record = record.clone();
81 codewhale_runtime::runtime_control::owner_work(move || {
82 let mut manager = manager.blocking_write();
83 manager.record_worker_source(&owner, &record)?;
84 Ok(())
85 })
86 .await
87 .map_err(std::io::Error::other)
88 }
89
90 pub(super) async fn publish_auxiliary_usage(
91 &self,
92 record: &crate::cost_status::RuntimeUsageRecord,
93 ) {
94 if let Err(error) = self.publish_async(record).await {
95 tracing::warn!(
96 target: "subagent",
97 owner = %self.owner,
98 %error,
99 "auxiliary review usage publication failed"
100 );
101 }
102 if let Err(error) = self.project_settled(record).await {
103 tracing::warn!(
104 target: "subagent",
105 owner = %self.owner,
106 %error,
107 "auxiliary review usage projection failed"
108 );
109 }
110 }
111 }
112
113 #[derive(Clone)]
114 pub struct ChildAuthority {
115 pub grant: codewhale_agent_contract::worker_profile::ChildGrant,
116 pub(super) disallowed_tools: Vec<String>,
117 pub(super) accept_edits: bool,
118 pub agent_type: FleetRole,
119 pub owner_agent_id: String,
120 pub owner_agent_name: String,
121 pub(super) coordination_manager: SharedSubAgentManager,
122 pub(super) enforce_write_claim: bool,
123 pub runtime: SubAgentRuntime,
124 pub person_wait: Arc<PersonWaitClock>,
125 pub executed_actions:
126 Arc<std::sync::Mutex<Vec<crate::core::authority::auto_review::AutoReviewChildAction>>>,
127 }
128 impl std::fmt::Debug for ChildAuthority {
129 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 f.debug_struct("ChildAuthority")
131 .field("owner", &self.owner_agent_id)
132 .field("grant", &self.grant)
133 .finish_non_exhaustive()
134 }
135 }
136 impl ChildAuthority {
137 const ACTION_ALIASES: &'static [(&'static str, &'static str, &'static str)] =
138 CANONICAL_ACTION_ALIASES;
139 pub fn capture(
140 runtime: SubAgentRuntime,
141 agent_type: FleetRole,
142 owner_agent_id: String,
143 owner_agent_name: String,
144 explicit_allowed_tools: Option<Vec<String>>,
145 ) -> Arc<Self> {
146 let parent_shell = if tool_denied(Some(&runtime.context.disallowed_tools), "bash") {
147 ShellPolicy::None
148 } else {
149 ShellPolicy::from_legacy_allow_shell(runtime.allow_shell)
150 };
151 let mut effective = runtime.worker_profile.clone();
152 effective.shell = effective.shell.min_with(parent_shell);
153 let scope = intersect_explicit_tool_scope(&effective.tools, explicit_allowed_tools);
154 let grant = codewhale_agent_contract::worker_profile::ChildGrant::resolve(
155 &agent_type,
156 &effective,
157 scope,
158 !runtime.would_exceed_depth(),
159 );
160 let executed_actions = runtime
161 .manager
162 .try_read()
163 .ok()
164 .and_then(|manager| manager.executed_actions_handle(&owner_agent_id))
165 .unwrap_or_default();
166 Arc::new(Self {
167 grant,
168 disallowed_tools: effective.denied_tools,
169 accept_edits: runtime.accept_edits,
170 agent_type,
171 owner_agent_id,
172 owner_agent_name,
173 coordination_manager: runtime.manager.clone(),
174 enforce_write_claim: true,
175 runtime,
176 person_wait: Arc::new(PersonWaitClock::default()),
177 executed_actions,
178 })
179 }
180 /// One child builder used by Core's actual turn registry. The supplied
181 /// runtime already carries the exact turn route and nested completion inbox.
182 pub fn tool_registry_builder(
183 &self,
184 runtime: SubAgentRuntime,
185 todos: SharedTodoList,
186 ) -> ToolRegistryBuilder {
187 ToolRegistryBuilder::new().with_full_agent_surface_options(
188 Some(runtime.client.clone()),
189 runtime.model.clone(),
190 runtime.manager.clone(),
191 runtime.clone(),
192 runtime.agent_tool_surface_options.clone(),
193 todos,
194 )
195 }
196 pub fn accounting_projection(&self) -> ChildAccountingProjection {
197 ChildAccountingProjection::capture(&self.runtime, &self.owner_agent_id)
198 }
199 pub fn usage_origin(&self) -> Option<crate::cost_status::NativeUsageOrigin> {
200 let origin = self.runtime.context.accounting_origin.clone();
201 #[cfg(any(test, feature = "test-support"))]
202 let origin = origin.or_else(|| self.runtime.accounting_origin.test_session_origin());
203 origin
204 }
205 pub fn accounting_origin(&self) -> (crate::cost_status::CostScopeToken, String, String) {
206 (
207 self.runtime.accounting_origin.cost_scope,
208 self.runtime.accounting_origin.session_id.clone(),
209 self.owner_agent_id.clone(),
210 )
211 }
212 pub async fn settle_response(
213 &self,
214 record: &crate::cost_status::RuntimeUsageRecord,
215 ) -> std::io::Result<()> {
216 let accounting = self.accounting_projection();
217 accounting.publish_async(record).await?;
218 accounting.project_settled(record).await
219 }
220 pub async fn project_settled_response(
221 &self,
222 record: &crate::cost_status::RuntimeUsageRecord,
223 ) -> std::io::Result<()> {
224 self.accounting_projection().project_settled(record).await
225 }
226 pub fn new_execution_id(&self) -> String {
227 new_child_execution_id(&self.owner_agent_id)
228 }
229 pub fn pause_person_wait(&self) -> PersonWaitPause {
230 self.person_wait.pause()
231 }
232 pub fn nested_runtime(
233 &self,
234 context: ToolContext,
235 completion: mpsc::Sender<SubAgentCompletion>,
236 fork: SubAgentForkContext,
237 ) -> SubAgentRuntime {
238 let mut runtime = self.runtime.clone();
239 runtime.context = context;
240 runtime.parent_agent_id = Some(self.owner_agent_id.clone());
241 runtime.worker_profile.shell = self.grant.shell_policy();
242 runtime.agent_tool_surface_options.shell_policy = self.grant.shell_policy();
243 runtime.parent_completion_tx = Some(completion);
244 runtime.fork_context = Some(fork);
245 runtime
246 }
247 pub fn typed_error(error: anyhow::Error) -> ToolError {
248 match error.downcast::<ToolError>() {
249 Ok(error) => error,
250 Err(error) => ToolError::permission_denied(error.to_string()),
251 }
252 }
253 pub fn validate_context(&self, context: &ToolContext) -> std::result::Result<(), ToolError> {
254 if context.workspace != self.runtime.context.workspace
255 || context.owner_agent_id.as_deref() != Some(self.owner_agent_id.as_str())
256 || context.state_namespace != self.runtime.context.state_namespace
257 {
258 return Err(ToolError::permission_denied(
259 "child caller identity or workspace changed before dispatch",
260 ));
261 }
262 if context
263 .cancel_token
264 .as_ref()
265 .is_some_and(CancellationToken::is_cancelled)
266 || self.runtime.cancel_token.is_cancelled()
267 {
268 return Err(ToolError::cancelled("child dispatch cancelled"));
269 }
270 Ok(())
271 }
272 pub async fn run_tool_bounded<F, T>(&self, future: F) -> std::result::Result<T, ToolError>
273 where
274 F: std::future::Future<Output = std::result::Result<T, ToolError>>,
275 {
276 let deadline = budget_handback::wall_deadline(&self.runtime);
277 match run_tool_with_person_aware_timeout(
278 self.runtime.tool_timeout,
279 deadline,
280 &self.person_wait,
281 future,
282 )
283 .await
284 {
285 Some(result) => result,
286 None => Err(ToolError::execution_failed(
287 "child tool or original work deadline exhausted",
288 )),
289 }
290 }
291 pub fn approval_receipt_store(
292 &self,
293 ) -> std::result::Result<crate::approval_log::ApprovalReceiptStore, String> {
294 self.runtime
295 .approval_receipt_store
296 .clone()
297 .unwrap_or_else(|| Err("child caller has no captured approval receipt store".into()))
298 }
299 pub fn context(self: &Arc<Self>) -> ToolContext {
300 let mut context = self
301 .runtime
302 .context
303 .clone()
304 .with_owner_agent(self.owner_agent_id.clone(), self.owner_agent_name.clone())
305 .with_shell_policy(self.grant.shell_policy());
306 context.disallowed_tools = self.disallowed_tools.clone();
307 context.child_host = Some(self.clone());
308 context
309 }
310 pub fn validate(&self, registry: &ToolRegistry, name: &str, input: &Value) -> Result<()> {
311 if !self.grant.desktop && is_machine_control_tool(name) {
312 return Err(admission_denied(format!(
313 "[tool.family.denied] Desktop/computer-control tool `{name}` is not available to sub-agents. Run it in the parent session instead, or ask the user."
314 )));
315 }
316 if self.grant_blocks_tool(registry, name) {
317 return Err(admission_denied(format!(
318 "Tool {name} is not available to this read-only worker because its process path does not share the hardened evidence boundary. Use read/search, classifier-bounded bash reads, or the verifier's bounded Run tool instead."
319 )));
320 }
321 let action = input.get("action").and_then(Value::as_str);
322 if self.grant.surface == codewhale_agent_contract::worker_profile::ToolSurface::Evidence
323 && name == "Web"
324 && !matches!(action, Some("search" | "fetch"))
325 {
326 return Err(admission_denied(
327 "Tool Web is limited to search/fetch in the read-only evidence profile",
328 ));
329 }
330 // Catalog shaping is not authority. `agent` clears both name-keyed
331 // gates below by design, so the per-action gate has to be repeated
332 // here or a hand-written call would reach an action the role's own
333 // catalog withheld.
334 if name == "agent"
335 && matches!(parse_agent_tool_action(input), Ok(AgentToolAction::Claim))
336 && !self.agent_action_permitted("claim")
337 {
338 return Err(admission_denied(format!(
339 "agent action=claim widens an enforced write scope, and the Fleet role `{role}` has no write authority to widen. Use an `implement` or `general` role.",
340 role = self.agent_type.as_str()
341 )));
342 }
343 let family_action_allowed = if !Self::ACTION_ALIASES
344 .iter()
345 .any(|(family, _, _)| *family == name)
346 {
347 true
348 } else if let Some(action) = action {
349 self.is_action_allowed(name, action)
350 } else {
351 self.grant
352 .scope
353 .as_ref()
354 .is_none_or(|list| list.iter().any(|allowed| allowed == name))
355 };
356 if !self.is_tool_allowed(name) || !family_action_allowed {
357 return Err(admission_denied(format!(
358 "Tool {name} not allowed for this sub-agent; report the blocked probe to the parent instead of working around it"
359 )));
360 }
361 // #3217: authoritative per-role posture — read-only roles cannot mutate
362 // and non-`Full`-shell roles cannot run shell, regardless of whether
363 // the parent session is auto-approved. This closes the auto-approve
364 // bypass where a read-only child could quietly write or shell out.
365 if let Some(grant) = registry.delegated_mcp_read(name) {
366 if !self.grant.network
367 || !self
368 .grant
369 .scope
370 .as_ref()
371 .is_some_and(|scope| scope.iter().any(|entry| entry == name))
372 {
373 return Err(admission_denied(
374 "[role.scope.denied] This connector needs an explicit child tool and network grant.",
375 ));
376 }
377 if !grant.current() {
378 return Err(admission_denied(
379 "[role.binding.stale] This connector binding has changed.",
380 ));
381 }
382 if !grant.permits_arguments(input) {
383 return Err(admission_denied(
384 "[role.disclosure.denied] This connector payload is outside the delegated read grant.",
385 ));
386 }
387 }
388 if !self.posture_permits_tool(registry, name, Some(input)) {
389 if crate::mcp::McpPool::is_mcp_tool(name) {
390 return Err(admission_denied(
391 "[role.effect.denied] This role requires an operator-authorized connector read.",
392 ));
393 }
394 if self.allows_bounded_readonly_bash(name) {
395 // #6015: the same rule text and next steps as the durable
396 // authority and the executor, from the one classifier.
397 let lane =
398 crate::tools::shell::readonly_enforced_lane_available(registry.context());
399 return Err(admission_denied(
400 match crate::tools::shell::agent_readonly_bash_verdict(input) {
401 Err(rejection) => format!(
402 "{} (tool {name}, Fleet role `{role}`)",
403 crate::tools::shell::readonly_refusal(&rejection, lane),
404 role = self.agent_type.as_str(),
405 ),
406 Ok(()) => format!(
407 "[shell.readonly.command] Tool {name} input did not match the bounded read-only shell grammar for Fleet role `{role}`. {guidance}",
408 role = self.agent_type.as_str(),
409 guidance =
410 codewhale_execpolicy::command_safety::readonly_command_help()
411 ),
412 },
413 ));
414 }
415 return Err(admission_denied(format!(
416 "[role.posture.denied] Tool {name} is not permitted for the read-only Fleet role `{role}`. Use an `implement` or `general` role (or `custom` with an explicit allowed_tools list) to mutate the workspace or run shell commands.",
417 role = self.agent_type.as_str()
418 )));
419 }
420 // Denied network capability cannot be expanded by answering a prompt.
421 if self.network_is_denied() {
422 reject_network_reaching_input(name, input).map_err(Self::typed_error)?;
423 }
424 reject_subagent_terminal_takeover(name, input).map_err(Self::typed_error)?;
425 if self.write_is_denied() {
426 reject_unbounded_verification(name, input, !self.shell_is_denied())
427 .map_err(Self::typed_error)?;
428 }
429 // The centralized envelope check. Everything above is name- or
430 // shape-specific; this one is derived from the tool's real capabilities
431 // and this call's canonical action, so it also covers the tools no list
432 // in this file can name — repository plugins, runtime MCP server tools,
433 // and anything registered later. The bounded read-only bash carve-out
434 // (#5426/#5438) carries its proven-read-only evidence so the envelope
435 // classifies it Bounded instead of refusing it as Executes.
436 if let Some(spec) = registry.get(name) {
437 crate::tools::execution_envelope::enforce_execution_envelope(
438 name,
439 input,
440 spec.as_ref(),
441 self.execution_envelope(),
442 self.bounded_readonly_bash_evidence(name, input),
443 )
444 .map_err(admission_denied)?;
445 }
446 Ok(())
447 }
448 pub async fn validate_claim(
449 &self,
450 registry: &ToolRegistry,
451 name: &str,
452 input: &Value,
453 ) -> Result<Vec<String>> {
454 self.validate(registry, name, input)?;
455 let canonical = codewhale_execpolicy::canonical_action::canonical_action_alias(name, input);
456 let scope_aware_write = matches!(
457 canonical,
458 "write" | "edit" | "write_file" | "edit_file" | "apply_patch" | "fim_edit"
459 ) || (name == "pandoc_convert"
460 && input.get("output_path").is_some());
461 if scope_aware_write && self.enforce_write_claim {
462 let paths = mutation_paths(name, input, &self.runtime.context.workspace)?;
463 if paths.is_empty() {
464 return Err(admission_denied(format!(
465 "Write tool {name} did not expose a bounded repo-relative target for coordination"
466 )));
467 }
468 let held = self.coordination_manager.clone().read_owned().await;
469 let owner = self.owner_agent_id.clone();
470 codewhale_runtime::runtime_control::owner_work(move || {
471 held.validate_write_scope(&owner, &paths)
472 .map_err(anyhow::Error::msg)
473 })
474 .await
475 .map_err(|error| admission_denied(error.to_string()))?;
476 } else if self.enforce_write_claim
477 // The typed read-only boundary above already rejected mutation.
478 && !self.write_is_denied()
479 && !is_internal_coordination_state_tool(name)
480 // Shell runs are governed by the execution envelope, sandbox and
481 // approval posture. The write claim coordinates bounded file
482 // tools; it no longer denies a child its shell while a peer writes.
483 && !is_unbounded_shell_run(name, input)
484 && registry.get(name).is_some_and(|spec| {
485 let canonical = canonical_action_alias(name, input);
486 let is_shell_control = matches!(
487 canonical,
488 "exec_shell_wait" | "exec_shell_interact" | "exec_shell_cancel"
489 );
490 let capabilities = spec.capabilities();
491 !is_shell_control
492 && (spec.approval_requirement_for(input) == ApprovalRequirement::Suggest
493 || (!spec.is_read_only_for(input)
494 && capabilities.iter().any(|capability| {
495 matches!(
496 capability,
497 ToolCapability::WritesFiles
498 | ToolCapability::ExecutesCode
499 | ToolCapability::Network
500 )
501 })))
502 })
503 {
504 let held = self.coordination_manager.clone().read_owned().await;
505 let owner = self.owner_agent_id.clone();
506 let blocking_peers = codewhale_runtime::runtime_control::owner_work(move || {
507 // A peer-free checkout still requires the exact held origin.
508 // The file/root checks stay on the bounded owner worker.
509 if let Some(claim) = held.shared_write_claim(&owner) {
510 held.validate_coordination_claim_root(&owner, claim)
511 .map_err(anyhow::Error::msg)?;
512 Ok(held.live_peer_shared_write_claim_owners(&owner))
513 } else {
514 Ok(Vec::new())
515 }
516 })
517 .await
518 .map_err(|error| admission_denied(error.to_string()))?;
519 if !blocking_peers.is_empty() {
520 return Err(admission_denied(format!(
521 "Tool {name} cannot prove a bounded file target while peers are writing in this shared checkout (blocking peers: {}). Use a bounded write tool, or run executable work that needs writes in an isolated worktree. Disjoint write_roots alone do not constrain arbitrary code.",
522 blocking_peers.join(", ")
523 )));
524 }
525 }
526 let observed_paths = if scope_aware_write {
527 mutation_paths(name, input, &self.runtime.context.workspace)?
528 } else {
529 Vec::new()
530 };
531 Ok(observed_paths)
532 }
533 pub async fn record_settled_writes(&self, paths: Vec<String>) {
534 if paths.is_empty() {
535 return;
536 }
537 let mut manager = self.coordination_manager.write().await;
538 let shared_checkout = manager
539 .worker_records
540 .get(&self.owner_agent_id)
541 .is_some_and(|record| {
542 normalize_subagent_workspace(&record.spec.workspace)
543 == normalize_subagent_workspace(&manager.workspace)
544 });
545 if shared_checkout && let Some(mailbox) = self.runtime.mailbox.as_ref() {
546 let _ = mailbox.send(MailboxMessage::FileWrites {
547 agent_id: self.owner_agent_id.clone(),
548 turn_seq: 0,
549 paths: paths.clone(),
550 });
551 }
552 if let Some(record) = manager.worker_records.get_mut(&self.owner_agent_id) {
553 record.delivery_evidence.observed_writes.extend(paths);
554 }
555 }
556 pub fn delegated_call(&self, registry: &ToolRegistry, name: &str, input: &Value) -> bool {
557 if self.bounded_readonly_bash_evidence(name, input) {
558 return true;
559 }
560 registry
561 .get(name)
562 .is_some_and(|spec| match spec.approval_requirement_for(input) {
563 ApprovalRequirement::Auto => true,
564 ApprovalRequirement::Suggest => {
565 self.grant.files == codewhale_agent_contract::worker_profile::FileGrant::Write
566 && (self.accept_edits
567 || Self::role_can_delegate_writes(&self.agent_type)
568 || self.workspace_write_carve_out_permits(registry, name, input))
569 }
570 ApprovalRequirement::Required => false,
571 })
572 }
573 pub fn role_can_delegate_writes(agent_type: &FleetRole) -> bool {
574 // Builder is the named implementation role. Custom may write only when
575 // its profile, explicit scope, and execution envelope all agree.
576 matches!(agent_type, FleetRole::Builder | FleetRole::Custom)
577 }
578
579 pub fn workspace_write_carve_out_permits(
580 &self,
581 registry: &ToolRegistry,
582 name: &str,
583 input: &Value,
584 ) -> bool {
585 // This is a bounded convenience for write-capable children, not an
586 // authority escalation: every target must resolve inside the workspace
587 // and still pass sensitive-path, repository-law, and claim checks.
588 if self.grant.files != codewhale_agent_contract::worker_profile::FileGrant::Write {
589 return false;
590 }
591 crate::core::authority::paths_within_workspace_write_carve_out(
592 &registry.context().workspace,
593 &raw_mutation_target_paths(name, input),
594 )
595 }
596
597 pub fn posture_permits_tool(
598 &self,
599 registry: &ToolRegistry,
600 name: &str,
601 input: Option<&Value>,
602 ) -> bool {
603 // Delegation depth governs `agent`; write posture must not accidentally
604 // suppress it or turn depth into a mutation permission.
605 if name == "agent" {
606 return true;
607 }
608 if let Some(grant) = registry.delegated_mcp_read(name) {
609 return grant.current()
610 && self.grant.network
611 && self
612 .grant
613 .scope
614 .as_ref()
615 .is_some_and(|scope| scope.iter().any(|entry| entry == name))
616 && input.is_none_or(|input| grant.permits_arguments(input));
617 }
618 match registry.get(name) {
619 Some(spec) => match input.map_or_else(
620 || spec.approval_requirement(),
621 |input| spec.approval_requirement_for(input),
622 ) {
623 ApprovalRequirement::Auto => true,
624 ApprovalRequirement::Suggest => {
625 self.grant.files == codewhale_agent_contract::worker_profile::FileGrant::Write
626 }
627 ApprovalRequirement::Required => {
628 // An outbound read needs approval because its payload can
629 // disclose data. That hold does not grant shell/write
630 // authority; network/envelope and parent approval gates
631 // below independently decide whether this child may send it.
632 let capabilities = spec.capabilities();
633 if capabilities.contains(&ToolCapability::ReadOnly)
634 && capabilities.contains(&ToolCapability::Network)
635 && !capabilities.contains(&ToolCapability::ExecutesCode)
636 && !capabilities.contains(&ToolCapability::WritesFiles)
637 {
638 return true;
639 }
640
641 // #5426 acceptance point 1: the bounded read-only shell.
642 // `allows_bounded_readonly_bash` admits canonical `bash`
643 // to the inspection grant through the raw-shell deny
644 // list; a call the agent read-only classifier proves
645 // mutation-free is Auto-class evidence, not a held
646 // mutation, so the gate must not demand a full shell
647 // grant for it. Judged by the same predicate
648 // `BashTool::execute` enforces under
649 // `ShellPolicy::ReadOnly` (shell.rs), so this admission
650 // can never widen past the execute-time refusal — the
651 // first live dogfood against #5428 was denied all three
652 // canonical inspection commands here because the gate
653 // consulted only `Required` → `Full`.
654 if self.allows_bounded_readonly_bash(name)
655 && input.is_some_and(crate::tools::shell::agent_readonly_bash_input)
656 {
657 return true;
658 }
659 // `Verify` holds process-start authority for the bounded
660 // verification surface; the envelope below still refuses
661 // its ExecutesCode/WritesFiles calls by capability.
662 self.grant.shell >= codewhale_agent_contract::worker_profile::ShellGrant::Verify
663 }
664 },
665 None => true,
666 }
667 }
668
669 pub fn is_tool_denied(&self, name: &str) -> bool {
670 // The shared matcher canonicalizes legacy/lowercase spellings before
671 // applying exact or prefix rules. For example `exec_shell*` denies
672 // `bash`, and `write_file*` denies `write`, in roots and children alike.
673 tool_denied(Some(&self.disallowed_tools), name)
674 }
675
676 pub fn allows_bounded_readonly_bash(&self, name: &str) -> bool {
677 name == "bash"
678 && self.grant.shell == codewhale_agent_contract::worker_profile::ShellGrant::Inspect
679 }
680
681 pub fn legacy_action_alias(family: &str, action: &str) -> Option<&'static str> {
682 Self::ACTION_ALIASES
683 .iter()
684 .find_map(|(candidate_family, candidate_action, alias)| {
685 (*candidate_family == family && *candidate_action == action).then_some(*alias)
686 })
687 }
688
689 pub fn is_action_allowed(&self, family: &str, action: &str) -> bool {
690 let alias = Self::legacy_action_alias(family, action);
691 // Read-only inspection keeps two deliberate evidence carve-outs:
692 // classifier-bounded Bash reads and Web search/fetch. They bypass only
693 // the coarse family sentinel; action, posture, and envelope checks still
694 // reject mutation, arbitrary shell, and non-evidence Web actions.
695 let bounded_readonly_bash = self.allows_bounded_readonly_bash(family) && action == "run";
696 let web_readonly_action = family.eq_ignore_ascii_case("Web")
697 && matches!(action, "search" | "fetch")
698 && self.network_is_denied();
699 if self.is_tool_denied(family)
700 || !bounded_readonly_bash
701 && !web_readonly_action
702 && alias.is_some_and(|name| self.is_tool_denied(name))
703 {
704 return false;
705 }
706 match &self.grant.scope {
707 None => true,
708 Some(list) => {
709 list.iter().any(|name| name.eq_ignore_ascii_case(family))
710 || alias.is_some_and(|alias| explicit_scope_permits(list, alias))
711 }
712 }
713 }
714
715 pub fn is_tool_allowed(&self, name: &str) -> bool {
716 if name == "agent" && !self.grant.spawn {
717 return false;
718 }
719 if self.is_tool_denied(name) && !self.allows_bounded_readonly_bash(name) {
720 return false;
721 }
722 match &self.grant.scope {
723 None => true,
724 Some(list) => {
725 explicit_scope_permits(list, name)
726 || Self::ACTION_ALIASES.iter().any(|(family, _, alias)| {
727 *family == name && list.iter().any(|allowed| allowed == alias)
728 })
729 }
730 }
731 }
732
733 pub(crate) fn can_collect_background_tests(&self) -> bool {
734 use codewhale_agent_contract::worker_profile::{ShellGrant, ToolSurface};
735 self.grant.shell == ShellGrant::Full
736 && self.grant.surface != ToolSurface::Evidence
737 && self.is_tool_allowed("task_shell_wait")
738 }
739
740 pub fn grant_blocks_tool(&self, registry: &ToolRegistry, name: &str) -> bool {
741 let lower = name.to_ascii_lowercase();
742 // Desktop / machine-control is never in a child's grant.
743 if !self.grant.desktop && is_machine_control_tool(name) {
744 return true;
745 }
746 // Core's virtual search returns this child's filtered catalog; it is
747 // not a registered process tool. Scope and deny checks still follow.
748 let evidence_tool = codewhale_tools::names::is_tool_search_tool(name)
749 || crate::tools::registry::readonly_evidence_tool_name(name)
750 || registry
751 .get(name)
752 .is_some_and(|tool| crate::tools::registry::readonly_evidence_tool(tool.as_ref()));
753 // The Evidence surface admits only the hardened evidence tools and
754 // `agent` (delegation).
755 if self.grant.surface == codewhale_agent_contract::worker_profile::ToolSurface::Evidence
756 && lower != "agent"
757 && !evidence_tool
758 {
759 return true;
760 }
761 // Below a Full shell grant the raw process surface is gone — except
762 // canonical `bash` under Inspect, which the read-only classifier
763 // bounds at dispatch.
764 let raw_shell = lower == "bash"
765 || lower.starts_with("exec_shell")
766 || matches!(
767 lower.as_str(),
768 "exec_wait" | "exec_interact" | "task_shell_start" | "task_shell_wait"
769 )
770 || lower.starts_with("terminal/")
771 || lower.starts_with("terminal_");
772 raw_shell
773 && self.grant.shell < codewhale_agent_contract::worker_profile::ShellGrant::Full
774 && !self.allows_bounded_readonly_bash(name)
775 }
776
777 pub fn network_is_denied(&self) -> bool {
778 !self.grant.network
779 }
780
781 pub fn write_is_denied(&self) -> bool {
782 self.grant.files != codewhale_agent_contract::worker_profile::FileGrant::Write
783 }
784
785 pub fn shell_is_denied(&self) -> bool {
786 self.grant.shell < codewhale_agent_contract::worker_profile::ShellGrant::Verify
787 }
788
789 pub fn execution_envelope(&self) -> crate::tools::execution_envelope::ExecutionEnvelope {
790 // The capability envelope is the grant's own projection: catalog and
791 // dispatch derive it from the same fields, never from a deny-list
792 // sentinel or a role re-mapping that could disagree with them.
793 crate::tools::execution_envelope::ExecutionEnvelope {
794 write: self.grant.files == codewhale_agent_contract::worker_profile::FileGrant::Write,
795 network: self.grant.network,
796 shell: !self.shell_is_denied(),
797 }
798 }
799
800 pub fn envelope_permits(&self, registry: &ToolRegistry, name: &str, input: &Value) -> bool {
801 let envelope = self.execution_envelope();
802 if envelope.is_unrestricted() {
803 return true;
804 }
805 match registry.get(name) {
806 Some(spec) => crate::tools::execution_envelope::enforce_execution_envelope(
807 name,
808 input,
809 spec.as_ref(),
810 envelope,
811 self.bounded_readonly_bash_evidence(name, input),
812 )
813 .is_ok(),
814 None => true,
815 }
816 }
817
818 pub fn bounded_readonly_bash_evidence(&self, name: &str, input: &Value) -> bool {
819 self.allows_bounded_readonly_bash(name)
820 && crate::tools::shell::agent_readonly_bash_input(input)
821 }
822
823 pub fn agent_action_permitted(&self, action: &str) -> bool {
824 // `release` (#5906) carried the same `agents/coordinate` authority as
825 // `claim` and is gated identically: a read-only role has no write
826 // scope, so no contention refusal to remediate.
827 if !matches!(action, "claim" | "release") {
828 return true;
829 }
830 self.grant.files == codewhale_agent_contract::worker_profile::FileGrant::Write
831 && !self.is_tool_denied("agents/coordinate")
832 }
833
834 pub fn visibility_representative_input(&self, name: &str) -> Option<Value> {
835 // Visibility and dispatch consult the same capability guard. These
836 // representative calls let a read-only bash schema survive catalog
837 // shaping without treating an empty input as arbitrary shell authority.
838 if self.grant.shell != codewhale_agent_contract::worker_profile::ShellGrant::Inspect {
839 return None;
840 }
841 match name {
842 "bash" => Some(json!({"command": "pwd"})),
843 _ => None,
844 }
845 }
846
847 pub fn can_admit_any_mcp_tool(&self) -> bool {
848 (self.grant.surface != codewhale_agent_contract::worker_profile::ToolSurface::Evidence
849 || self.grant.scope.as_ref().is_some_and(|scope| {
850 scope
851 .iter()
852 .any(|name| crate::mcp::McpPool::is_mcp_tool(name) && !name.contains('*'))
853 }))
854 && self.grant.network
855 && !self.grant.scope.as_ref().is_some_and(Vec::is_empty)
856 && !self.is_tool_denied("mcp*")
857 }
858
859 pub async fn admitted_mcp_servers(
860 self: &Arc<Self>,
861 runtime: &SubAgentRuntime,
862 ) -> HashSet<String> {
863 if !self.can_admit_any_mcp_tool() {
864 return HashSet::new();
865 }
866 let Some(pool) = runtime.mcp_pool.as_ref() else {
867 return HashSet::new();
868 };
869 let routes = {
870 let guard = pool.lock().await;
871 guard.resolved_tool_servers()
872 };
873 if routes.is_empty() {
874 return HashSet::new();
875 }
876 let mcp_registry = ToolRegistryBuilder::new()
877 .with_mcp_tools(Arc::clone(pool))
878 .await
879 .build(self.context());
880 self.tools_for_model(&mcp_registry, &self.agent_type)
881 .into_iter()
882 .filter_map(|tool| routes.get(&tool.name).cloned())
883 .collect()
884 }
885
886 pub(crate) fn connected_mcp_tools_for_model(
887 &self,
888 registry: &ToolRegistry,
889 connected: Vec<Tool>,
890 ) -> Vec<Tool> {
891 let connected: HashSet<_> = connected.into_iter().map(|tool| tool.name).collect();
892 self.tools_for_model(registry, &self.agent_type)
893 .into_iter()
894 .filter(|tool| connected.contains(&tool.name))
895 .collect()
896 }
897
898 pub fn tools_for_model(&self, registry: &ToolRegistry, agent_type: &FleetRole) -> Vec<Tool> {
899 // Filter the full registry in deny-first order. These catalog filters
900 // reduce accidental exposure, but are never the authority boundary:
901 // execute() repeats role, scope, posture, envelope, and claim checks.
902 let _ = agent_type;
903 let api_tools = registry.to_api_tools();
904 let filtered = match &self.grant.scope {
905 None => api_tools,
906 Some(list) => api_tools
907 .into_iter()
908 .filter(|tool| {
909 explicit_scope_permits(list, &tool.name)
910 || is_action_family(&tool.name)
911 && tool.input_schema["properties"]["action"]["enum"]
912 .as_array()
913 .is_some_and(|actions| {
914 actions.iter().any(|action| {
915 action.as_str().is_some_and(|action| {
916 Self::legacy_action_alias(&tool.name, action)
917 .is_some_and(|alias| {
918 list.iter().any(|n| n == alias)
919 })
920 })
921 })
922 })
923 })
924 .collect::<Vec<_>>(),
925 };
926 let mut tools = filtered
927 .into_iter()
928 .filter(|tool| tool.name != "agent" || self.grant.spawn)
929 .filter(|tool| {
930 !self.is_tool_denied(&tool.name) || self.allows_bounded_readonly_bash(&tool.name)
931 })
932 .filter(|tool| !self.grant_blocks_tool(registry, &tool.name))
933 .filter(|tool| {
934 let representative = self.visibility_representative_input(&tool.name);
935 self.posture_permits_tool(registry, &tool.name, representative.as_ref())
936 })
937 .filter(|tool| {
938 if is_action_family(&tool.name) {
939 return true;
940 }
941 let representative = self
942 .visibility_representative_input(&tool.name)
943 .unwrap_or_else(|| json!({}));
944 self.envelope_permits(registry, &tool.name, &representative)
945 })
946 .collect::<Vec<_>>();
947
948 for tool in &mut tools {
949 if tool.name == "bash"
950 && self.grant.shell == codewhale_agent_contract::worker_profile::ShellGrant::Inspect
951 {
952 crate::tools::shell::strip_readonly_bash_schema_properties(&mut tool.input_schema);
953 }
954 if !is_action_family(&tool.name) {
955 continue;
956 }
957 // Indexing `["properties"]["action"]["enum"]` mutably would
958 // fabricate an `"action": {"enum": null}` property on schemas
959 // that have no action discriminator (the lowercase `bash`
960 // command/timeout shape) — a phantom node that fails Moonshot
961 // MFJS validation. Only shape enums that already exist.
962 let Some(actions) = tool
963 .input_schema
964 .pointer_mut("/properties/action/enum")
965 .and_then(serde_json::Value::as_array_mut)
966 else {
967 continue;
968 };
969 actions.retain(|action| {
970 let Some(action) = action.as_str() else {
971 return false;
972 };
973 let evidence_action = self.grant.surface
974 != codewhale_agent_contract::worker_profile::ToolSurface::Evidence
975 || tool.name != "Web"
976 || matches!(action, "search" | "fetch");
977 let mut representative = self
978 .visibility_representative_input(&tool.name)
979 .unwrap_or_else(|| json!({}));
980 representative["action"] = json!(action);
981 evidence_action
982 && self.is_action_allowed(&tool.name, action)
983 && self.envelope_permits(registry, &tool.name, &representative)
984 });
985 }
986 // `agent` is not a `CANONICAL_ACTION_ALIASES` family, so the pruner
987 // above never reaches it — and it must not become one, because
988 // `canonical_action_alias` feeds `execution_envelope`, where `agent`'s
989 // `ExecutesCode` capability is deliberately reclassified `Bounded`.
990 // Shape its enum explicitly instead.
991 for tool in &mut tools {
992 if tool.name != "agent" {
993 continue;
994 }
995 let Some(actions) = tool
996 .input_schema
997 .pointer_mut("/properties/action/enum")
998 .and_then(serde_json::Value::as_array_mut)
999 else {
1000 continue;
1001 };
1002 actions.retain(|action| {
1003 action
1004 .as_str()
1005 .is_some_and(|action| self.agent_action_permitted(action))
1006 });
1007 }
1008 tools.retain(|tool| {
1009 tool.input_schema["properties"]["action"]["enum"]
1010 .as_array()
1011 .is_none_or(|actions| !actions.is_empty())
1012 });
1013 tools
1014 }
1015 }
1016
1017 /// Worker metadata and its existing transcript projection. Core Session remains
1018 /// the request/history owner; these snapshots are delivery/resume receipts.
1019 pub struct ChildJob {
1020 pub authority: Arc<ChildAuthority>,
1021 pub assignment: SubAgentAssignment,
1022 pub started_at: Instant,
1023 pub max_steps: u32,
1024 pub deadline: Option<Instant>,
1025 pub fork_context: bool,
1026 parking: Option<Arc<std::sync::atomic::AtomicBool>>,
1027 artifact: Arc<tokio::sync::Mutex<Option<SubAgentTranscriptArtifactWriter>>>,
1028 pub requests: std::sync::atomic::AtomicU32,
1029 logical_steps: std::sync::atomic::AtomicU32,
1030 initial_submission_assigned: std::sync::atomic::AtomicBool,
1031 response_received: std::sync::atomic::AtomicBool,
1032 selected_model: std::sync::Mutex<String>,
1033 stop_reason: std::sync::Mutex<Option<(String, AgentLimitKind)>>,
1034 activation_provider_stop: std::sync::Mutex<Option<String>>,
1035 activation_admission_index: std::sync::Mutex<Option<usize>>,
1036 activation_terminal_stop:
1037 std::sync::Mutex<codewhale_agent_contract::worker_profile::ChildActivationStopReason>,
1038 }
1039 impl ChildJob {
1040 pub async fn admitted(
1041 authority: Arc<ChildAuthority>,
1042 assignment: SubAgentAssignment,
1043 started_at: Instant,
1044 max_steps: u32,
1045 fork_context: bool,
1046 parking: Option<Arc<std::sync::atomic::AtomicBool>>,
1047 ) -> Result<Arc<Self>> {
1048 let deadline = budget_handback::wall_deadline(&authority.runtime);
1049 let artifact = SubAgentTranscriptArtifactWriter::for_runtime(
1050 &authority.runtime,
1051 &authority.owner_agent_id,
1052 )
1053 .await?;
1054 let selected_model = authority.runtime.model.clone();
1055 let _ = tokio::runtime::Handle::try_current()
1056 .map_err(|_| anyhow!("child admission requires the existing Engine scheduler"))?;
1057 Ok(Arc::new(Self {
1058 authority,
1059 assignment,
1060 started_at,
1061 max_steps,
1062 deadline,
1063 fork_context,
1064 parking,
1065 artifact: Arc::new(tokio::sync::Mutex::new(Some(artifact))),
1066 requests: std::sync::atomic::AtomicU32::new(0),
1067 logical_steps: std::sync::atomic::AtomicU32::new(0),
1068 initial_submission_assigned: std::sync::atomic::AtomicBool::new(false),
1069 response_received: std::sync::atomic::AtomicBool::new(false),
1070 selected_model: std::sync::Mutex::new(selected_model),
1071 stop_reason: std::sync::Mutex::new(None),
1072 activation_provider_stop: std::sync::Mutex::new(None),
1073 activation_admission_index: std::sync::Mutex::new(None),
1074 activation_terminal_stop: std::sync::Mutex::new(
1075 codewhale_agent_contract::worker_profile::ChildActivationStopReason::Error,
1076 ),
1077 }))
1078 }
1079 pub fn take_initial_submission_id(&self) -> Option<String> {
1080 let activation = self.authority.runtime.activation.as_ref()?;
1081 (!self
1082 .initial_submission_assigned
1083 .swap(true, std::sync::atomic::Ordering::AcqRel))
1084 .then(|| activation.identity.initial_submission_id.clone())
1085 }
1086
1087 pub async fn record_initial_admission(
1088 &self,
1089 submission_id: Option<&str>,
1090 turn_id: &str,
1091 messages: &[Message],
1092 ) -> Result<()> {
1093 let Some(activation) = self.authority.runtime.activation.as_ref() else {
1094 return Ok(());
1095 };
1096 let Some(submission_id) = submission_id else {
1097 return Ok(());
1098 };
1099 anyhow::ensure!(
1100 submission_id == activation.identity.initial_submission_id,
1101 "child initial submission identity changed"
1102 );
1103 let message_index = messages
1104 .len()
1105 .checked_sub(1)
1106 .ok_or_else(|| anyhow!("child initial input was not appended"))?;
1107 anyhow::ensure!(
1108 messages[message_index].role == codewhale_models::Role::User,
1109 "child initial input is not a user message"
1110 );
1111 self.project(messages, self.steps()).await?;
1112 let message_index = self
1113 .artifact
1114 .lock()
1115 .await
1116 .as_ref()
1117 .and_then(|writer| writer.persisted_messages.checked_sub(1))
1118 .ok_or_else(|| anyhow!("child initial input has no durable transcript index"))?;
1119 use sha2::Digest as _;
1120 let prefix_sha256 = sha2::Sha256::digest(serde_json::to_vec(messages)?)
1121 .iter()
1122 .map(|byte| format!("{byte:02x}"))
1123 .collect();
1124 super::record_child_admission(
1125 &self.authority.runtime.manager,
1126 &activation.identity,
1127 codewhale_agent_contract::worker_profile::ChildInitialAdmission {
1128 submission_id: submission_id.to_owned(),
1129 turn_id: turn_id.to_owned(),
1130 message_index,
1131 prefix_sha256,
1132 },
1133 )
1134 .await?;
1135 *self
1136 .activation_admission_index
1137 .lock()
1138 .unwrap_or_else(|error| error.into_inner()) = Some(message_index);
1139 Ok(())
1140 }
1141
1142 pub async fn record_route_replacement(
1143 &self,
1144 current: &SubAgentRuntime,
1145 next: &SubAgentRuntime,
1146 source: SpawnRouteSource,
1147 note: String,
1148 error: &anyhow::Error,
1149 ) {
1150 let mut manager = self.authority.runtime.manager.write().await;
1151 if let Some(origin) = current.route_origin.as_deref() {
1152 manager.record_refused_route(
1153 &origin.route,
1154 &current.client.redact_model_bound_text(&error.to_string()),
1155 );
1156 }
1157 manager.record_route_replacement(&self.authority.owner_agent_id, next, source, note);
1158 }
1159 pub fn can_replace_first_request(&self) -> bool {
1160 self.steps() == 1
1161 && !self
1162 .response_received
1163 .load(std::sync::atomic::Ordering::Acquire)
1164 && !self.authority.runtime.cancel_token.is_cancelled()
1165 }
1166 pub fn installed_replacement(&self, model: &str) {
1167 self.logical_steps
1168 .store(0, std::sync::atomic::Ordering::Relaxed);
1169 *self
1170 .selected_model
1171 .lock()
1172 .unwrap_or_else(std::sync::PoisonError::into_inner) = model.to_owned();
1173 }
1174 pub async fn record_request_nudge(
1175 &self,
1176 turn_id: &str,
1177 request_index: u32,
1178 text: &str,
1179 cancel: &CancellationToken,
1180 ) -> Result<()> {
1181 let deadline = self
1182 .deadline
1183 .map(tokio::time::Instant::from_std)
1184 .into_iter()
1185 .chain(self.authority.runtime.context.turn_deadline)
1186 .chain(Some(
1187 tokio::time::Instant::now() + self.authority.runtime.tool_timeout,
1188 ))
1189 .min()
1190 .expect("captured tool timeout bounds receipt persistence");
1191 let artifact = self.artifact.clone();
1192 let acquire = tokio::time::timeout_at(deadline, artifact.lock_owned());
1193 let mut artifact = tokio::select! {
1194 biased;
1195 () = cancel.cancelled() => return Err(anyhow!("child request receipt cancelled")),
1196 () = self.authority.runtime.cancel_token.cancelled() => return Err(anyhow!("child request receipt cancelled")),
1197 result = acquire => result.map_err(|_| anyhow!("child request receipt deadline elapsed"))?,
1198 };
1199 let turn_id = turn_id.to_string();
1200 let text = text.to_string();
1201 let persist = tokio::task::spawn_blocking(move || {
1202 artifact
1203 .as_mut()
1204 .ok_or_else(|| anyhow!("child transcript writer is unavailable"))?
1205 .record_request_nudge(&turn_id, request_index, &text)
1206 });
1207 tokio::select! {
1208 biased;
1209 () = cancel.cancelled() => Err(anyhow!("child request receipt cancelled")),
1210 () = self.authority.runtime.cancel_token.cancelled() => Err(anyhow!("child request receipt cancelled")),
1211 result = tokio::time::timeout_at(deadline, persist) => result
1212 .map_err(|_| anyhow!("child request receipt deadline elapsed"))?
1213 .map_err(|error| anyhow!("child receipt writer failed: {error}"))?,
1214 }
1215 }
1216
1217 pub async fn project(&self, messages: &[Message], steps: u32) -> Result<()> {
1218 let mut artifact = self.artifact.try_lock().map_err(|_| {
1219 anyhow!("child transcript writer is still busy; checkpoint not advanced")
1220 })?;
1221 if let Some(writer) = artifact.as_mut() {
1222 writer.sync_messages(messages, true)?;
1223 }
1224 let checkpoint = checkpoint_subagent_progress(
1225 &self.authority.runtime,
1226 &self.authority.owner_agent_id,
1227 "Core child Session checkpoint",
1228 messages,
1229 steps,
1230 true,
1231 )
1232 .await;
1233 publish_live_subagent_transcript(
1234 &self.authority.runtime,
1235 &self.authority.owner_agent_id,
1236 &self.authority.agent_type,
1237 &self.assignment,
1238 None,
1239 Some(&checkpoint),
1240 artifact.as_mut(),
1241 messages,
1242 steps,
1243 self.started_at,
1244 self.fork_context,
1245 )
1246 .await;
1247 Ok(())
1248 }
1249 pub async fn before_replace(&self, old: &[Message], new: &[Message]) -> Result<()> {
1250 let mut artifact = self.artifact.lock().await;
1251 if let Some(writer) = artifact.as_mut() {
1252 writer.sync_messages(old, true)?;
1253 writer.record_compaction(old, new)?;
1254 writer.append_messages(&[], true)?;
1255 }
1256 Ok(())
1257 }
1258 pub(crate) fn stop_for_limit(&self, kind: AgentLimitKind) {
1259 let reason = match kind {
1260 AgentLimitKind::Step => "child model-step work budget exhausted",
1261 AgentLimitKind::WallTime => "child wall-time work budget exhausted",
1262 };
1263 self.stop_reason
1264 .lock()
1265 .unwrap_or_else(std::sync::PoisonError::into_inner)
1266 .get_or_insert_with(|| (reason.to_owned(), kind));
1267 }
1268 pub fn budget_reason(&self) -> Option<String> {
1269 self.stop_reason
1270 .lock()
1271 .unwrap_or_else(std::sync::PoisonError::into_inner)
1272 .as_ref()
1273 .map(|(reason, _)| reason.clone())
1274 }
1275 pub fn steps(&self) -> u32 {
1276 self.logical_steps
1277 .load(std::sync::atomic::Ordering::Relaxed)
1278 }
1279 pub fn provider_refused(&self, error: &anyhow::Error) {
1280 if !provider_request_refusal_proven(error) {
1281 self.response_received
1282 .store(true, std::sync::atomic::Ordering::Release);
1283 }
1284 if matches!(
1285 error.downcast_ref::<LlmError>(),
1286 Some(LlmError::RateLimited { .. } | LlmError::QuotaWindow { .. })
1287 ) && let Some(governor) = self.authority.runtime.governor.as_ref()
1288 {
1289 governor.record_rate_limited(Instant::now());
1290 }
1291 }
1292 pub fn dispatched(
1293 self: &Arc<Self>,
1294 logical_step: u32,
1295 source: String,
1296 route: crate::cost_status::EffectiveRouteEnvelope,
1297 ) -> ChildDispatchedRequest {
1298 if let Some(governor) = self.authority.runtime.governor.as_ref() {
1299 governor.record_attempt(Instant::now());
1300 }
1301 self.logical_steps
1302 .fetch_max(logical_step, std::sync::atomic::Ordering::Relaxed);
1303 self.requests
1304 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1305 let origin = self.authority.usage_origin();
1306 ChildDispatchedRequest {
1307 accounting_source: crate::cost_status::NativeUsageSource::capture_with_origin(
1308 source,
1309 crate::cost_status::UsageSpendOwner::Auxiliary,
1310 origin,
1311 ),
1312 job: self.clone(),
1313 route,
1314 settled: None,
1315 }
1316 }
1317 pub fn record_activation_provider_stop(&self, reason: Option<&str>, failed: bool) {
1318 if self.authority.runtime.activation.is_none() {
1319 return;
1320 }
1321 *self
1322 .activation_provider_stop
1323 .lock()
1324 .unwrap_or_else(|error| error.into_inner()) =
1325 (!failed).then(|| reason.map(str::to_owned)).flatten();
1326 }
1327
1328 pub fn record_activation_terminal_stop(
1329 &self,
1330 status: crate::core::events::TurnOutcomeStatus,
1331 cancelled: bool,
1332 ) {
1333 use codewhale_agent_contract::worker_profile::ChildActivationStopReason as Stop;
1334 let provider = self
1335 .activation_provider_stop
1336 .lock()
1337 .unwrap_or_else(|error| error.into_inner());
1338 let stop = if cancelled {
1339 Stop::Aborted
1340 } else if self.budget_reason().is_some() {
1341 Stop::Error
1342 } else if matches!(provider.as_deref(), Some("refusal")) {
1343 Stop::Refusal
1344 } else if status == crate::core::events::TurnOutcomeStatus::Completed {
1345 Stop::Completed
1346 } else if codewhale_models::is_output_limit_stop_reason(provider.as_deref()) {
1347 Stop::MaxTokens
1348 } else {
1349 Stop::Error
1350 };
1351 *self
1352 .activation_terminal_stop
1353 .lock()
1354 .unwrap_or_else(|error| error.into_inner()) = stop;
1355 }
1356
1357 async fn capture_activation_output_off_runtime(
1358 &self,
1359 admission: usize,
1360 streamed_text: String,
1361 ) -> Result<Option<codewhale_agent_contract::worker_profile::ChildActivationOutput>> {
1362 let artifact = self.artifact.clone();
1363 let owner_agent_id = self.authority.owner_agent_id.clone();
1364 tokio::task::spawn_blocking(move || {
1365 let mut artifact = artifact.blocking_lock();
1366 let writer = artifact
1367 .as_mut()
1368 .ok_or_else(|| anyhow!("child transcript writer is unavailable"))?;
1369 writer.append_messages(&[], true)?;
1370 let messages =
1371 super::load_subagent_transcript_artifact(&writer.state_root, &owner_agent_id)?;
1372 let selected =
1373 messages
1374 .iter()
1375 .enumerate()
1376 .skip(admission + 1)
1377 .rev()
1378 .find(|(_, message)| {
1379 matches!(
1380 message.role,
1381 codewhale_models::Role::Assistant
1382 | codewhale_models::Role::InterruptedAssistant
1383 ) && !message.content.is_empty()
1384 });
1385 let selected = if let Some((index, message)) = selected {
1386 Some((index, message.content.clone()))
1387 } else if !streamed_text.is_empty() {
1388 let message = Message {
1389 role: codewhale_models::Role::InterruptedAssistant,
1390 content: vec![ContentBlock::Text {
1391 text: streamed_text,
1392 cache_control: None,
1393 }],
1394 };
1395 let index = writer.persisted_messages;
1396 writer.append_messages(std::slice::from_ref(&message), true)?;
1397 Some((index, message.content))
1398 } else {
1399 None
1400 };
1401 selected
1402 .map(|(index, content)| -> Result<codewhale_agent_contract::worker_profile::ChildActivationOutput> {
1403 use sha2::Digest as _;
1404 Ok(
1405 codewhale_agent_contract::worker_profile::ChildActivationOutput {
1406 transcript_message_index: index,
1407 content_sha256: sha2::Sha256::digest(serde_json::to_vec(&content)?)
1408 .iter()
1409 .map(|byte| format!("{byte:02x}"))
1410 .collect(),
1411 },
1412 )
1413 })
1414 .transpose()
1415 })
1416 .await
1417 .map_err(|error| anyhow!("child activation output capture failed: {error}"))?
1418 }
1419
1420 async fn capture_activation_output(&self, streamed_text: String) -> Result<()> {
1421 let Some(activation) = self.authority.runtime.activation.as_ref() else {
1422 return Ok(());
1423 };
1424 let admission = *self
1425 .activation_admission_index
1426 .lock()
1427 .unwrap_or_else(|error| error.into_inner());
1428 let Some(admission) = admission else {
1429 return Ok(());
1430 };
1431 let output = self
1432 .capture_activation_output_off_runtime(admission, streamed_text)
1433 .await?;
1434 let stop_reason = *self
1435 .activation_terminal_stop
1436 .lock()
1437 .unwrap_or_else(|error| error.into_inner());
1438 super::record_child_output(
1439 &self.authority.runtime.manager,
1440 &activation.identity,
1441 output,
1442 stop_reason,
1443 )
1444 .await
1445 }
1446
1447 async fn sync_transcript_artifact_metadata(
1448 &self,
1449 messages: &[Message],
1450 durable: bool,
1451 ) -> Option<Value> {
1452 let artifact = self.artifact.clone();
1453 let agent_id = self.authority.owner_agent_id.clone();
1454 let messages = messages.to_vec();
1455 tokio::task::spawn_blocking(move || {
1456 let mut artifact = artifact.blocking_lock();
1457 sync_transcript_artifact_metadata(artifact.as_mut(), &agent_id, &messages, durable)
1458 })
1459 .await
1460 .unwrap_or_else(|error| {
1461 tracing::warn!(
1462 target: "subagent",
1463 ?error,
1464 agent_id = %self.authority.owner_agent_id,
1465 "failed to join sub-agent transcript artifact sync task"
1466 );
1467 None
1468 })
1469 }
1470
1471 pub fn provider_responded(&self) {
1472 // Even an incomplete/failed decoder means the provider accepted this
1473 // request. It is never eligible for first-request route replacement.
1474 self.response_received
1475 .store(true, std::sync::atomic::Ordering::Release);
1476 }
1477 pub fn response_settled(&self, success: bool) {
1478 if success && let Some(governor) = self.authority.runtime.governor.as_ref() {
1479 governor.record_success(Instant::now());
1480 }
1481 }
1482 pub async fn finish(
1483 &self,
1484 messages: &[Message],
1485 steps: u32,
1486 status: SubAgentStatus,
1487 text: Option<String>,
1488 reason: Option<&str>,
1489 ) -> Result<SubAgentResult> {
1490 self.project(messages, steps).await?;
1491 self.finish_projected(messages, steps, status, text, reason)
1492 .await
1493 }
1494
1495 async fn finish_projected(
1496 &self,
1497 messages: &[Message],
1498 steps: u32,
1499 status: SubAgentStatus,
1500 text: Option<String>,
1501 reason: Option<&str>,
1502 ) -> Result<SubAgentResult> {
1503 if self.authority.runtime.cancel_token.is_cancelled() {
1504 // `project` has durably synced this exact Core Session and updated
1505 // the captured worker. Return that checkpoint rather than discarding
1506 // it while projecting the cancellation result.
1507 let checkpoint = self
1508 .authority
1509 .runtime
1510 .manager
1511 .read()
1512 .await
1513 .get_result(&self.authority.owner_agent_id)?
1514 .checkpoint;
1515 let artifact_metadata = self.sync_transcript_artifact_metadata(messages, true).await;
1516 return Ok(cancelled_subagent_result(
1517 &self.authority.runtime,
1518 &self.authority.owner_agent_id,
1519 &self.authority.agent_type,
1520 &self.assignment,
1521 messages,
1522 steps,
1523 self.max_steps,
1524 checkpoint.as_ref(),
1525 self.parking.as_ref(),
1526 artifact_metadata,
1527 self.started_at,
1528 self.fork_context,
1529 " in Core child turn",
1530 )
1531 .await);
1532 }
1533 let repaired_messages;
1534 let messages = if status == SubAgentStatus::BudgetExhausted {
1535 let mut cloned = messages.to_vec();
1536 budget_handback::repair_stopped_tool_calls(
1537 &mut cloned,
1538 reason.unwrap_or("child work budget exhausted"),
1539 );
1540 repaired_messages = cloned;
1541 repaired_messages.as_slice()
1542 } else {
1543 messages
1544 };
1545 let checkpoint = build_subagent_checkpoint(
1546 &self.authority.owner_agent_id,
1547 reason.unwrap_or_else(|| subagent_status_name(&status)),
1548 messages,
1549 steps,
1550 matches!(status, SubAgentStatus::Interrupted(_)),
1551 );
1552 let duration_ms = u64::try_from(self.started_at.elapsed().as_millis()).unwrap_or(u64::MAX);
1553 let artifact_metadata = self
1554 .sync_transcript_artifact_metadata(messages, status != SubAgentStatus::Running)
1555 .await;
1556 insert_subagent_full_transcript_handle_with_metadata(
1557 &self.authority.runtime,
1558 &self.authority.owner_agent_id,
1559 &self.authority.agent_type,
1560 &self.assignment,
1561 &status,
1562 text.as_ref(),
1563 Some(&checkpoint),
1564 artifact_metadata,
1565 messages,
1566 steps,
1567 duration_ms,
1568 self.fork_context,
1569 )
1570 .await;
1571 let mut result = self
1572 .authority
1573 .runtime
1574 .manager
1575 .read()
1576 .await
1577 .get_result(&self.authority.owner_agent_id)?;
1578 result.status = status;
1579 result.result = text;
1580 result.steps_taken = steps;
1581 result.checkpoint = Some(checkpoint);
1582 result.duration_ms = duration_ms;
1583 result.model = self
1584 .selected_model
1585 .lock()
1586 .unwrap_or_else(std::sync::PoisonError::into_inner)
1587 .clone();
1588 result.needs_input = match &result.status {
1589 SubAgentStatus::Interrupted(reason) => result
1590 .checkpoint
1591 .as_ref()
1592 .map(|checkpoint| needs_input_for_interrupted_checkpoint(reason, checkpoint)),
1593 _ => None,
1594 };
1595 result.usage = self
1596 .authority
1597 .runtime
1598 .manager
1599 .read()
1600 .await
1601 .worker_records
1602 .get(&self.authority.owner_agent_id)
1603 .map(|record| record.usage.clone());
1604 if result.status == SubAgentStatus::BudgetExhausted {
1605 let cause = reason.unwrap_or("child work budget exhausted");
1606 let partial = result
1607 .result
1608 .take()
1609 .unwrap_or_else(|| budget_handback::fallback_partial_text(messages));
1610 let preservation_note = budget_work_preservation_note(
1611 &self.authority.runtime.manager,
1612 &self.authority.owner_agent_id,
1613 cause,
1614 )
1615 .await;
1616 let digest = match preservation_note.as_deref() {
1617 Some(note) => format!("{partial}\n\n{note}"),
1618 None => partial.clone(),
1619 };
1620 let artifact = budget_handback::write_digest_artifact(
1621 &self.authority.runtime,
1622 &self.authority.owner_agent_id,
1623 digest,
1624 )
1625 .await;
1626 let mut handback_note = "The host preserves the recorded work without another model request; the assignment is not complete.".to_string();
1627 if let Some(artifact) = artifact {
1628 handback_note.push_str(&format!(
1629 " Recorded work is saved as this child's deliverable: {}.",
1630 artifact.display()
1631 ));
1632 }
1633 if let Some(note) = preservation_note {
1634 handback_note.push(' ');
1635 handback_note.push_str(&note);
1636 }
1637 let kind = self
1638 .stop_reason
1639 .lock()
1640 .unwrap_or_else(std::sync::PoisonError::into_inner)
1641 .as_ref()
1642 .map(|(_, kind)| *kind);
1643 result = budget_partial_result_with_note(result, kind, cause, &handback_note, &partial);
1644 }
1645 release_resident_leases_for(&self.authority.owner_agent_id);
1646 Ok(result)
1647 }
1648 }
1649
1650 /// Exact primary dispatch ownership with durable reservation before invocation.
1651 /// Dropping retains the captured origin's Unknown reservation and any unacknowledged
1652 /// final in the existing journal. Billing precedes worker projection.
1653 pub struct ChildDispatchedRequest {
1654 accounting_source: crate::cost_status::NativeUsageSource,
1655 job: Arc<ChildJob>,
1656 route: crate::cost_status::EffectiveRouteEnvelope,
1657 settled: Option<crate::cost_status::RuntimeUsageRecord>,
1658 }
1659 /// Only a typed authoritative rejection proves the dispatched operation
1660 /// produced no billable response. Network/body/cancellation ambiguity does not.
1661 pub fn provider_request_refusal_proven(error: &anyhow::Error) -> bool {
1662 matches!(
1663 error.downcast_ref::<LlmError>(),
1664 Some(
1665 LlmError::ConnectError { .. }
1666 | LlmError::RateLimited { .. }
1667 | LlmError::QuotaWindow { .. }
1668 | LlmError::QuotaExhausted(_)
1669 | LlmError::AuthenticationError(_)
1670 | LlmError::AuthorizationError(_)
1671 | LlmError::InvalidRequest { .. }
1672 | LlmError::ModelError(_)
1673 | LlmError::ContentPolicyError(_)
1674 | LlmError::ContextLengthError(_)
1675 )
1676 )
1677 }
1678 impl ChildDispatchedRequest {
1679 pub async fn settle_open_error(&mut self, error: &anyhow::Error) {
1680 let wire = self.accounting_source.observed_wire();
1681 let coverage = if wire.last_transmission.is_some() {
1682 wire.usage_coverage(false, false)
1683 } else {
1684 match error.downcast_ref::<LlmError>().map(LlmError::transmission) {
1685 Some(crate::llm_client::RequestTransmission::NotDispatched) => {
1686 crate::llm_client::ProviderUsageCoverage::NotDispatched
1687 }
1688 Some(crate::llm_client::RequestTransmission::Rejected) => {
1689 crate::llm_client::ProviderUsageCoverage::Rejected
1690 }
1691 _ => crate::llm_client::ProviderUsageCoverage::Missing,
1692 }
1693 };
1694 let record = self.accounting_source.prepare_record(
1695 &self.route,
1696 &Usage::default(),
1697 coverage,
1698 crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown,
1699 &wire,
1700 );
1701 let accounting = self.job.authority.accounting_projection();
1702 let _ = accounting.publish_async(&record).await;
1703 if let Err(error) = accounting.project_settled(&record).await {
1704 tracing::warn!(%error, "worker usage projection failed");
1705 }
1706 self.settled = Some(record);
1707 }
1708 pub async fn settle(&mut self, usage: &Usage, complete: bool) {
1709 let reason = if complete {
1710 crate::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage
1711 } else {
1712 crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown
1713 };
1714 let coverage = if complete && usage_has_reported_data(usage) {
1715 crate::llm_client::ProviderUsageCoverage::Reported
1716 } else if usage_has_reported_data(usage) {
1717 crate::llm_client::ProviderUsageCoverage::Incomplete
1718 } else {
1719 crate::llm_client::ProviderUsageCoverage::Missing
1720 };
1721 let record = self.accounting_source.prepare_record(
1722 &self.route,
1723 usage,
1724 coverage,
1725 reason,
1726 &self.accounting_source.observed_wire(),
1727 );
1728 let accounting = self.job.authority.accounting_projection();
1729 let _ = accounting.publish_async(&record).await;
1730 self.settled = Some(record.clone());
1731 if let Err(error) = accounting.project_settled(&record).await {
1732 tracing::warn!(%error, "worker usage publication failed");
1733 }
1734 }
1735 }
1736
1737 #[derive(Debug)]
1738 pub(super) struct UnsettledChildCancellation(pub(super) String);
1739 impl std::fmt::Display for UnsettledChildCancellation {
1740 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1741 write!(f, "{}; approval receipts may remain pending", self.0)
1742 }
1743 }
1744 impl std::error::Error for UnsettledChildCancellation {}
1745
1746 struct ChildActorGuard {
1747 handle: crate::core::engine::EngineHandle,
1748 actor: tokio::task::AbortHandle,
1749 joined: bool,
1750 }
1751 impl Drop for ChildActorGuard {
1752 fn drop(&mut self) {
1753 if self.joined {
1754 return;
1755 }
1756 self.handle.cancel();
1757 self.actor.abort();
1758 // Emergency abandonment cannot promise a durable decision. Preserve
1759 // unmatched Asked receipts for the existing protected recovery reader;
1760 // routine Stop stays in drive_child_actor through the owned join.
1761 }
1762 }
1763
1764 /// One existing input's pending-count receipt. The actual Core outcome owns
1765 /// commit/drop; abandoning the transport also retires its UI pending counter.
1766 #[cfg(any(test, feature = "test-support"))]
1767 pub fn send_test_child_input(
1768 tx: &mpsc::UnboundedSender<SubAgentInput>,
1769 text: &str,
1770 interrupt: bool,
1771 pending: Arc<std::sync::atomic::AtomicUsize>,
1772 ) {
1773 tx.send(SubAgentInput {
1774 text: text.into(),
1775 interrupt,
1776 pending: Some(pending),
1777 })
1778 .unwrap();
1779 }
1780
1781 struct InputSettlement(SubAgentInput);
1782 impl Drop for InputSettlement {
1783 fn drop(&mut self) {
1784 self.0.mark_taken();
1785 }
1786 }
1787
1788 /// One transport adapter into the same Core actor and its run_turn pipeline.
1789 /// It owns no provider, tool planning, approval decision, or request history.
1790 #[allow(clippy::too_many_arguments)]
1791 pub(super) async fn run_child_agent(
1792 runtime: &SubAgentRuntime,
1793 agent_id: String,
1794 agent_type: FleetRole,
1795 prompt: String,
1796 assignment: SubAgentAssignment,
1797 allowed_tools: Option<Vec<String>>,
1798 fork_context: bool,
1799 started_at: Instant,
1800 max_steps: u32,
1801 parking: Option<Arc<std::sync::atomic::AtomicBool>>,
1802 input_rx: mpsc::UnboundedReceiver<SubAgentInput>,
1803 ) -> Result<SubAgentResult> {
1804 let allow_mcp = !matches!(agent_type, FleetRole::Scout | FleetRole::Reviewer);
1805 let (runtime, attachment) = if runtime.cancel_token.is_cancelled() {
1806 (runtime.clone(), None)
1807 } else {
1808 prepare_child_membership(runtime, &assignment, &agent_id, allow_mcp).await?
1809 };
1810 let (owner_agent_name, executed_actions) = {
1811 let manager = runtime.manager.read().await;
1812 let name = manager
1813 .get_result(&agent_id)
1814 .map(|agent| subagent_result_display_name(&agent))
1815 .unwrap_or_else(|_| {
1816 assignment
1817 .role
1818 .clone()
1819 .unwrap_or_else(|| agent_type.as_str().to_owned())
1820 });
1821 (name, manager.executed_actions_handle(&agent_id))
1822 };
1823 let branch_workspace = runtime.context.workspace.clone();
1824 let branch = tokio::task::spawn_blocking(move || current_git_branch(&branch_workspace))
1825 .await
1826 .ok()
1827 .flatten();
1828 let mut authority = ChildAuthority::capture(
1829 runtime.clone(),
1830 agent_type.clone(),
1831 agent_id.clone(),
1832 owner_agent_name.clone(),
1833 allowed_tools.clone(),
1834 );
1835 let identity = subagent_capability_block(
1836 &owner_agent_name,
1837 &runtime,
1838 &authority.grant,
1839 branch.as_deref(),
1840 );
1841 if let Some(actions) = executed_actions
1842 && let Some(auth) = Arc::get_mut(&mut authority)
1843 {
1844 auth.executed_actions = actions;
1845 }
1846 let mut system =
1847 build_subagent_system_prompt_with_memory(&agent_type, &assignment, &runtime.context);
1848 if let Some(persona) = runtime
1849 .activation
1850 .as_ref()
1851 .and_then(|activation| activation.configuration.persona.as_deref())
1852 {
1853 anyhow::ensure!(
1854 persona.len() <= 32 * 1024,
1855 "child persona exceeds the reviewed limit"
1856 );
1857 system.push_str("\n\n");
1858 system.push_str(persona);
1859 }
1860 if let Some(schema) = runtime.workflow_response_schema.as_ref() {
1861 system = system
1862 .replace(SUBAGENT_OUTPUT_FORMAT, "")
1863 .replace(WRITE_CHILD_VERIFY_CONTRACT, "");
1864 system.push_str(&format!(
1865 "\n\nFor this read-only Workflow task, return exactly one JSON value matching the following response schema. This replaces the default report sections and Markdown format. Include the requested findings and evidence in that JSON value, with no surrounding fences or prose.\n{schema}"
1866 ));
1867 }
1868 let prompt = format!(
1869 "{prompt}\n\n{}\n\n{identity}",
1870 child_runtime_budget_context(&runtime, max_steps)
1871 );
1872 let fork = if fork_context {
1873 match runtime.fork_context.as_ref() {
1874 Some(fork) => Some(fork.with_resolved_state_block().await),
1875 None => None,
1876 }
1877 } else {
1878 None
1879 };
1880 let mut seed = build_initial_subagent_messages_with_system(
1881 &prompt,
1882 &assignment,
1883 &agent_type,
1884 &system,
1885 fork.as_ref(),
1886 );
1887 let admitted_mcp_servers = authority.admitted_mcp_servers(&runtime).await;
1888 crate::core::engine::filter_messages_mcp_server_instructions(&mut seed, &admitted_mcp_servers);
1889 let initial = seed
1890 .pop()
1891 .ok_or_else(|| anyhow!("child assignment has no task message"))?;
1892 if let Some(section) =
1893 subagent_inherited_instructions_section(&runtime.parent_pinned_project_instructions)
1894 {
1895 system.push_str("\n\n");
1896 system.push_str(&section);
1897 }
1898 let content = initial
1899 .content
1900 .iter()
1901 .filter_map(|block| match block {
1902 ContentBlock::Text { text, .. } => Some(text.as_str()),
1903 _ => None,
1904 })
1905 .collect::<Vec<_>>()
1906 .join("\n");
1907 let job = ChildJob::admitted(
1908 authority.clone(),
1909 assignment,
1910 started_at,
1911 max_steps,
1912 fork_context,
1913 parking,
1914 )
1915 .await?;
1916 if runtime.cancel_token.is_cancelled() {
1917 // No tool/model is admitted. Preserve the same full seed and the
1918 // existing Park-vs-Cancel projection, including a step-zero checkpoint.
1919 seed.push(initial);
1920 let artifact_metadata = {
1921 let artifact = job.artifact.clone();
1922 let agent_id = agent_id.clone();
1923 let messages = seed.clone();
1924 tokio::task::spawn_blocking(move || -> Result<Option<Value>> {
1925 let mut artifact = artifact.blocking_lock();
1926 if let Some(writer) = artifact.as_mut() {
1927 writer.sync_messages(&messages, false)?;
1928 }
1929 Ok(sync_transcript_artifact_metadata(
1930 artifact.as_mut(),
1931 &agent_id,
1932 &messages,
1933 true,
1934 ))
1935 })
1936 .await
1937 .map_err(|error| anyhow!("child cancelled transcript sync failed: {error}"))??
1938 };
1939 let checkpoint =
1940 build_subagent_checkpoint(&agent_id, "Core child Session checkpoint", &seed, 0, true);
1941 return Ok(cancelled_subagent_result(
1942 &runtime,
1943 &agent_id,
1944 &agent_type,
1945 &job.assignment,
1946 &seed,
1947 0,
1948 max_steps,
1949 Some(&checkpoint),
1950 job.parking.as_ref(),
1951 artifact_metadata,
1952 started_at,
1953 fork_context,
1954 " before Core child admission",
1955 )
1956 .await);
1957 }
1958 let api = runtime.api_config.as_deref().ok_or_else(|| anyhow!(
1959 "child Engine requires its captured provider configuration; no ambient route is admitted"
1960 ))?;
1961 let config = crate::core::engine::EngineConfig {
1962 workspace: runtime.context.workspace.clone(),
1963 model: runtime.model.clone(),
1964 max_steps: codewhale_runtime::turn_budget::resolve_max_model_steps(Some(max_steps)),
1965 compaction: runtime.compaction.clone(),
1966 subagent_api_timeout: runtime.step_api_timeout,
1967 stream_retry_limits: api.stream_retry_limits(),
1968 stream_open_timeout: api.stream_open_timeout(),
1969 auto_review_policy: runtime.auto_review_policy.as_ref().clone(),
1970 tools: api.tools.clone(),
1971 tools_always_load: allowed_tools.iter().flatten().cloned().collect(),
1972 reasoning_only_max_reprompts: api.reasoning_only_max_reprompts(),
1973 reasoning_only_on_output_limit: api.reasoning_only_on_output_limit(),
1974 reasoning_only_reprompt_message: Some(api.reasoning_only_reprompt_message().to_string()),
1975 locale_tag: runtime.locale_tag.clone(),
1976 search_third_party: api.search.as_ref().and_then(|search| search.third_party),
1977 search_consent_implied: api.search_consent_implied(),
1978 ..Default::default()
1979 };
1980 let (mut core, handle) = crate::core::engine::Engine::new_child_admitted(
1981 config,
1982 api,
1983 authority,
1984 subagent_request_system_prompt(&system),
1985 attachment,
1986 )?;
1987 core.install_child_job(job.clone(), seed)?;
1988 let spec = core.child_turn_spec(content, allowed_tools)?;
1989 handle.send(crate::core::ops::Op::SendMessage(spec)).await?;
1990 drive_child_actor(core, handle, job, input_rx).await
1991 }
1992
1993 /// Project an already-decided Core observation under its captured owner.
1994 /// The existing audit/approval writers retain authority; capacity waits are
1995 /// bounded by the caller's cancellation and captured deadline/tool timeout.
1996 pub async fn forward_child_gate_observation(
1997 runtime: &SubAgentRuntime,
1998 owner: &str,
1999 mut event: Event,
2000 cancel: &CancellationToken,
2001 deadline: Option<tokio::time::Instant>,
2002 ) {
2003 let Event::ToolGateDecision {
2004 agent_id,
2005 receipt_id,
2006 call_digest,
2007 ..
2008 } = &mut event
2009 else {
2010 return;
2011 };
2012 if agent_id.is_none() {
2013 *agent_id = Some(owner.to_owned());
2014 }
2015 *receipt_id = None;
2016 *call_digest = None;
2017 let Some(tx) = runtime.event_tx.as_ref() else {
2018 return;
2019 };
2020 let deadline = deadline
2021 .into_iter()
2022 .chain(runtime.context.turn_deadline)
2023 .chain(Some(tokio::time::Instant::now() + runtime.tool_timeout))
2024 .min()
2025 .expect("captured tool timeout bounds observation delivery");
2026 let permit = tokio::select! {
2027 biased;
2028 () = runtime.cancel_token.cancelled() => None,
2029 () = cancel.cancelled() => None,
2030 result = tokio::time::timeout_at(deadline, tx.reserve()) => result.ok().and_then(Result::ok),
2031 };
2032 if let Some(permit) = permit {
2033 permit.send(event);
2034 } else {
2035 // Available capacity can still carry the final observation after
2036 // cancellation. A full/closed host cannot keep the actor alive.
2037 let _ = tx.try_send(event);
2038 }
2039 }
2040
2041 async fn forward_child_request_receipt(
2042 runtime: &SubAgentRuntime,
2043 owner: &str,
2044 message: String,
2045 cancel: &CancellationToken,
2046 deadline: Option<tokio::time::Instant>,
2047 ) {
2048 let deadline = deadline
2049 .into_iter()
2050 .chain(runtime.context.turn_deadline)
2051 .chain(Some(tokio::time::Instant::now() + runtime.tool_timeout))
2052 .min()
2053 .expect("captured tool timeout bounds receipt delivery");
2054 let activity = AgentProgressEventMeta::new(AgentWorkerStatus::Running);
2055 let manager = tokio::select! {
2056 biased;
2057 () = runtime.cancel_token.cancelled() => None,
2058 () = cancel.cancelled() => None,
2059 result = tokio::time::timeout_at(deadline, runtime.manager.write()) => result.ok(),
2060 };
2061 if let Some(mut manager) = manager {
2062 manager.touch(owner);
2063 manager.record_worker_event(
2064 owner,
2065 activity.worker_status,
2066 Some(message.clone()),
2067 activity.step,
2068 activity.tool_name.clone(),
2069 );
2070 }
2071 let Some(tx) = runtime.event_tx.as_ref() else {
2072 return;
2073 };
2074 let event = Event::AgentProgress {
2075 owner_session_id: runtime.context.state_namespace.clone(),
2076 id: owner.to_string(),
2077 status: message,
2078 activity,
2079 parent_run_id: runtime.parent_agent_id.clone(),
2080 spawn_depth: runtime.spawn_depth,
2081 };
2082 let permit = tokio::select! {
2083 biased;
2084 () = runtime.cancel_token.cancelled() => None,
2085 () = cancel.cancelled() => None,
2086 result = tokio::time::timeout_at(deadline, tx.reserve()) => result.ok().and_then(Result::ok),
2087 };
2088 if let Some(permit) = permit {
2089 permit.send(event);
2090 } else {
2091 let _ = tx.try_send(event);
2092 }
2093 }
2094
2095 /// Service the existing Core event/approval/input queues until its actor
2096 /// settles. Shared by the real launch and its exact Core transport tests.
2097 pub async fn drive_child_actor(
2098 core: crate::core::engine::Engine,
2099 handle: crate::core::engine::EngineHandle,
2100 job: Arc<ChildJob>,
2101 mut input_rx: mpsc::UnboundedReceiver<SubAgentInput>,
2102 ) -> Result<SubAgentResult> {
2103 let runtime = job.authority.runtime.clone();
2104 let agent_id = job.authority.owner_agent_id.clone();
2105 let mut actor = tokio::spawn(Box::pin(core.run_child()));
2106 let mut guard = ChildActorGuard {
2107 handle: handle.clone(),
2108 actor: actor.abort_handle(),
2109 joined: false,
2110 };
2111 let mut approvals = futures_util::stream::FuturesUnordered::new();
2112 let mut approval_deliveries = futures_util::stream::FuturesUnordered::<
2113 std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send>>,
2114 >::new();
2115 let mut steers = futures_util::stream::FuturesUnordered::new();
2116 let mut events = handle.rx_event.write().await;
2117 let mut input_open = true;
2118 let mut pending_input: Option<InputSettlement> = None;
2119 let mut cancellation_deadline = None;
2120 let mut tool_names: HashMap<String, String> = HashMap::new();
2121 // The launch permit alone is not a started turn. Project only Core's
2122 // admitted lifecycle event, once across work, report and route retries.
2123 let mut started = false;
2124 let mut streamed_text = String::new();
2125 let mut observe_start = |event: &Event| {
2126 if runtime.activation.is_some()
2127 && let Event::MessageDelta { content, .. } = event
2128 {
2129 streamed_text.push_str(content);
2130 }
2131 if !started && matches!(event, Event::TurnStarted { .. }) {
2132 started = true;
2133 if let Some(mailbox) = runtime.mailbox.as_ref() {
2134 let _ = mailbox.send(MailboxMessage::started(
2135 &agent_id,
2136 job.authority.agent_type.clone(),
2137 ));
2138 }
2139 }
2140 };
2141 let mut result = loop {
2142 if runtime.cancel_token.is_cancelled() && cancellation_deadline.is_none() {
2143 handle.cancel();
2144 cancellation_deadline = Some(tokio::time::Instant::now() + CHILD_STOP_SETTLE_GRACE);
2145 }
2146 use futures_util::StreamExt;
2147 tokio::select! {
2148 biased;
2149 () = runtime.cancel_token.cancelled(), if !handle.is_cancelled() => handle.cancel(),
2150 joined = &mut actor => {
2151 guard.joined = true;
2152 break joined.map_err(|e| anyhow!(UnsettledChildCancellation(format!("child Core actor failed: {e}"))))?;
2153 },
2154 () = async {
2155 match cancellation_deadline {
2156 Some(deadline) => tokio::time::sleep_until(deadline).await,
2157 None => std::future::pending::<()>().await,
2158 }
2159 } => {
2160 actor.abort();
2161 let _ = (&mut actor).await;
2162 guard.joined = true;
2163 break Err(anyhow!(UnsettledChildCancellation("child cancellation settlement deadline elapsed".into())));
2164 },
2165 input = input_rx.recv(), if input_open && pending_input.is_none() => match input {
2166 Some(input) => pending_input = Some(InputSettlement(input)),
2167 None => input_open = false,
2168 },
2169 reservation = handle.reserve_steer(), if pending_input.is_some() => {
2170 let input = pending_input.take().expect("selected pending input");
2171 match reservation {
2172 Ok(permit) => {
2173 let outcome = if input.0.interrupt { permit.send_replacing_with_outcome(input.0.text.clone()) }
2174 else { permit.send_with_outcome(input.0.text.clone()) };
2175 steers.push(async move { let result = outcome.await; (input, result) });
2176 }
2177 Err(_) => drop(input), // Core closed before admission: explicitly dropped.
2178 }
2179 },
2180 Some((input, _outcome)) = steers.next(), if !steers.is_empty() => {
2181 // Core's commit/drop outcome, not transport admission, retires it.
2182 drop(input);
2183 },
2184 Some((id, decision)) = approvals.next(), if !approvals.is_empty() => {
2185 if runtime.cancel_token.is_cancelled() || handle.is_cancelled() {
2186 // Core observes the exact cancelled TurnControl before any
2187 // queued Allow; do not stall its join on another inbox send.
2188 handle.cancel();
2189 } else {
2190 let handle = handle.clone();
2191 approval_deliveries.push(Box::pin(async move {
2192 match decision {
2193 Ok(reply) => handle.accept_child_approval(id, reply).await,
2194 Err(_) => handle.deny_tool_call_unavailable(id).await,
2195 }
2196 }));
2197 }
2198 },
2199 Some(delivered) = approval_deliveries.next(), if !approval_deliveries.is_empty() => {
2200 if let Err(error) = delivered {
2201 tracing::warn!(%error, "child approval did not match a durable Core decision");
2202 }
2203 },
2204 event = events.recv() => {
2205 let Some(event) = event else { break Err(anyhow!("child Core event stream closed before join")); };
2206 observe_start(&event);
2207 match &event {
2208 Event::ApprovalRequired { id, tool_name, description, publication, .. } => {
2209 let (_, answer) = runtime.manager.write().await.register_child_approval(&agent_id, id, tool_name, description, publication.clone())?;
2210 let key = id.clone(); approvals.push(async move { (key, answer.await) });
2211 record_agent_progress(&runtime, &agent_id, AgentProgressEventMeta::new(AgentWorkerStatus::WaitingForUser)
2212 .with_tool(tool_name.clone()).with_approval_id(id.clone()), description.clone());
2213 if let Some(tx) = runtime.event_tx.as_ref().filter(|_| runtime.parent_can_prompt) {
2214 let admitted_cancel = handle.captured_turn_cancel();
2215 let sent = tokio::select! {
2216 biased;
2217 () = runtime.cancel_token.cancelled() => false,
2218 () = admitted_cancel.cancelled() => false,
2219 result = tx.send(event.clone()) => result.is_ok(),
2220 };
2221 if !sent {
2222 if runtime.cancel_token.is_cancelled() || handle.is_cancelled() {
2223 handle.cancel();
2224 } else {
2225 runtime.manager.write().await.cancel_child_approval(id);
2226 {
2227 let handle = handle.clone();
2228 let id = id.clone();
2229 approval_deliveries.push(Box::pin(async move { handle.deny_tool_call_unavailable(id).await }));
2230 }
2231 }
2232 }
2233 } else if runtime.cancel_token.is_cancelled() || handle.is_cancelled() {
2234 handle.cancel();
2235 } else {
2236 runtime.manager.write().await.cancel_child_approval(id);
2237 {
2238 let handle = handle.clone();
2239 let id = id.clone();
2240 approval_deliveries.push(Box::pin(async move { handle.deny_tool_call_unavailable(id).await }));
2241 }
2242 }
2243 }
2244 Event::ApprovalWithdrawn { id } => {
2245 runtime.manager.write().await.cancel_child_approval(id);
2246 if let Some(tx) = runtime.event_tx.as_ref() {
2247 tokio::select! {
2248 biased;
2249 () = runtime.cancel_token.cancelled() => { let _ = tx.try_send(event.clone()); }
2250 result = tx.send(event.clone()) => { let _ = result; }
2251 }
2252 }
2253 }
2254 Event::ToolGateDecision { .. } => {
2255 forward_child_gate_observation(
2256 &runtime,
2257 &agent_id,
2258 event,
2259 &handle.captured_turn_cancel(),
2260 job.deadline.map(Into::into),
2261 ).await;
2262 }
2263 Event::ToolCallStarted { id, name, .. } => {
2264 tool_names.insert(id.clone(), name.clone());
2265 }
2266 Event::ToolExecutionStarted { id } => {
2267 if let Some(mailbox) = runtime.mailbox.as_ref() {
2268 let tool_name = tool_names.get(id).cloned().unwrap_or_else(|| "tool".to_string());
2269 let _ = mailbox.send(MailboxMessage::ToolCallStarted { agent_id: agent_id.clone(), tool_name, step: job.steps() });
2270 }
2271 }
2272 Event::ToolCallComplete { id, name, result, .. } => {
2273 let label = tool_names.remove(id).unwrap_or_else(|| name.clone());
2274 record_agent_progress(&runtime, &agent_id, AgentProgressEventMeta::new(AgentWorkerStatus::RunningTool).with_tool(name.clone()),
2275 format!("{label} {}", if result.is_ok() { "done" } else { "failed" }));
2276 }
2277 Event::Status { message, .. }
2278 if message.starts_with(crate::core::events::REQUEST_NUDGE_RECEIPT_PREFIX) => {
2279 forward_child_request_receipt(&runtime, &agent_id, message.clone(),
2280 &handle.captured_turn_cancel(), job.deadline.map(Into::into)).await;
2281 }
2282 Event::Status { message, .. } => record_agent_progress(&runtime, &agent_id,
2283 AgentProgressEventMeta::new(AgentWorkerStatus::Running), message.clone()),
2284 _ => {} // Session is projected by Core; aggregate usage is never rebilled here.
2285 }
2286 },
2287 }
2288 };
2289 if !guard.joined {
2290 handle.cancel();
2291 result = match tokio::time::timeout(CHILD_STOP_SETTLE_GRACE, &mut actor).await {
2292 Ok(joined) => joined.map_err(|error| {
2293 anyhow!(UnsettledChildCancellation(format!(
2294 "child Core actor failed: {error}"
2295 )))
2296 })?,
2297 Err(_) => {
2298 actor.abort();
2299 let _ = (&mut actor).await;
2300 Err(anyhow!(UnsettledChildCancellation(
2301 "child cancellation settlement deadline elapsed".into()
2302 )))
2303 }
2304 };
2305 guard.joined = true;
2306 }
2307 // The join can win over events already queued by Core. Retain its start
2308 // and final gate observations; this projection never asks or decides a call.
2309 while let Ok(event) = events.try_recv() {
2310 observe_start(&event);
2311 if let Event::ApprovalWithdrawn { id } = &event {
2312 runtime.manager.write().await.cancel_child_approval(id);
2313 if let Some(tx) = &runtime.event_tx {
2314 let _ = tx.try_send(event);
2315 }
2316 } else if let Event::Status { message, .. } = &event
2317 && message.starts_with(crate::core::events::REQUEST_NUDGE_RECEIPT_PREFIX)
2318 {
2319 forward_child_request_receipt(
2320 &runtime,
2321 &agent_id,
2322 message.clone(),
2323 &handle.captured_turn_cancel(),
2324 job.deadline.map(Into::into),
2325 )
2326 .await;
2327 } else if matches!(event, Event::ToolGateDecision { .. }) {
2328 forward_child_gate_observation(
2329 &runtime,
2330 &agent_id,
2331 event,
2332 &handle.captured_turn_cancel(),
2333 job.deadline.map(Into::into),
2334 )
2335 .await;
2336 }
2337 }
2338 // Joining drops the Core receiver and every unsettled steer. Retire those
2339 // exact outcomes even when the join branch won before the outcome branch.
2340 use futures_util::StreamExt;
2341 while let Some(delivered) = approval_deliveries.next().await {
2342 if let Err(error) = delivered {
2343 tracing::warn!(%error, "child approval did not match a durable Core decision");
2344 }
2345 }
2346 while let Some((input, _outcome)) = steers.next().await {
2347 drop(input);
2348 }
2349 drop(pending_input);
2350 while let Ok(input) = input_rx.try_recv() {
2351 input.mark_taken();
2352 }
2353 let pending = runtime
2354 .manager
2355 .read()
2356 .await
2357 .pending_requests_for_agent(&agent_id);
2358 for pending in pending {
2359 runtime
2360 .manager
2361 .write()
2362 .await
2363 .cancel_child_approval(&pending.approval_id);
2364 if let Some(tx) = runtime.event_tx.as_ref() {
2365 let event = Event::ApprovalWithdrawn {
2366 id: pending.approval_id,
2367 };
2368 if runtime.cancel_token.is_cancelled() {
2369 let _ = tx.try_send(event);
2370 } else if let Some(deadline) = job.deadline {
2371 let _ = tokio::time::timeout_at(deadline.into(), tx.send(event)).await;
2372 } else {
2373 let _ = tx.send(event).await;
2374 }
2375 }
2376 }
2377 if !result
2378 .as_ref()
2379 .err()
2380 .is_some_and(|error| error.downcast_ref::<UnsettledChildCancellation>().is_some())
2381 && let Err(error) = job.capture_activation_output(streamed_text).await
2382 {
2383 result = Err(error.context("child activation output capture failed"));
2384 }
2385 result
2386 }
2387
2388 async fn prepare_child_membership(
2389 runtime: &SubAgentRuntime,
2390 assignment: &SubAgentAssignment,
2391 agent_id: &str,
2392 allow_mcp: bool,
2393 ) -> Result<(
2394 SubAgentRuntime,
2395 Option<crate::extension_host::HostAttachment>,
2396 )> {
2397 let mut scoped_runtime = runtime.clone();
2398 let extension_host = if codewhale_plugins::activation::extension_host_policy_enabled() {
2399 if let Some(plugins) = runtime.context.plugin_registry.as_ref() {
2400 let selected = if let Some(preset) = assignment.native_preset.as_ref() {
2401 let plugins = Arc::clone(plugins);
2402 let preset = preset.clone();
2403 let policy = codewhale_plugins::activation::extension_host_policy_enabled();
2404 #[cfg(any(test, feature = "test-support"))]
2405 let env_scope = crate::test_support::env_scope_ticket();
2406 tokio::task::spawn_blocking(move || {
2407 #[cfg(any(test, feature = "test-support"))]
2408 let _env_scope = crate::test_support::join_env_scope(env_scope);
2409 let _policy = codewhale_plugins::activation::PolicyScope::propagate(policy);
2410 plugins.with_native_preset(preset)
2411 })
2412 .await
2413 .map_err(|error| anyhow!("Native preset validation worker failed: {error}"))?
2414 .map_err(anyhow::Error::msg)?
2415 } else {
2416 plugins.as_ref().clone()
2417 };
2418 let attachment = crate::extension_host::manager().attach(Arc::new(selected));
2419 attachment.set_identity(
2420 runtime
2421 .context
2422 .execution
2423 .session_objects
2424 .as_ref()
2425 .map(|session| session.session_id.clone()),
2426 Some(agent_id.to_owned()),
2427 );
2428 attachment.reconcile().await.map_err(anyhow::Error::msg)?;
2429 scoped_runtime.context = scoped_runtime
2430 .context
2431 .clone()
2432 .with_plugin_registry(attachment.plugin_view());
2433 if allow_mcp && let Some(parent_pool) = runtime.mcp_pool.as_ref() {
2434 let mut pool = parent_pool
2435 .lock()
2436 .await
2437 .fork_for_plugins(attachment.plugin_view())?;
2438 // Discover this caller's selected catalog through the existing
2439 // Core connection factory before the child registry snapshots it.
2440 // Optional connection failures retain Core's lazy retry behavior.
2441 for (name, error) in pool.connect_all().await {
2442 tracing::warn!("child MCP server {name} unavailable: {error}");
2443 }
2444 scoped_runtime.mcp_pool = Some(Arc::new(tokio::sync::Mutex::new(pool)));
2445 }
2446 Some(attachment)
2447 } else if assignment.native_preset.is_some() {
2448 return Err(anyhow!(
2449 "Native composition requires the caller's reviewed plugin inventory"
2450 ));
2451 } else {
2452 None
2453 }
2454 } else if assignment.native_preset.is_some() {
2455 return Err(anyhow!(
2456 "Native composition requires Experimental extension_host"
2457 ));
2458 } else {
2459 None
2460 };
2461
2462 Ok((scoped_runtime, extension_host))
2463 }
2464
2465 /// Counters for one logical Engine model step. They do not dispatch or own
2466 /// a turn; the existing outer run_turn loop consumes this policy decision.
2467 #[derive(Default)]
2468 pub struct ChildRequestRetries {
2469 transient: u32,
2470 timeouts: u32,
2471 }
2472 pub enum ChildRequestRecovery {
2473 Retry {
2474 delay: Duration,
2475 note: String,
2476 },
2477 Interrupted {
2478 checkpoint_reason: &'static str,
2479 message: String,
2480 },
2481 }
2482 impl ChildRequestRetries {
2483 pub fn decide(
2484 &mut self,
2485 runtime: &SubAgentRuntime,
2486 error: &anyhow::Error,
2487 ) -> Option<ChildRequestRecovery> {
2488 if let Some(error @ (LlmError::QuotaWindow { .. } | LlmError::RateLimited { .. })) =
2489 error.downcast_ref::<LlmError>()
2490 && (matches!(error, LlmError::QuotaWindow { .. })
2491 || error.suggested_retry_delay().is_some_and(|delay| {
2492 delay > codewhale_runtime::retry_status::MAX_PROVIDER_PAUSE
2493 }))
2494 {
2495 return Some(ChildRequestRecovery::Interrupted {
2496 checkpoint_reason: "api_rate_limited",
2497 message: format!(
2498 "Provider quota window requires continuation after reset: {error}"
2499 ),
2500 });
2501 }
2502 let transmission = error.downcast_ref::<LlmError>().map_or(
2503 crate::llm_client::RequestTransmission::OutcomeUnknown,
2504 LlmError::transmission,
2505 );
2506 if transmission == crate::llm_client::RequestTransmission::OutcomeUnknown {
2507 return Some(ChildRequestRecovery::Interrupted {
2508 checkpoint_reason: "request_outcome_unknown",
2509 message: format!(
2510 "Provider request outcome unknown; checkpoint preserved without automatic replay: {error:#}"
2511 ),
2512 });
2513 }
2514 if matches!(
2515 error.downcast_ref::<LlmError>(),
2516 Some(LlmError::ConnectError {
2517 transient: true,
2518 timed_out: true,
2519 ..
2520 })
2521 ) {
2522 if self.timeouts >= SUBAGENT_API_TIMEOUT_MAX_RETRIES {
2523 return Some(ChildRequestRecovery::Interrupted {
2524 checkpoint_reason: "api_timeout",
2525 message: format!(
2526 "Connection timed out before request dispatch after {}ms on {} attempt(s); checkpoint preserved for continuation",
2527 runtime.step_api_timeout.as_millis(),
2528 self.timeouts.saturating_add(1)
2529 ),
2530 });
2531 }
2532 self.timeouts = self.timeouts.saturating_add(1);
2533 let delay = subagent_api_timeout_retry_delay(
2534 self.timeouts,
2535 runtime.api_timeout_retry_base_backoff,
2536 );
2537 return Some(ChildRequestRecovery::Retry {
2538 delay,
2539 note: format!(
2540 "Connection timed out before request dispatch after {}ms; retrying connection {}/{} in {}ms",
2541 runtime.step_api_timeout.as_millis(),
2542 self.timeouts,
2543 SUBAGENT_API_TIMEOUT_MAX_RETRIES,
2544 delay.as_millis()
2545 ),
2546 });
2547 }
2548 let retryable =
2549 retryable_subagent_provider_failure(error, self.transient.saturating_add(1))?;
2550 if self.transient >= SUBAGENT_TRANSIENT_PROVIDER_MAX_RETRIES {
2551 return Some(ChildRequestRecovery::Interrupted {
2552 checkpoint_reason: retryable.checkpoint_reason,
2553 message: format!(
2554 "{} after {} API attempt(s): {error:#}; checkpoint preserved for continuation",
2555 retryable.label,
2556 self.transient.saturating_add(1)
2557 ),
2558 });
2559 }
2560 self.transient = self.transient.saturating_add(1);
2561 Some(ChildRequestRecovery::Retry {
2562 delay: retryable.delay,
2563 note: format!(
2564 "{}; retrying API request {}/{} in {}ms ({error:#})",
2565 retryable.label,
2566 self.transient,
2567 SUBAGENT_TRANSIENT_PROVIDER_MAX_RETRIES,
2568 retryable.delay.as_millis()
2569 ),
2570 })
2571 }
2572 }
2573
2574 /// Reuse the approved first-request route policy. The caller installs it in
2575 /// the existing Engine; this helper has no provider, planner or retry loop.
2576 pub fn approved_first_request_replacement(
2577 job: &ChildJob,
2578 current: &SubAgentRuntime,
2579 replacements_tried: &mut usize,
2580 pin_fallback_used: &mut bool,
2581 error: &anyhow::Error,
2582 ) -> Result<Option<(SubAgentRuntime, SpawnRouteSource, String)>> {
2583 if !job.can_replace_first_request() {
2584 return Ok(None);
2585 }
2586 let detail: String = current
2587 .client
2588 .redact_model_bound_text(&format!("{error}"))
2589 .chars()
2590 .take(160)
2591 .collect();
2592 if !*pin_fallback_used
2593 && let Some(origin) = current.route_origin.as_deref()
2594 && let Some(parent) = origin.parent.as_ref()
2595 && let Some(why) = pin_refusal_reason(error)
2596 {
2597 *pin_fallback_used = true;
2598 let note: String = format!(
2599 "{}, which failed authorization ({why}: {detail}); ran on {} instead",
2600 origin.source, parent.label
2601 )
2602 .chars()
2603 .take(480)
2604 .collect();
2605 let mut next = current.clone();
2606 parent.install(&mut next);
2607 next.check_worker_pool()?;
2608 next.route_origin = Some(Arc::new(spawn_route_origin(
2609 SpawnRouteSource::SessionFallback,
2610 current.worker_profile.role.as_str(),
2611 None,
2612 parent.label.clone(),
2613 Some(&note),
2614 )));
2615 return Ok(Some((next, SpawnRouteSource::SessionFallback, note)));
2616 }
2617 let Some(why) = route_replacement_reason(error) else {
2618 return Ok(None);
2619 };
2620 let original = &job.authority.runtime;
2621 let mut skipped = Vec::new();
2622 while let Some(route) = original.route_replacements.get(*replacements_tried) {
2623 *replacements_tried += 1;
2624 let to = format!(
2625 "{}/{}",
2626 route.provider.as_deref().unwrap_or_default(),
2627 route.model
2628 );
2629 match replacement_route_runtime(original, route).and_then(|next| {
2630 next.check_worker_pool()
2631 .map_err(|error| error.to_string())?;
2632 Ok(next)
2633 }) {
2634 Ok(mut next) => {
2635 let from = format!(
2636 "{}/{}",
2637 current.client.api_provider().as_str(),
2638 current.model
2639 );
2640 let mut note = format!(
2641 "{from} refused the first request before any work ({why}: {detail}); moved to approved replacement {to} (attempt {} of {})",
2642 *replacements_tried,
2643 original.route_replacements.len()
2644 );
2645 if !skipped.is_empty() {
2646 note.push_str("; skipped ");
2647 note.push_str(&skipped.join("; "));
2648 }
2649 let note: String = note.chars().take(480).collect();
2650 next.route_origin = Some(Arc::new(spawn_route_origin(
2651 SpawnRouteSource::RoleReplacement,
2652 original.worker_profile.role.as_str(),
2653 None,
2654 runtime_route_label(&next),
2655 Some(&note),
2656 )));
2657 return Ok(Some((next, SpawnRouteSource::RoleReplacement, note)));
2658 }
2659 Err(unavailable) => skipped.push(format!(
2660 "{to} ({})",
2661 unavailable.chars().take(120).collect::<String>()
2662 )),
2663 }
2664 }
2665 if skipped.is_empty() {
2666 Ok(None)
2667 } else {
2668 Err(anyhow!(
2669 "no approved replacement route could take the task: {}",
2670 skipped.join("; ")
2671 ))
2672 }
2673 }
2674
2675 #[cfg(test)]
2676 mod owner_origin_tests {
2677 use super::*;
2678
2679 #[tokio::test]
2680 async fn canonical_child_bounded_write_checks_exact_held_origin_before_scope_validation() {
2681 let _environment = crate::test_support::lock_test_env();
2682 let temporary = tempfile::tempdir().unwrap();
2683 let root = temporary.path().canonicalize().unwrap();
2684 let original = root.join("original");
2685 let selected = root.join("selected");
2686 fs::create_dir_all(original.join("src")).unwrap();
2687 fs::create_dir_all(selected.join("src")).unwrap();
2688 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", root.join("home"));
2689 let manager = new_shared_subagent_manager(original.clone(), 2);
2690 {
2691 let mut held = manager.write().await;
2692 for lexical in [&original, &selected] {
2693 let (canonical, file) =
2694 codewhale_util::workspace_dir::open_workspace_directory(lexical).unwrap();
2695 held.admit_coordination_workspace(lexical.clone(), canonical, Arc::new(file))
2696 .unwrap();
2697 }
2698 let spec = super::super::owner_scoped_coordination_tests::writer(
2699 "selected-writer",
2700 &selected,
2701 "src",
2702 );
2703 held.register_worker_with_coordination(spec).unwrap();
2704 }
2705 let mut runtime = super::super::tests::stub_runtime();
2706 runtime.manager = manager.clone();
2707 runtime.context = ToolContext::new(selected.clone());
2708 runtime.worker_profile = WorkerRuntimeProfile::for_role(FleetRole::Builder);
2709 runtime.allow_shell = true;
2710 let authority = ChildAuthority::capture(
2711 runtime,
2712 FleetRole::Builder,
2713 "selected-writer".into(),
2714 "writer".into(),
2715 None,
2716 );
2717 let mut registry = ToolRegistry::new(ToolContext::new(selected.clone()));
2718 registry.register(Arc::new(crate::tools::shell::BashTool::new("Bash")));
2719 let input = serde_json::json!({"path":"src/lib.rs","content":"x"});
2720 assert_eq!(
2721 authority
2722 .validate_claim(&registry, "write_file", &input)
2723 .await
2724 .unwrap(),
2725 vec!["src/lib.rs".to_string()]
2726 );
2727 {
2728 let mut held = manager.write().await;
2729 let foreign = held.admitted_coordination_roots[&original].receipt.clone();
2730 held.worker_origins
2731 .get_mut("selected-writer")
2732 .unwrap()
2733 .scope = Some(foreign);
2734 }
2735 let refused = authority
2736 .validate_claim(&registry, "write_file", &input)
2737 .await
2738 .unwrap_err();
2739 assert!(
2740 refused.to_string().contains("owner re-admission"),
2741 "{refused}"
2742 );
2743 assert!(
2744 manager
2745 .read()
2746 .await
2747 .live_peer_shared_write_claim_owners("selected-writer")
2748 .is_empty()
2749 );
2750 assert!(!selected.join("effect").exists());
2751 }
2752
2753 #[tokio::test]
2754 async fn publish_auxiliary_usage_warns_when_worker_projection_fails() {
2755 use std::io::{Read as _, Seek as _, SeekFrom};
2756 use tracing::instrument::WithSubscriber as _;
2757
2758 let _environment = crate::test_support::lock_test_env();
2759 let tmp = tempfile::tempdir().unwrap();
2760 let _home =
2761 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path().join("home"));
2762 let mut runtime = super::super::tests::stub_runtime();
2763 runtime.manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
2764 runtime.context = ToolContext::new(tmp.path().to_path_buf());
2765 let route = runtime
2766 .client
2767 .effective_route_envelope(&runtime.model, chrono::Utc::now());
2768 let source = crate::cost_status::NativeUsageSource::capture_with_origin(
2769 "auto-review-return:missing-worker".to_string(),
2770 crate::cost_status::UsageSpendOwner::Auxiliary,
2771 None,
2772 );
2773 let usage = Usage {
2774 input_tokens: 12,
2775 output_tokens: 7,
2776 ..Usage::default()
2777 };
2778 let record = source.reported(&route, &usage);
2779 let accounting = ChildAccountingProjection::capture(&runtime, "missing-worker");
2780
2781 let mut output = tempfile::tempfile().unwrap();
2782 let subscriber = tracing_subscriber::fmt()
2783 .without_time()
2784 .with_ansi(false)
2785 .with_env_filter(tracing_subscriber::EnvFilter::new("warn"))
2786 .with_writer(std::sync::Mutex::new(output.try_clone().unwrap()))
2787 .finish();
2788 accounting
2789 .publish_auxiliary_usage(&record)
2790 .with_subscriber(subscriber)
2791 .await;
2792
2793 output.seek(SeekFrom::Start(0)).unwrap();
2794 let mut logs = String::new();
2795 output.read_to_string(&mut logs).unwrap();
2796 assert!(
2797 logs.contains("WARN")
2798 && logs.contains("auxiliary review usage projection failed")
2799 && logs.contains("owner=missing-worker")
2800 && logs.contains("error="),
2801 "{logs}"
2802 );
2803 }
2804
2805 #[tokio::test]
2806 async fn capture_activation_output_runs_transcript_io_off_tokio_worker() {
2807 let tmp = tempfile::tempdir().unwrap();
2808 let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
2809 let agent_id = {
2810 manager
2811 .write()
2812 .await
2813 .insert_test_running_agent("activation-worker", tmp.path())
2814 };
2815 let mut runtime = super::super::tests::stub_runtime();
2816 runtime.manager = manager.clone();
2817 runtime.context = ToolContext::new(tmp.path().to_path_buf());
2818 let authority = ChildAuthority::capture(
2819 runtime,
2820 FleetRole::Worker,
2821 agent_id.clone(),
2822 "activation-worker".into(),
2823 None,
2824 );
2825 let job = ChildJob::admitted(
2826 authority,
2827 SubAgentAssignment::new("capture output".into(), None),
2828 Instant::now(),
2829 4,
2830 false,
2831 None,
2832 )
2833 .await
2834 .unwrap();
2835 {
2836 let mut artifact = job.artifact.lock().await;
2837 artifact
2838 .as_mut()
2839 .unwrap()
2840 .append_messages(
2841 &[Message {
2842 role: codewhale_models::Role::User,
2843 content: vec![ContentBlock::Text {
2844 text: "hello".into(),
2845 cache_control: None,
2846 }],
2847 }],
2848 true,
2849 )
2850 .unwrap();
2851 }
2852
2853 let artifact_hold = job.artifact.lock().await;
2854 let capture_task = tokio::spawn({
2855 let job = job.clone();
2856 async move {
2857 job.capture_activation_output_off_runtime(0, "streamed reply".into())
2858 .await
2859 }
2860 });
2861 tokio::task::yield_now().await;
2862 let probe = tokio::time::timeout(Duration::from_secs(2), tokio::spawn(async { 42usize }))
2863 .await
2864 .unwrap()
2865 .unwrap();
2866 assert_eq!(probe, 42);
2867 drop(artifact_hold);
2868
2869 let captured = tokio::time::timeout(Duration::from_secs(5), capture_task)
2870 .await
2871 .unwrap()
2872 .unwrap()
2873 .unwrap()
2874 .expect("captured streamed output");
2875 assert_eq!(captured.transcript_message_index, 1);
2876 assert_eq!(captured.content_sha256.len(), 64);
2877 assert!(job.artifact.try_lock().is_ok());
2878
2879 let loaded =
2880 super::super::load_subagent_transcript_artifact(tmp.path(), &agent_id).unwrap();
2881 assert_eq!(loaded.len(), 2);
2882 }
2883
2884 #[tokio::test]
2885 async fn finish_does_not_hold_artifact_mutex_across_await_points() {
2886 let tmp = tempfile::tempdir().unwrap();
2887 let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 2);
2888 let agent_id = {
2889 manager
2890 .write()
2891 .await
2892 .insert_test_running_agent("finish-worker", tmp.path())
2893 };
2894 let mut runtime = super::super::tests::stub_runtime();
2895 runtime.manager = manager.clone();
2896 runtime.context = ToolContext::new(tmp.path().to_path_buf());
2897 let handle_store = runtime.context.runtime.handle_store.clone();
2898 let authority = ChildAuthority::capture(
2899 runtime,
2900 FleetRole::Worker,
2901 agent_id.clone(),
2902 "finish-worker".into(),
2903 None,
2904 );
2905 let job = ChildJob::admitted(
2906 authority,
2907 SubAgentAssignment::new("finish cleanly".into(), None),
2908 Instant::now(),
2909 4,
2910 false,
2911 None,
2912 )
2913 .await
2914 .unwrap();
2915 let messages = vec![Message {
2916 role: codewhale_models::Role::User,
2917 content: vec![ContentBlock::Text {
2918 text: "work".into(),
2919 cache_control: None,
2920 }],
2921 }];
2922 job.project(&messages, 1).await.unwrap();
2923
2924 let manager_hold = manager.write().await;
2925 let finish_task = tokio::spawn({
2926 let job = job.clone();
2927 let messages = messages.clone();
2928 async move {
2929 job.finish_projected(
2930 &messages,
2931 1,
2932 SubAgentStatus::Completed,
2933 Some("done".into()),
2934 None,
2935 )
2936 .await
2937 }
2938 });
2939 let lookup = VarHandle {
2940 kind: "var_handle".to_string(),
2941 session_id: format!("agent:{agent_id}"),
2942 name: "full_transcript".to_string(),
2943 type_name: String::new(),
2944 length: 0,
2945 repr_preview: String::new(),
2946 sha256: String::new(),
2947 };
2948 let wait_deadline = Instant::now() + Duration::from_secs(5);
2949 loop {
2950 let completed_published = {
2951 let store = handle_store.lock().await;
2952 store.get(&lookup).is_some_and(|record| {
2953 matches!(
2954 &record.value,
2955 crate::tools::handle::HandleValue::Json(payload)
2956 if payload["status"] == json!("completed")
2957 )
2958 })
2959 };
2960 if completed_published {
2961 break;
2962 }
2963 assert!(
2964 Instant::now() < wait_deadline,
2965 "finish_projected did not reach post-handle manager.read() await"
2966 );
2967 tokio::task::yield_now().await;
2968 }
2969 assert!(
2970 job.artifact.try_lock().is_ok(),
2971 "artifact mutex must not be held while finish awaits manager.read()"
2972 );
2973 drop(manager_hold);
2974
2975 let result = tokio::time::timeout(Duration::from_secs(5), finish_task)
2976 .await
2977 .unwrap()
2978 .unwrap()
2979 .unwrap();
2980 assert_eq!(result.status, SubAgentStatus::Completed);
2981 assert_eq!(result.result.as_deref(), Some("done"));
2982 }
2983 }
2984
2984 lines RUST