harn_vm/orchestration/
mod.rs1use std::path::PathBuf;
2use std::{cell::RefCell, thread_local};
3
4use serde::{Deserialize, Serialize};
5
6use crate::llm::vm_value_to_json;
7use crate::value::{VmError, VmValue};
8
9pub(crate) fn now_unix_seconds_text() -> String {
18 use std::time::{SystemTime, UNIX_EPOCH};
19 let ts = SystemTime::now()
20 .duration_since(UNIX_EPOCH)
21 .unwrap_or_default()
22 .as_secs();
23 format!("{ts}")
24}
25
26pub(crate) fn new_id(prefix: &str) -> String {
27 format!("{prefix}_{}", uuid::Uuid::now_v7())
28}
29
30pub(crate) fn default_run_dir() -> PathBuf {
31 let base = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
32 crate::runtime_paths::run_root(&base)
33}
34
35mod hooks;
36pub use hooks::*;
37#[cfg(test)]
38mod tests_lazy_hooks;
39
40mod pipeline_lifecycle;
41pub use pipeline_lifecycle::*;
42
43mod settlement_agent;
44pub use settlement_agent::*;
45
46mod lifecycle_receipts;
47pub use lifecycle_receipts::*;
48
49mod command_policy;
50pub use command_policy::*;
51
52mod tool_precheck;
53pub use tool_precheck::*;
54
55mod compaction;
56pub use compaction::*;
57
58mod repair_ledger;
59
60mod compact_lifecycle;
61pub use compact_lifecycle::*;
62
63mod compaction_receipt;
64pub use compaction_receipt::*;
65
66mod compaction_policy_registry;
67pub use compaction_policy_registry::*;
68
69pub mod agent_inbox;
70
71mod artifacts;
72pub use artifacts::*;
73
74mod assemble;
75pub use assemble::*;
76
77mod handoffs;
78pub use handoffs::*;
79
80mod friction;
81pub use friction::*;
82
83mod crystallize;
84pub use crystallize::*;
85
86mod release_fixture;
87pub use release_fixture::*;
88
89mod replay_oracle;
90pub use replay_oracle::*;
91
92mod replay_bench;
93pub use replay_bench::*;
94
95mod policy;
96#[cfg(test)]
97pub(crate) use policy::swap_execution_policy_stack;
98pub use policy::*;
99
100mod ambient_scope;
101pub(crate) use ambient_scope::{
102 scope_ambient, scope_ambient_transaction, scope_inline_subtask, scope_run_event_sink,
103 AmbientExecutionScope,
104};
105pub use ambient_scope::{
106 scope_llm_runtime_overrides, scope_llm_runtime_overrides_with_provider_endpoints,
107};
108
109mod stage_options;
110pub use stage_options::*;
111
112mod workflow;
113pub use workflow::*;
114
115mod workflow_bundle;
116pub use workflow_bundle::*;
117
118mod workflow_patch;
119pub use workflow_patch::*;
120
121mod safe_function_tools;
122pub use safe_function_tools::*;
123
124mod nested_invocation;
125pub use nested_invocation::*;
126
127#[cfg(test)]
128mod workflow_test_fixtures;
129
130mod records;
131pub use records::*;
132
133mod training_example;
134pub use training_example::*;
135
136mod context_eval;
137pub use context_eval::*;
138
139mod skill_gate;
140pub use skill_gate::*;
141
142mod merge_captain_audit;
143pub use merge_captain_audit::*;
144
145mod merge_captain_driver;
146pub use merge_captain_driver::*;
147
148mod merge_captain_ladder;
149pub use merge_captain_ladder::*;
150
151mod merge_captain_iteration;
152pub use merge_captain_iteration::*;
153
154pub mod playground;
155
156thread_local! {
157 static CURRENT_MUTATION_SESSION: RefCell<Option<MutationSessionRecord>> = const { RefCell::new(None) };
158 static CURRENT_WORKFLOW_SKILL_CONTEXT: RefCell<Option<WorkflowSkillContext>> = const { RefCell::new(None) };
164}
165
166#[derive(Clone, Default)]
171pub struct WorkflowSkillContext {
172 pub registry: Option<VmValue>,
173 pub match_config: Option<VmValue>,
174}
175
176pub fn install_workflow_skill_context(context: Option<WorkflowSkillContext>) {
177 CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| {
178 *slot.borrow_mut() = context;
179 });
180}
181
182pub fn current_workflow_skill_context() -> Option<WorkflowSkillContext> {
183 CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| slot.borrow().clone())
184}
185
186pub struct WorkflowSkillContextGuard;
190
191impl Drop for WorkflowSkillContextGuard {
192 fn drop(&mut self) {
193 install_workflow_skill_context(None);
194 }
195}
196
197#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
198#[serde(default)]
199pub struct MutationSessionRecord {
200 pub session_id: String,
201 pub parent_session_id: Option<String>,
202 pub run_id: Option<String>,
203 pub worker_id: Option<String>,
204 pub execution_kind: Option<String>,
205 pub mutation_scope: String,
206 pub approval_policy: Option<ToolApprovalPolicy>,
210}
211
212impl MutationSessionRecord {
213 pub fn normalize(mut self) -> Self {
214 if self.session_id.is_empty() {
215 self.session_id = new_id("session");
216 }
217 if self.mutation_scope.is_empty() {
218 self.mutation_scope = "read_only".to_string();
219 }
220 self
221 }
222}
223
224pub fn install_current_mutation_session(session: Option<MutationSessionRecord>) {
225 CURRENT_MUTATION_SESSION.with(|slot| {
226 *slot.borrow_mut() = session.map(MutationSessionRecord::normalize);
227 });
228}
229
230pub fn current_mutation_session() -> Option<MutationSessionRecord> {
231 CURRENT_MUTATION_SESSION.with(|slot| slot.borrow().clone())
232}
233
234pub(crate) fn swap_mutation_session(
242 next: Option<MutationSessionRecord>,
243) -> Option<MutationSessionRecord> {
244 CURRENT_MUTATION_SESSION.with(|slot| std::mem::replace(&mut *slot.borrow_mut(), next))
245}
246pub(crate) fn parse_json_payload<T: for<'de> Deserialize<'de>>(
247 json: serde_json::Value,
248 label: &str,
249) -> Result<T, VmError> {
250 let payload = json.to_string();
251 let mut deserializer = serde_json::Deserializer::from_str(&payload);
252 let mut tracker = serde_path_to_error::Track::new();
253 let path_deserializer = serde_path_to_error::Deserializer::new(&mut deserializer, &mut tracker);
254 T::deserialize(path_deserializer).map_err(|error| {
255 let snippet = if payload.len() > 600 {
256 format!("{}...", &payload[..600])
257 } else {
258 payload.clone()
259 };
260 VmError::Runtime(format!(
261 "{label} parse error at {}: {} | payload={}",
262 tracker.path(),
263 error,
264 snippet
265 ))
266 })
267}
268
269pub(crate) fn parse_json_value<T: for<'de> Deserialize<'de>>(
270 value: &VmValue,
271) -> Result<T, VmError> {
272 parse_json_payload(vm_value_to_json(value), "orchestration")
273}
274
275#[cfg(test)]
276mod tests;
277
278#[cfg(test)]
279mod policy_restriction_tests;
280
281#[cfg(test)]
282mod typed_options_parity;