返回 CodeWhale
rlm_host.rs
根目录 / crates / engine / src / core / engine / rlm_host.rs
1 //! Captured, call-local RLM projection onto the canonical Engine.
2 //!
3 //! A Python kernel never owns this receipt or a bridge. The only model/code
4 //! driver is Engine::run_turn; the RPC adapter owns its bounded invocation.
5 use super::turn_loop::usage_has_reported_data;
6 use super::*;
7 use crate::core::authority::auto_review::AutoReviewPolicy;
8 use crate::core::ops::TurnInputAuthorship;
9 use crate::rlm::bridge::{RlmUsageAccumulator, RlmUsageReservation, wait_for_deadline};
10 use crate::rlm::turn::{RlmRoundTrace, RlmTermination, RlmTurnResult};
11 use anyhow::anyhow;
12
13 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
14 pub enum RlmMode {
15 Completion,
16 Recursive { depth_remaining: u32 },
17 }
18
19 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
20 pub enum RlmPromptPolicy {
21 #[default]
22 Session,
23 IsolatedPlugin,
24 }
25
26 pub struct RlmInvocation {
27 pub prompt: String,
28 pub mode: RlmMode,
29 pub prompt_policy: RlmPromptPolicy,
30 pub max_tokens: Option<u32>,
31 pub task_instructions: Option<String>,
32 pub deadline: Option<tokio::time::Instant>,
33 pub gate: Option<crate::tools::codemode::NestedCallGate>,
34 pub events: Option<mpsc::Sender<Event>>,
35 pub usage: RlmUsageAccumulator,
36 }
37
38 /// Frozen from the actual serving Core turn, never from a client/string alone.
39 /// `context` predates attaching this receipt, so it cannot contain itself.
40 #[derive(Clone)]
41 pub struct CapturedRlmCaller {
42 #[cfg(any(test, feature = "test-support"))]
43 _fixture_workspace: Option<Arc<tempfile::TempDir>>,
44 pub(super) context: ToolContext,
45 authority: TurnAuthority,
46 route: ValidatedRuntimeRoute,
47 client: SharedModelClient,
48 subagent_manager: SharedSubAgentManager,
49 injected: bool,
50 config: EngineConfig,
51 system: SystemPrompt,
52 instruction_assembly: Option<Arc<crate::project_context::InstructionAssembly>>,
53 extension_prompt_block: Option<String>,
54 constitution_block: Option<String>,
55 approval_store: Result<ApprovalReceiptStore, String>,
56 review_policy: Arc<AutoReviewPolicy>,
57 deadline: Option<tokio::time::Instant>,
58 origin_scope: crate::cost_status::CostScopeToken,
59 child_accounting: Option<crate::tools::subagent::engine::ChildAccountingProjection>,
60 }
61 impl std::fmt::Debug for CapturedRlmCaller {
62 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 f.debug_struct("CapturedRlmCaller")
64 .field("workspace", &self.context.workspace)
65 .field("session", &self.context.state_namespace)
66 .finish_non_exhaustive()
67 }
68 }
69 impl CapturedRlmCaller {
70 pub(super) fn capture(
71 engine: &Engine,
72 authority: &TurnAuthority,
73 route: &TurnRouteContext,
74 context: &ToolContext,
75 origin_turn: &str,
76 ) -> Result<Self, ToolError> {
77 if context.acp_host.is_some() || origin_turn.trim().is_empty() {
78 return Err(ToolError::not_available(
79 "this host has no RLM model-call authority",
80 ));
81 }
82 let identity = engine
83 .api_provider_identity
84 .as_ref()
85 .ok_or_else(|| ToolError::not_available("the Core route has no admitted identity"))?;
86 route
87 .api_config
88 .verify_provider_identity(identity)
89 .map_err(ToolError::permission_denied)?;
90 let resolved =
91 resolve_runtime_route_for_identity(&route.api_config, identity, Some(&route.model))
92 .map_err(ToolError::permission_denied)?;
93 let client = engine
94 .codewhale_client
95 .as_ref()
96 .ok_or_else(|| ToolError::not_available("the Core route has no captured client"))?;
97 if client.admitted_provider_identity() != identity
98 || engine
99 .active_route_endpoint
100 .as_ref()
101 .map(Engine::endpoint_identity)
102 != Some(Engine::endpoint_identity(resolved.candidate.endpoint()))
103 {
104 return Err(ToolError::permission_denied(
105 "the RLM route differs from the installed Core client",
106 ));
107 }
108 let mut captured_context = context.clone();
109 captured_context.rlm_caller = None;
110 #[cfg(any(test, feature = "test-support"))]
111 if captured_context.accounting_origin.is_none() {
112 captured_context.accounting_origin = crate::session_manager::default_sessions_dir()
113 .ok()
114 .map(|dir| {
115 crate::cost_status::NativeUsageOrigin::session(
116 crate::cost_status::scope_token(),
117 dir,
118 captured_context.state_namespace.clone(),
119 )
120 });
121 }
122 let child_accounting = engine
123 .child_host
124 .as_ref()
125 .map(|child| child.authority.accounting_projection());
126 let deadline = context
127 .turn_deadline
128 .into_iter()
129 .chain(engine.nested_work_deadline())
130 .min();
131 let result =
132 Self {
133 #[cfg(any(test, feature = "test-support"))]
134 _fixture_workspace: None,
135 context: captured_context,
136 authority: authority.clone(),
137 route: ValidatedRuntimeRoute {
138 identity: resolved.identity,
139 candidate: resolved.candidate,
140 config: resolved.config,
141 model: resolved.model,
142 context_window: resolved.context_window,
143 client: client.clone(),
144 },
145 client: engine.model_client.clone().ok_or_else(|| {
146 ToolError::not_available("the Core model client is unavailable")
147 })?,
148 subagent_manager: Arc::clone(&engine.subagent_manager),
149 injected: engine.model_client_injected,
150 config: engine.config.clone(),
151 system: engine.session.system_prompt.clone().ok_or_else(|| {
152 ToolError::not_available("the Core policy prompt is unavailable")
153 })?,
154 instruction_assembly: engine.session.instruction_assembly.clone(),
155 extension_prompt_block: engine.extension_prompt_block.clone(),
156 constitution_block: engine.constitution_block.clone(),
157 approval_store: engine.approval_receipt_store.clone(),
158 review_policy: Arc::clone(&engine.shared_auto_review_policy),
159 deadline,
160 origin_scope: crate::cost_status::scope_token(),
161 child_accounting,
162 };
163 result.validate_context(context)?;
164 Ok(result)
165 }
166
167 pub fn validate_context(&self, context: &ToolContext) -> Result<(), ToolError> {
168 if context.workspace != self.context.workspace
169 || context.state_namespace != self.context.state_namespace
170 || context.owner_agent_id != self.context.owner_agent_id
171 || context
172 .plugin_registry
173 .as_ref()
174 .map(|p| p.caller_selection())
175 != self
176 .context
177 .plugin_registry
178 .as_ref()
179 .map(|p| p.caller_selection())
180 {
181 return Err(ToolError::permission_denied(
182 "RLM caller identity, workspace or composition changed",
183 ));
184 }
185 self.validate_live()
186 }
187
188 pub(super) fn validate_live(&self) -> Result<(), ToolError> {
189 if self
190 .context
191 .cancel_token
192 .as_ref()
193 .is_none_or(CancellationToken::is_cancelled)
194 {
195 return Err(ToolError::cancelled(
196 "RLM originating turn is cancelled or unavailable",
197 ));
198 }
199 if self
200 .deadline
201 .is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
202 {
203 return Err(ToolError::execution_failed(
204 "RLM original parent deadline exhausted",
205 ));
206 }
207 crate::extension_host::validate_caller_plugins(self.context.plugin_registry.as_deref())
208 .map_err(ToolError::permission_denied)?;
209 self.route
210 .config
211 .verify_provider_identity(&self.route.identity)
212 .map_err(ToolError::permission_denied)
213 }
214
215 pub fn deadline(&self) -> Option<tokio::time::Instant> {
216 self.deadline
217 }
218
219 pub(crate) fn route_model(&self) -> &str {
220 &self.route.model
221 }
222
223 pub(crate) fn route_provider_id(&self) -> String {
224 self.route.identity.key.to_string()
225 }
226
227 pub(crate) fn route_context_window(&self) -> Option<u32> {
228 (self.route.context_window.tokens > 0).then_some(self.route.context_window.tokens)
229 }
230
231 /// Boxing breaks recursive future types; the future still borrows this
232 /// caller and never enters the persistent session map or PythonRuntime.
233 pub fn dispatch<'call>(
234 &'call self,
235 invocation: RlmInvocation,
236 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = RlmTurnResult> + Send + 'call>> {
237 Box::pin(self.dispatch_admitted(invocation))
238 }
239
240 async fn dispatch_admitted(&self, mut invocation: RlmInvocation) -> RlmTurnResult {
241 let started = Instant::now();
242 invocation.deadline = invocation.deadline.into_iter().chain(self.deadline).min();
243 if let Err(error) = self.validate_live() {
244 return RlmTurnResult::failed(error.to_string(), started.elapsed());
245 }
246 if invocation
247 .deadline
248 .is_some_and(|deadline| tokio::time::Instant::now() >= deadline)
249 {
250 return RlmTurnResult::failed(
251 "RLM original parent deadline exhausted".into(),
252 started.elapsed(),
253 );
254 }
255 if invocation.mode != RlmMode::Completion && invocation.gate.is_none() {
256 return RlmTurnResult::failed(
257 "no permission gate is serving this RLM turn".into(),
258 started.elapsed(),
259 );
260 }
261 // Every admitted completion/recursive host owns bounded receipt
262 // capacity, including setup/preparation failures with no provider call.
263 if let Err(error) = invocation.usage.reserve_nested_turn().await {
264 return RlmTurnResult::failed(error, started.elapsed());
265 }
266 let usage = invocation.usage.clone();
267 let events = invocation.events.clone();
268 let depth = match invocation.mode {
269 RlmMode::Completion => 0,
270 RlmMode::Recursive { depth_remaining } => depth_remaining,
271 };
272 let run_id = uuid::Uuid::new_v4().simple().to_string();
273 let (mut engine, handle) =
274 match Engine::new_rlm_admitted(Arc::new(self.clone()), invocation).await {
275 Ok(host) => host,
276 Err(error) => return RlmTurnResult::failed(error.to_string(), started.elapsed()),
277 };
278 let spec = match engine.rlm_turn_spec() {
279 Ok(spec) => spec,
280 Err(error) => return RlmTurnResult::failed(error.to_string(), started.elapsed()),
281 };
282 let cancel = self
283 .context
284 .cancel_token
285 .as_ref()
286 .expect("validated caller cancel")
287 .clone();
288 let deadline = engine.rlm_host.as_ref().expect("RLM host").deadline;
289 engine.rlm_host.as_mut().expect("RLM host").run_id = run_id;
290 let mut receiver = handle.rx_event.write().await;
291 let local_cancel = engine.cancel_token.clone();
292 // Drive the existing admission/turn method while draining its existing
293 // bounded event channel. No authority-bearing task is detached.
294 let outcome = {
295 let mut call = Box::pin(engine.handle_send_message(spec));
296 loop {
297 tokio::select! {
298 biased;
299 () = cancel.cancelled() => { local_cancel.cancel(); break None; }
300 () = wait_for_deadline(deadline) => { local_cancel.cancel(); break None; }
301 result = &mut call => break Some(result),
302 event = receiver.recv() => {
303 let Some(event) = event else { local_cancel.cancel(); break None; };
304 forward_rlm_event(events.as_ref(), event, depth, &cancel, deadline).await;
305 }
306 }
307 }
308 };
309 while let Ok(event) = receiver.try_recv() {
310 forward_rlm_event(events.as_ref(), event, depth, &cancel, deadline).await;
311 }
312 let mut result = engine.rlm_result(outcome, started.elapsed());
313 let terminal = format!(
314 "RLM finished: {:?} after {} iteration(s), {} sub-LLM call(s), answer {} chars{}",
315 result.termination,
316 result.iterations,
317 result.total_rpcs,
318 result.answer.chars().count(),
319 result
320 .error
321 .as_ref()
322 .map_or(String::new(), |error| format!(" — {error}"))
323 );
324 usage.record_nested_event(serde_json::json!({"run_id": engine.rlm_host.as_ref().expect("RLM host").run_id, "depth_remaining": depth, "kind":"status", "content":terminal})).await;
325 // Settlement is already in the canonical nested-event ledger. The
326 // terminal observation must not wait past cancellation/deadline, and
327 // an available channel can still observe it after the deadline.
328 if let Some(events) = events.as_ref()
329 && let Some(message) =
330 crate::rlm::bridge::nested_rlm_status_line(Event::status(terminal), depth)
331 {
332 let _ = events.try_send(Event::status(message));
333 }
334 let snapshot = usage.snapshot().await;
335 result.usage = snapshot.usage;
336 result.routed_usage = snapshot.records;
337 result.routed_usage_drop_records = snapshot.drop_records;
338 result.routed_usage_dropped_records = snapshot.dropped_records;
339 result
340 }
341 }
342
343 pub(super) struct RlmHostSetup {
344 pub caller: Arc<CapturedRlmCaller>,
345 pub invocation: RlmInvocation,
346 pub system_prompt: SystemPrompt,
347 }
348
349 pub(super) struct RlmHostState {
350 pub caller: Arc<CapturedRlmCaller>,
351 pub run_id: String,
352 pub mode: RlmMode,
353 pub prompt_policy: RlmPromptPolicy,
354 pub system_prompt: SystemPrompt,
355 pub prompt: String,
356 pub deadline: Option<tokio::time::Instant>,
357 pub gate: Option<crate::tools::codemode::NestedCallGate>,
358 pub usage: RlmUsageAccumulator,
359 pub max_tokens: Option<u32>,
360 pub trace: Vec<RlmRoundTrace>,
361 pub last_response: String,
362 pub final_answer: Option<String>,
363 pub total_rpcs: u32,
364 pub consecutive_no_code: u32,
365 pub termination: Option<RlmTermination>,
366 pub error: Option<String>,
367 pub model_rounds: u32,
368 }
369 impl RlmHostState {
370 pub(super) fn instruction_assembly(
371 &self,
372 ) -> Option<Arc<crate::project_context::InstructionAssembly>> {
373 session_instruction_assembly(&self.caller, self.prompt_policy)
374 }
375 }
376
377 fn session_instruction_assembly(
378 caller: &CapturedRlmCaller,
379 policy: RlmPromptPolicy,
380 ) -> Option<Arc<crate::project_context::InstructionAssembly>> {
381 (policy == RlmPromptPolicy::Session)
382 .then(|| caller.instruction_assembly.clone())
383 .flatten()
384 }
385
386 impl From<RlmHostSetup> for RlmHostState {
387 fn from(setup: RlmHostSetup) -> Self {
388 Self {
389 caller: setup.caller,
390 run_id: String::new(),
391 mode: setup.invocation.mode,
392 prompt_policy: setup.invocation.prompt_policy,
393 system_prompt: setup.system_prompt,
394 prompt: setup.invocation.prompt,
395 deadline: setup.invocation.deadline,
396 gate: setup.invocation.gate,
397 usage: setup.invocation.usage,
398 max_tokens: setup.invocation.max_tokens,
399 trace: Vec::new(),
400 last_response: String::new(),
401 final_answer: None,
402 total_rpcs: 0,
403 consecutive_no_code: 0,
404 termination: None,
405 error: None,
406 model_rounds: 0,
407 }
408 }
409 }
410
411 impl Engine {
412 pub(super) async fn new_rlm_admitted(
413 caller: Arc<CapturedRlmCaller>,
414 invocation: RlmInvocation,
415 ) -> Result<(Self, EngineHandle)> {
416 caller.validate_live().map_err(anyhow::Error::new)?;
417 let mut config = caller.config.clone();
418 config.model = caller.route.model.clone();
419 config.workspace = caller.context.workspace.clone();
420 config.session_id = Some(caller.context.state_namespace.clone());
421 config.plugin_registry = caller.context.plugin_registry.clone();
422 config.runtime_services = caller.context.runtime.clone();
423 config.allow_shell = caller.authority.allow_shell;
424 config.trust_mode = caller.authority.trust_mode;
425 config.network_policy = caller.context.network_policy.clone();
426 config.max_steps = if invocation.mode == RlmMode::Completion {
427 1
428 } else {
429 caller.config.max_steps
430 };
431 config.snapshots_enabled = false;
432 config.memory_enabled = false;
433 config.terminal_chrome_enabled = false;
434 config.subagents_enabled = false;
435 config.advisor_config = crate::tools::subagent::AdvisorConfig::disabled();
436 config.goal_objective = None;
437 config.goal_status = GoalStatus::Paused;
438 config.goal_state = new_shared_goal_state();
439 config.turn_wall_clock = invocation.deadline.map_or(Duration::MAX, |deadline| {
440 deadline.saturating_duration_since(tokio::time::Instant::now())
441 });
442 let isolated = invocation.prompt_policy == RlmPromptPolicy::IsolatedPlugin;
443 if isolated {
444 anyhow::ensure!(
445 invocation.mode == RlmMode::Completion,
446 "isolated plugin RLM policy is valid only in completion mode"
447 );
448 config.hook_executor = None;
449 }
450 config.runtime_services.accounting_origin = caller.context.accounting_origin.clone();
451 let system_prompt = if isolated {
452 crate::rlm::prompt::isolated_plugin_rlm_prompt(invocation.task_instructions.as_deref())?
453 } else {
454 crate::rlm::prompt::captured_rlm_prompt(
455 &caller.system,
456 invocation.mode,
457 invocation.task_instructions.as_deref(),
458 )?
459 };
460 let mut kernel = None;
461 if invocation.mode != RlmMode::Completion {
462 let cancel = caller
463 .context
464 .cancel_token
465 .as_ref()
466 .expect("validated originating cancellation");
467 let startup = tokio::select! {
468 biased;
469 () = cancel.cancelled() => Err("RLM Python startup cancelled by its originating turn".to_string()),
470 () = wait_for_deadline(invocation.deadline) => Err("RLM Python startup exhausted its original wall-clock deadline".to_string()),
471 result = crate::rlm::kernel::spawn_kernel(&caller.context, Some(&invocation.prompt), None) => result,
472 };
473 match startup {
474 Ok(runtime) => kernel = Some(runtime),
475 Err(error) => return Err(anyhow!("RLM Python startup failed: {error}")),
476 }
477 }
478 let api = (*caller.route.config).clone();
479 let setup = RlmHostSetup {
480 caller: Arc::clone(&caller),
481 invocation,
482 system_prompt,
483 };
484 let (mut engine, mut handle) =
485 Self::new_admitted(config, &api, Some(EngineHostSetup::Rlm(setup)));
486 engine.install_validated_runtime_route(caller.route.clone());
487 engine.model_client = Some(Arc::clone(&caller.client));
488 engine.model_client_injected = caller.injected;
489 handle.client_preflight_required = false;
490 engine.repl_kernel = kernel;
491 engine.repl_kernel_policy = caller.context.elevated_sandbox_policy.clone();
492 if !isolated {
493 engine.extension_prompt_block = caller.extension_prompt_block.clone();
494 engine.constitution_block = caller.constitution_block.clone();
495 }
496 Ok((engine, handle))
497 }
498
499 fn rlm_turn_spec(&self) -> Result<TurnSpec> {
500 let state = self
501 .rlm_host
502 .as_ref()
503 .ok_or_else(|| anyhow!("not an admitted RLM host"))?;
504 state.caller.validate_live().map_err(anyhow::Error::new)?;
505 let max_output_tokens = state
506 .max_tokens
507 .map(|limit| {
508 std::num::NonZeroU32::new(limit)
509 .ok_or_else(|| anyhow!("RLM max_tokens must be greater than zero"))
510 })
511 .transpose()?;
512 let content = if state.mode == RlmMode::Completion {
513 state.prompt.clone()
514 } else {
515 crate::rlm::turn::metadata_text(&state.prompt, 0, None, None)
516 };
517 Ok(TurnSpec {
518 profile_constitution: None,
519 content,
520 images: Vec::new(),
521 mode: state.caller.authority.mode,
522 route: Box::new(state.caller.route.clone().into_resolved()),
523 compaction: Box::new(self.config.compaction.clone()),
524 initial_routed_usage: Box::default(),
525 goal_objective: None,
526 goal_token_budget: None,
527 goal_status: GoalStatus::Paused,
528 reasoning_effort: self.session.reasoning_effort.clone(),
529 reasoning_effort_auto: false,
530 auto_model: false,
531 allow_shell: state.caller.authority.allow_shell,
532 trust_mode: state.caller.authority.trust_mode,
533 auto_approve: state.caller.authority.auto_approve,
534 approval_mode: state.caller.authority.approval_mode,
535 translation_enabled: false,
536 allowed_tools: Some(if state.mode == RlmMode::Completion {
537 Vec::new()
538 } else {
539 vec![tool_catalog::CODE_EXECUTION_TOOL_NAME.to_string()]
540 }),
541 dynamic_tools: Vec::new(),
542 hook_executor: self.config.hook_executor.clone(),
543 verbosity: None,
544 provenance: UserInputProvenance::Runtime,
545 input_authorship: TurnInputAuthorship::NotPerson,
546 submission_id: None,
547 max_output_tokens,
548 })
549 }
550
551 fn rlm_result(&self, outcome: Option<SendMessageOutcome>, duration: Duration) -> RlmTurnResult {
552 let state = self.rlm_host.as_ref().expect("admitted RLM state");
553 let error = state.error.clone().or_else(|| match outcome {
554 Some(SendMessageOutcome::Finished {
555 status: TurnOutcomeStatus::Completed,
556 error,
557 }) => error,
558 Some(SendMessageOutcome::Finished { error, .. })
559 | Some(SendMessageOutcome::NotStarted { error }) => {
560 error.or_else(|| Some("RLM Core turn did not complete".into()))
561 }
562 None => Some(
563 "RLM evaluation cancelled or exhausted its original wall-clock deadline".into(),
564 ),
565 });
566 RlmTurnResult {
567 answer: state
568 .final_answer
569 .clone()
570 .unwrap_or_else(|| state.last_response.clone()),
571 iterations: state.model_rounds,
572 duration,
573 error,
574 usage: Usage::default(),
575 routed_usage: Vec::new(),
576 routed_usage_drop_records: Vec::new(),
577 routed_usage_dropped_records: 0,
578 termination: state.termination.unwrap_or(RlmTermination::Error),
579 trace: state.trace.clone(),
580 total_rpcs: state.total_rpcs,
581 }
582 .require_answer_or_error()
583 }
584 }
585
586 impl EngineHostSetup {
587 pub(super) fn initial_authority(&self, api: &Config) -> LiveRuntimeAuthority {
588 self.context()
589 .live_posture
590 .as_ref()
591 .map(LivePosture::read)
592 .unwrap_or_else(|| match self {
593 Self::Child(setup) => {
594 let runtime = &setup.authority.runtime;
595 let context = &runtime.context;
596 LiveRuntimeAuthority::from_fields(
597 runtime.parent_mode,
598 runtime.allow_shell,
599 context.trust_mode,
600 context.auto_approve,
601 context.approval_mode,
602 api.sandbox_mode.clone(),
603 )
604 }
605 Self::Rlm(setup) => LiveRuntimeAuthority::from_fields(
606 setup.caller.authority.mode,
607 setup.caller.authority.allow_shell,
608 setup.caller.authority.trust_mode,
609 setup.caller.authority.auto_approve,
610 setup.caller.authority.approval_mode,
611 api.sandbox_mode.clone(),
612 ),
613 })
614 }
615 pub(super) fn cancel_token(&self) -> &CancellationToken {
616 match self {
617 Self::Child(setup) => &setup.authority.runtime.cancel_token,
618 Self::Rlm(setup) => setup
619 .caller
620 .context
621 .cancel_token
622 .as_ref()
623 .expect("captured RLM cancel"),
624 }
625 }
626 pub(super) fn context(&self) -> &ToolContext {
627 match self {
628 Self::Child(setup) => &setup.authority.runtime.context,
629 Self::Rlm(setup) => &setup.caller.context,
630 }
631 }
632 pub(super) fn subagent_manager(&self) -> &SharedSubAgentManager {
633 match self {
634 Self::Child(setup) => &setup.authority.runtime.manager,
635 Self::Rlm(setup) => &setup.caller.subagent_manager,
636 }
637 }
638 pub(super) fn owner_agent_id(&self) -> Option<String> {
639 match self {
640 Self::Child(setup) => Some(setup.authority.owner_agent_id.clone()),
641 Self::Rlm(setup) => setup.caller.context.owner_agent_id.clone(),
642 }
643 }
644 pub(super) fn client(&self) -> &CodewhaleClient {
645 match self {
646 Self::Child(setup) => &setup.authority.runtime.client,
647 Self::Rlm(setup) => &setup.caller.route.client,
648 }
649 }
650 pub(super) fn system_prompt(&self) -> &SystemPrompt {
651 match self {
652 Self::Child(setup) => &setup.system_prompt,
653 Self::Rlm(setup) => &setup.system_prompt,
654 }
655 }
656 pub(super) fn instruction_assembly(
657 &self,
658 ) -> Option<Arc<crate::project_context::InstructionAssembly>> {
659 match self {
660 Self::Child(_) => None,
661 Self::Rlm(setup) => {
662 session_instruction_assembly(&setup.caller, setup.invocation.prompt_policy)
663 }
664 }
665 }
666 pub(super) fn review_policy(&self) -> Arc<AutoReviewPolicy> {
667 match self {
668 Self::Child(setup) => Arc::clone(&setup.authority.runtime.auto_review_policy),
669 Self::Rlm(setup) => Arc::clone(&setup.caller.review_policy),
670 }
671 }
672 pub(super) fn approval_store(&self) -> Result<ApprovalReceiptStore, String> {
673 match self {
674 Self::Child(setup) => setup.authority.approval_receipt_store(),
675 Self::Rlm(setup) => setup.caller.approval_store.clone(),
676 }
677 }
678 }
679
680 async fn forward_rlm_event(
681 events: Option<&mpsc::Sender<Event>>,
682 event: Event,
683 depth: u32,
684 cancel: &CancellationToken,
685 deadline: Option<tokio::time::Instant>,
686 ) {
687 if let Some(events) = events
688 && let Some(message) = crate::rlm::bridge::nested_rlm_status_line(event, depth)
689 {
690 tokio::select! {
691 biased;
692 () = cancel.cancelled() => {},
693 _ = wait_for_deadline(deadline) => {},
694 _ = events.send(Event::status(message)) => {},
695 }
696 }
697 }
698
699 impl Engine {
700 pub(super) fn rlm_tool_build(
701 &self,
702 authority: &TurnAuthority,
703 _route: &TurnRouteContext,
704 ) -> TurnToolBuild {
705 let state = self.rlm_host.as_ref().expect("admitted RLM host");
706 let mut context = state.caller.context.clone();
707 context.rlm_caller = Some(Arc::clone(&state.caller));
708 context.cancel_token = Some(self.cancel_token.clone());
709 context.turn_deadline = state.deadline;
710 let registry = ToolRegistryBuilder::new().build(context);
711 let mut catalog = Vec::new();
712 if state.mode != RlmMode::Completion {
713 tool_catalog::ensure_advanced_tooling(
714 &mut catalog,
715 authority.mode,
716 &HashSet::new(),
717 tool_catalog::ToolMode::Direct,
718 );
719 catalog.retain(|tool| tool.name == tool_catalog::CODE_EXECUTION_TOOL_NAME);
720 }
721 let allowed = Some(catalog.iter().map(|tool| tool.name.clone()).collect());
722 TurnToolBuild {
723 surface: ToolSurfacePolicy::new(
724 registry,
725 Some(catalog),
726 authority.mode,
727 &HashSet::new(),
728 false,
729 allowed,
730 None,
731 self.config.max_tool_calls,
732 tool_catalog::ToolMode::Direct,
733 ),
734 mcp_tool_names: Vec::new(),
735 mcp: McpToolState::Disabled,
736 #[cfg(test)]
737 subagent_runtime_model: None,
738 mailbox: None,
739 plugin_tool_names: HashSet::new(),
740 }
741 }
742 }
743
744 /// One actual producer dispatch with a durable source reservation before the client.
745 pub(super) struct RlmDispatchedRequest {
746 caller: Arc<CapturedRlmCaller>,
747 usage: RlmUsageAccumulator,
748 reservation: RlmUsageReservation,
749 accounting_source: crate::cost_status::NativeUsageSource,
750 route: crate::cost_status::EffectiveRouteEnvelope,
751 settled: Option<crate::cost_status::RuntimeUsageRecord>,
752 projected: bool,
753 refused: bool,
754 }
755 impl RlmDispatchedRequest {
756 pub(super) async fn settle_open_error(&mut self, error: &anyhow::Error) {
757 let wire = self.accounting_source.observed_wire();
758 let coverage = if wire.last_transmission.is_some() {
759 wire.usage_coverage(false, false)
760 } else {
761 match error
762 .downcast_ref::<crate::llm_client::LlmError>()
763 .map(crate::llm_client::LlmError::transmission)
764 {
765 Some(crate::llm_client::RequestTransmission::NotDispatched) => {
766 crate::llm_client::ProviderUsageCoverage::NotDispatched
767 }
768 Some(crate::llm_client::RequestTransmission::Rejected) => {
769 crate::llm_client::ProviderUsageCoverage::Rejected
770 }
771 _ => crate::llm_client::ProviderUsageCoverage::Missing,
772 }
773 };
774 let record = self.accounting_source.prepare_record(
775 &self.route,
776 &Usage::default(),
777 coverage,
778 crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown,
779 &wire,
780 );
781 self.caller.publish_response_async(&record).await;
782 self.usage.complete_record(self.reservation, &record).await;
783 let projected = if let Some(child) = &self.caller.child_accounting {
784 child.project_settled(&record).await
785 } else {
786 Ok(())
787 };
788 self.projected = projected.is_ok();
789 self.settled = Some(record);
790 self.refused = self.projected
791 && matches!(
792 coverage,
793 crate::llm_client::ProviderUsageCoverage::Rejected
794 | crate::llm_client::ProviderUsageCoverage::NotDispatched
795 );
796 }
797 pub(super) async fn cancel_unexecuted(&mut self) {
798 let wire = self.accounting_source.observed_wire();
799 if wire.last_transmission.is_some() {
800 self.settle(&Usage::default(), false).await;
801 return;
802 }
803 let record = self.accounting_source.prepare_record(
804 &self.route,
805 &Usage::default(),
806 crate::llm_client::ProviderUsageCoverage::NotDispatched,
807 crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown,
808 &wire,
809 );
810 self.caller.publish_response_async(&record).await;
811 self.usage.complete_record(self.reservation, &record).await;
812 let projected = if let Some(child) = &self.caller.child_accounting {
813 child.project_settled(&record).await
814 } else {
815 Ok(())
816 };
817 self.projected = projected.is_ok();
818 self.refused = self.projected;
819 self.settled = Some(record);
820 }
821 pub(super) async fn settle(&mut self, usage: &Usage, complete: bool) {
822 if self.refused {
823 return;
824 }
825 let reason = if complete {
826 crate::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage
827 } else {
828 crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown
829 };
830 let coverage = if complete && usage_has_reported_data(usage) {
831 crate::llm_client::ProviderUsageCoverage::Reported
832 } else if usage_has_reported_data(usage) {
833 crate::llm_client::ProviderUsageCoverage::Incomplete
834 } else {
835 crate::llm_client::ProviderUsageCoverage::Missing
836 };
837 let record = self.accounting_source.prepare_record(
838 &self.route,
839 usage,
840 coverage,
841 reason,
842 &self.accounting_source.observed_wire(),
843 );
844 self.caller.publish_response_async(&record).await;
845 self.settled = Some(record.clone());
846 self.usage.complete_record(self.reservation, &record).await;
847 let projected = if let Some(child) = &self.caller.child_accounting {
848 child.project_settled(&record).await
849 } else {
850 Ok(())
851 };
852 self.projected = projected.is_ok();
853 }
854 }
855
856 impl Drop for RlmDispatchedRequest {
857 fn drop(&mut self) {
858 if self.settled.is_some() || self.refused {
859 return;
860 }
861 let wire = self.accounting_source.observed_wire();
862 let coverage = if wire.last_transmission.is_some() {
863 wire.usage_coverage(false, false)
864 } else {
865 crate::llm_client::ProviderUsageCoverage::Missing
866 };
867 let record = self.accounting_source.prepare_record(
868 &self.route,
869 &Usage::default(),
870 coverage,
871 crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown,
872 &wire,
873 );
874 self.caller.publish_response(&record);
875 self.usage.complete_record_sync(self.reservation, &record);
876 self.settled = Some(record);
877 }
878 }
879
880 impl CapturedRlmCaller {
881 async fn publish_response_async(
882 self: &Arc<Self>,
883 record: &crate::cost_status::RuntimeUsageRecord,
884 ) {
885 let caller = Arc::clone(self);
886 let record = record.clone();
887 #[cfg(any(test, feature = "test-support"))]
888 let origin = crate::cost_status::test_cost_scope_id();
889 let _ = codewhale_runtime::runtime_control::owner_work(move || {
890 #[cfg(any(test, feature = "test-support"))]
891 let _origin = crate::cost_status::bind_test_cost_scope(origin);
892 caller.publish_response(&record);
893 Ok(())
894 })
895 .await;
896 }
897
898 fn publish_response(&self, record: &crate::cost_status::RuntimeUsageRecord) {
899 if let Some(child) = &self.child_accounting {
900 let _ = child.publish(record);
901 return;
902 }
903 crate::cost_status::record_runtime_usage(
904 self.origin_scope,
905 self.context.accounting_origin.as_ref(),
906 record,
907 );
908 }
909 }
910
911 impl Engine {
912 pub(super) async fn rlm_provider_request(
913 &mut self,
914 client: &SharedModelClient,
915 request: &codewhale_models::MessageRequest,
916 ) -> Result<Option<RlmDispatchedRequest>, String> {
917 let Some(state) = self.rlm_host.as_mut() else {
918 return Ok(None);
919 };
920 state
921 .caller
922 .validate_live()
923 .map_err(|error| error.to_string())?;
924 let route = client.effective_route_envelope(&request.model, chrono::Utc::now());
925 let reservation = state.usage.reserve(route.clone()).await?;
926 let source = state
927 .usage
928 .source_id(reservation)
929 .await
930 .ok_or_else(|| "RLM dispatch reservation disappeared".to_string())?;
931 state.model_rounds = state.model_rounds.saturating_add(1);
932 Ok(Some(RlmDispatchedRequest {
933 caller: Arc::clone(&state.caller),
934 usage: state.usage.clone(),
935 reservation,
936 accounting_source: crate::cost_status::NativeUsageSource::capture_with_origin(
937 source,
938 crate::cost_status::UsageSpendOwner::Auxiliary,
939 state.caller.context.accounting_origin.clone(),
940 ),
941 route,
942 settled: None,
943 projected: false,
944 refused: false,
945 }))
946 }
947 }
948
949 #[cfg(any(test, feature = "test-support"))]
950 impl CapturedRlmCaller {
951 pub fn fixture_origin_cancel(&self) -> CancellationToken {
952 self.context
953 .cancel_token
954 .as_ref()
955 .expect("captured originating token")
956 .clone()
957 }
958 pub fn hold_fixture_workspace(&mut self, workspace: Arc<tempfile::TempDir>) {
959 self._fixture_workspace = Some(workspace);
960 }
961 }
962
962 lines RUST