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 approval_reviewer;
59pub use approval_reviewer::*;
60
61mod compaction;
62pub use compaction::*;
63
64mod repair_ledger;
65
66mod compact_lifecycle;
67pub use compact_lifecycle::*;
68
69mod compaction_receipt;
70pub use compaction_receipt::*;
71
72mod compaction_policy_registry;
73pub use compaction_policy_registry::*;
74
75pub mod agent_inbox;
76
77mod artifacts;
78pub use artifacts::*;
79
80mod assemble;
81pub use assemble::*;
82
83mod handoffs;
84pub use handoffs::*;
85
86mod friction;
87pub use friction::*;
88
89mod crystallize;
90pub use crystallize::*;
91
92mod release_fixture;
93pub use release_fixture::*;
94
95mod replay_oracle;
96pub use replay_oracle::*;
97
98mod replay_bench;
99pub use replay_bench::*;
100
101mod policy;
102#[cfg(test)]
103pub(crate) use policy::swap_execution_policy_stack;
104pub use policy::*;
105
106mod ambient_scope;
107pub use ambient_scope::blocking::run_blocking_with_ambient;
108pub(crate) use ambient_scope::{
109 scope_agent_session, scope_ambient, scope_ambient_transaction, scope_approval_policy,
110 scope_autonomy_policy, scope_command_policy, scope_dynamic_permissions, scope_inline_subtask,
111 scope_run_event_sink, scope_spawned_source_dir, AmbientExecutionScope,
112};
113pub use ambient_scope::{
114 scope_execution_policy, scope_fresh_run_runtime, scope_fresh_tracing_runtime,
115 scope_fresh_trigger_registry, scope_llm_runtime_overrides,
116 scope_llm_runtime_overrides_with_provider_endpoints,
117};
118
119mod stage_options;
120pub use stage_options::*;
121
122mod workflow;
123pub use workflow::*;
124
125mod workflow_bundle;
126pub use workflow_bundle::*;
127
128mod workflow_patch;
129pub use workflow_patch::*;
130
131mod safe_function_tools;
132pub use safe_function_tools::*;
133
134mod nested_invocation;
135pub use nested_invocation::*;
136
137#[cfg(test)]
138mod workflow_test_fixtures;
139
140mod records;
141pub use records::*;
142
143mod run_review;
144pub use run_review::*;
145
146mod run_view_fixtures;
147pub use run_view_fixtures::*;
148
149mod training_example;
150pub use training_example::*;
151
152mod context_eval;
153pub use context_eval::*;
154
155mod skill_gate;
156pub use skill_gate::*;
157
158mod merge_captain_audit;
159pub use merge_captain_audit::*;
160
161mod merge_captain_driver;
162pub use merge_captain_driver::*;
163
164mod merge_captain_ladder;
165pub use merge_captain_ladder::*;
166
167mod merge_captain_iteration;
168pub use merge_captain_iteration::*;
169
170pub mod playground;
171
172thread_local! {
173 static CURRENT_MUTATION_SESSION: RefCell<Option<MutationSessionRecord>> = const { RefCell::new(None) };
174 static CURRENT_WORKFLOW_SKILL_CONTEXT: RefCell<Option<WorkflowSkillContext>> = const { RefCell::new(None) };
180}
181
182#[derive(Clone, Default)]
187pub struct WorkflowSkillContext {
188 pub registry: Option<VmValue>,
189 pub match_config: Option<VmValue>,
190}
191
192pub fn install_workflow_skill_context(context: Option<WorkflowSkillContext>) {
193 CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| {
194 *slot.borrow_mut() = context;
195 });
196}
197
198pub fn current_workflow_skill_context() -> Option<WorkflowSkillContext> {
199 CURRENT_WORKFLOW_SKILL_CONTEXT.with(|slot| slot.borrow().clone())
200}
201
202pub struct WorkflowSkillContextGuard;
206
207impl Drop for WorkflowSkillContextGuard {
208 fn drop(&mut self) {
209 install_workflow_skill_context(None);
210 }
211}
212
213#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
214#[serde(default)]
215pub struct MutationSessionRecord {
216 pub session_id: String,
217 pub parent_session_id: Option<String>,
218 pub run_id: Option<String>,
219 pub worker_id: Option<String>,
220 pub execution_kind: Option<String>,
221 pub mutation_scope: String,
222 pub approval_policy: Option<ToolApprovalPolicy>,
226}
227
228impl MutationSessionRecord {
229 pub fn normalize(mut self) -> Self {
230 if self.session_id.is_empty() {
231 self.session_id = new_id("session");
232 }
233 if self.mutation_scope.is_empty() {
234 self.mutation_scope = "read_only".to_string();
235 }
236 self
237 }
238}
239
240pub fn install_current_mutation_session(session: Option<MutationSessionRecord>) {
241 CURRENT_MUTATION_SESSION.with(|slot| {
242 *slot.borrow_mut() = session.map(MutationSessionRecord::normalize);
243 });
244}
245
246pub fn current_mutation_session() -> Option<MutationSessionRecord> {
247 CURRENT_MUTATION_SESSION.with(|slot| slot.borrow().clone())
248}
249
250pub(crate) fn swap_mutation_session(
258 next: Option<MutationSessionRecord>,
259) -> Option<MutationSessionRecord> {
260 CURRENT_MUTATION_SESSION.with(|slot| std::mem::replace(&mut *slot.borrow_mut(), next))
261}
262
263const PAYLOAD_SNIPPET_MAX_BYTES: usize = 600;
265
266pub(crate) fn parse_json_payload<T: for<'de> Deserialize<'de>>(
267 json: serde_json::Value,
268 label: &str,
269) -> Result<T, VmError> {
270 let payload = json.to_string();
271 let mut deserializer = serde_json::Deserializer::from_str(&payload);
272 let mut tracker = serde_path_to_error::Track::new();
273 let path_deserializer = serde_path_to_error::Deserializer::new(&mut deserializer, &mut tracker);
274 T::deserialize(path_deserializer).map_err(|error| {
275 let snippet = crate::text::truncate_end_bytes(&payload, PAYLOAD_SNIPPET_MAX_BYTES);
276 VmError::Runtime(format!(
277 "{label} parse error at {}: {} | payload={}",
278 tracker.path(),
279 error,
280 snippet
281 ))
282 })
283}
284
285pub(crate) fn parse_json_value<T: for<'de> Deserialize<'de>>(
286 value: &VmValue,
287) -> Result<T, VmError> {
288 parse_json_payload(vm_value_to_json(value), "orchestration")
289}
290
291#[cfg(test)]
292mod tests;
293
294#[cfg(test)]
295mod policy_restriction_tests;
296
297#[cfg(test)]
298mod typed_options_parity;