lean_ctx_ext/core/
decision_loop_runtime.rs1use std::{
5 panic::{AssertUnwindSafe, catch_unwind},
6 sync::OnceLock,
7};
8
9use crate::core::execution_lifecycle::{
10 CompletionObservation, ExecutionLifecycle, ProductEntitlements, RuntimeContext, ToolRequest,
11 ToolSurface,
12};
13
14#[cfg(any(test, feature = "test-support"))]
15use crate::core::triage::TriageEngine;
16
17pub use crate::core::execution_lifecycle::TaskContext;
18
19#[derive(Debug)]
20pub struct DecisionLoopRuntime {
22 lifecycle: ExecutionLifecycle,
23}
24
25impl DecisionLoopRuntime {
26 pub fn get_or_init() -> &'static Self {
27 static RUNTIME: OnceLock<DecisionLoopRuntime> = OnceLock::new();
28 RUNTIME.get_or_init(|| Self {
29 lifecycle: ExecutionLifecycle::global().clone(),
30 })
31 }
32
33 pub fn profile_for_session(
35 &self,
36 session_id: &str,
37 ) -> Option<crate::core::triage::profile::TaskProfileLocal> {
38 self.lifecycle.profile_for_session(session_id)
39 }
40
41 pub fn on_tool_start(
42 &self,
43 tool_name: &str,
44 query: Option<&str>,
45 session_id: &str,
46 agent_id: &str,
47 ) -> TaskContext {
48 catch_unwind(AssertUnwindSafe(|| {
49 self.lifecycle.begin(
50 ToolRequest {
51 tool_name: tool_name.to_owned(),
52 query: query.map(str::to_owned),
53 session_id: session_id.to_owned(),
54 agent_id: agent_id.to_owned(),
55 surface: ToolSurface::Mcp,
56 idempotency_key: None,
57 },
58 RuntimeContext::default(),
59 ProductEntitlements::default(),
60 )
61 }))
62 .unwrap_or_else(|_| {
63 self.lifecycle.begin(
64 ToolRequest {
65 tool_name: tool_name.to_owned(),
66 query: None,
67 session_id: session_id.to_owned(),
68 agent_id: agent_id.to_owned(),
69 surface: ToolSurface::Mcp,
70 idempotency_key: None,
71 },
72 RuntimeContext::default(),
73 ProductEntitlements::default(),
74 )
75 })
76 }
77
78 pub fn on_tool_end(
79 &self,
80 ctx: &TaskContext,
81 input_tokens: u64,
82 output_tokens: u64,
83 model: &str,
84 success: bool,
85 ) -> Option<crate::core::value_gate::ValueAssessment> {
86 if ctx.outcome().is_some() {
87 return None;
88 }
89 catch_unwind(AssertUnwindSafe(|| {
90 self.lifecycle
91 .complete_once(
92 ctx,
93 CompletionObservation::tool_result(input_tokens, output_tokens, model, success),
94 )
95 .and_then(|outcome| outcome.assessment)
96 }))
97 .ok()
98 .flatten()
99 }
100
101 #[cfg(any(test, feature = "test-support"))]
102 pub fn with_triage(triage: TriageEngine) -> Self {
103 Self {
104 lifecycle: ExecutionLifecycle::with_triage(triage),
105 }
106 }
107
108 #[cfg(any(test, feature = "test-support"))]
109 pub fn assessment_for(
110 &self,
111 task_id: &str,
112 ) -> Option<crate::core::value_gate::ValueAssessment> {
113 self.lifecycle.assessment_for(task_id)
114 }
115
116 #[cfg(any(test, feature = "test-support"))]
117 pub fn outcome_for(
118 &self,
119 task_id: &str,
120 ) -> Option<crate::core::execution_lifecycle::LifecycleOutcome> {
121 self.lifecycle.outcome_for(task_id)
122 }
123}