1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::path::PathBuf;
3use std::sync::atomic::{AtomicBool, Ordering};
4use std::sync::{Arc, Mutex};
5use std::time::Instant;
6
7use crate::chunk::{Chunk, ChunkRef, Constant};
8use crate::runtime_limits::RuntimeLimits;
9use crate::value::{
10 ModuleFunctionRegistry, VmAsyncBuiltinFn, VmBuiltinFn, VmClosure, VmEnv, VmError, VmMutex,
11 VmTaskHandle, VmValue,
12};
13use crate::BuiltinId;
14
15use super::debug::DebugHook;
16pub(crate) use super::execution_deadline::{ExecutionDeadlinePauseGuard, ExecutionDeadlineState};
17use super::modules::ModuleCache;
18use super::VmBuiltinMetadata;
19
20pub(crate) struct ResolvedLazyCallable {
34 pub(crate) exports: BTreeMap<String, Arc<VmClosure>>,
35 #[allow(dead_code)]
40 pub(crate) retained_module_graph: ModuleCache,
41}
42
43pub(crate) type LazyCallableResolution = Arc<ResolvedLazyCallable>;
44pub(crate) struct LazyCallableCacheSlot {
45 pub(crate) execution_guard: Option<Arc<harn_modules::package_execution::PackageExecutionGuard>>,
46 pub(crate) resolution: Arc<tokio::sync::OnceCell<LazyCallableResolution>>,
47}
48pub(crate) type LazyCallableModuleCache =
49 Arc<VmMutex<BTreeMap<PathBuf, Vec<LazyCallableCacheSlot>>>>;
50
51pub(crate) struct ScopeSpan(u64);
53
54impl ScopeSpan {
55 pub(crate) fn new(kind: crate::tracing::SpanKind, name: String) -> Self {
56 Self(crate::tracing::span_start(kind, name))
57 }
58}
59
60impl Drop for ScopeSpan {
61 fn drop(&mut self) {
62 crate::tracing::span_end(self.0);
63 }
64}
65
66#[derive(Clone)]
67pub(crate) struct LocalSlot {
68 pub(crate) value: VmValue,
69 pub(crate) initialized: bool,
70 pub(crate) synced: bool,
71}
72
73impl Drop for LocalSlot {
74 fn drop(&mut self) {
75 if crate::value::recursion::is_recursive_container(&self.value) {
83 crate::value::recursion::dismantle(std::mem::replace(&mut self.value, VmValue::Nil));
84 }
85 }
86}
87
88#[derive(Clone)]
89pub(crate) struct InterruptHandler {
90 pub(crate) handle: i64,
91 pub(crate) signals: Vec<String>,
92 pub(crate) once: bool,
93 pub(crate) graceful_timeout_ms: Option<u64>,
94 pub(crate) handler: VmValue,
95}
96
97pub(crate) struct CallFrame {
99 pub(crate) chunk: ChunkRef,
100 pub(crate) inline_cache_set: usize,
104 pub(crate) ip: usize,
105 pub(crate) stack_base: usize,
106 pub(crate) saved_env: VmEnv,
107 pub(crate) initial_env: Option<VmEnv>,
115 pub(crate) initial_local_slots: Option<Vec<LocalSlot>>,
116 pub(crate) saved_iterator_depth: usize,
118 pub(crate) fn_name: crate::value::HarnStr,
121 pub(crate) argc: usize,
123 pub(crate) saved_source_dir: Option<std::path::PathBuf>,
126 pub(crate) module_functions: Option<ModuleFunctionRegistry>,
128 pub(crate) module_state: Option<crate::value::ModuleState>,
134 pub(crate) local_slots: Vec<LocalSlot>,
136 pub(crate) local_scope_base: usize,
138 pub(crate) local_scope_depth: usize,
140}
141
142pub(crate) struct InlineCacheSite {
143 pub(crate) cache_set: usize,
144 pub(crate) slot_count: usize,
145 pub(crate) slot: Option<usize>,
146}
147
148impl CallFrame {
149 #[inline]
150 pub(crate) fn inline_cache_site_for_previous_op(&self) -> InlineCacheSite {
151 let op_offset = self.ip.saturating_sub(1);
152 InlineCacheSite {
153 cache_set: self.inline_cache_set,
154 slot_count: self.chunk.inline_cache_slot_count(),
155 slot: self.chunk.inline_cache_slot(op_offset),
156 }
157 }
158}
159
160pub(crate) struct ExceptionHandler {
162 pub(crate) catch_ip: usize,
163 pub(crate) stack_depth: usize,
164 pub(crate) frame_depth: usize,
165 pub(crate) env_scope_depth: usize,
166 pub(crate) error_type: Option<crate::value::HarnStr>,
168}
169
170pub(crate) struct TaskScope {
173 pub(crate) task_ids: Vec<String>,
176 pub(crate) frame_depth: usize,
178 pub(crate) env_scope_depth: usize,
180}
181
182pub(crate) struct ProcessExitRequest {
186 code: Mutex<Option<i32>>,
187 requested: AtomicBool,
188}
189
190impl ProcessExitRequest {
191 fn new() -> Self {
192 Self {
193 code: Mutex::new(None),
194 requested: AtomicBool::new(false),
195 }
196 }
197
198 fn request(&self, code: i32) {
199 let mut recorded = self
200 .code
201 .lock()
202 .expect("process exit request lock poisoned");
203 if recorded.is_none() {
204 *recorded = Some(code);
205 self.requested.store(true, Ordering::Release);
206 }
207 }
208
209 fn code(&self) -> Option<i32> {
210 if !self.requested.load(Ordering::Acquire) {
211 return None;
212 }
213 *self
214 .code
215 .lock()
216 .expect("process exit request lock poisoned")
217 }
218}
219
220pub(crate) enum IterState {
222 Vec {
223 items: Arc<Vec<VmValue>>,
224 idx: usize,
225 },
226 Dict {
227 entries: Arc<crate::value::DictMap>,
228 keys: Vec<crate::value::HarnStr>,
229 idx: usize,
230 },
231 Channel {
232 receiver: std::sync::Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<VmValue>>>,
233 close: std::sync::Arc<crate::value::VmChannelCloseState>,
234 },
235 Generator {
236 gen: Arc<crate::value::VmGenerator>,
237 },
238 Stream {
239 stream: Arc<crate::value::VmStream>,
240 },
241 Range {
245 next: i64,
246 end: i64,
247 inclusive: bool,
248 done: bool,
249 },
250 VmIter {
251 handle: crate::vm::iter::VmIterHandle,
252 },
253}
254
255#[derive(Clone)]
256pub(crate) enum VmBuiltinDispatch {
257 Sync(VmBuiltinFn),
258 Async(VmAsyncBuiltinFn),
259}
260
261#[derive(Clone)]
262pub(crate) struct VmBuiltinEntry {
263 pub(crate) name: Arc<str>,
264 pub(crate) dispatch: VmBuiltinDispatch,
265 pub(crate) recorded_effects: Option<&'static [harn_builtin_meta::EffectSpec]>,
269}
270
271pub struct Vm {
273 pub(crate) stack: Vec<VmValue>,
274 pub(crate) env: VmEnv,
275 pub(crate) output: String,
276 pub(crate) builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
277 pub(crate) async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
278 pub(crate) capability_methods:
282 Arc<BTreeMap<harn_builtin_meta::CapabilityId, BTreeMap<String, VmBuiltinDispatch>>>,
283 pub(crate) builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
284 pub(crate) builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
287 pub(crate) builtin_id_collisions: Arc<HashSet<BuiltinId>>,
290 pub(crate) iterators: Vec<IterState>,
292 pub(crate) frames: Vec<CallFrame>,
294 pub(crate) exception_handlers: Vec<ExceptionHandler>,
296 pub(crate) spawned_tasks: BTreeMap<String, VmTaskHandle>,
298 pub(crate) process_exit_request: Arc<ProcessExitRequest>,
300 pub(crate) sync_runtime: Arc<crate::synchronization::VmSyncRuntime>,
302 pub(crate) shared_state_runtime: Arc<crate::shared_state::VmSharedStateRuntime>,
304 pub(crate) worker_registry: Arc<crate::stdlib::agents::agents_workers::WorkerRegistry>,
308 pub(crate) daemon_registry: Arc<crate::stdlib::agents_daemon::DaemonRegistry>,
310 pub(crate) trigger_registry: Arc<crate::triggers::registry::TriggerRegistryRuntime>,
313 pub(crate) session_runtime: Arc<crate::agent_sessions::AgentSessionRuntime>,
315 pub(crate) tracing_runtime: Arc<crate::tracing::TracingRuntime>,
317 pub(crate) execution_id: Arc<str>,
319 pub(crate) owns_execution: bool,
321 pub(crate) flight_recorder: Option<Arc<crate::flight_recorder::FlightRecorder>>,
323 pub(crate) flight_recorder_max_events: Option<usize>,
325 pub(crate) agent_host_session_runtime:
327 Arc<crate::llm::agent_session_host::AgentHostSessionRuntime>,
328 pub(crate) connector_clients: Arc<crate::connectors::VmConnectorClients>,
332 pub(crate) inline_cache_sets: Vec<Vec<crate::chunk::InlineCacheEntry>>,
336 pub(crate) inline_cache_set_by_chunk: HashMap<u64, usize>,
337 pub(crate) pool_registry: Arc<crate::stdlib::pool::PoolRegistry>,
339 pub(crate) llm_mock_context: crate::llm::mock::LlmMockContext,
341 pub(crate) package_snapshot_registry: Arc<crate::stdlib::PackageSnapshotRegistry>,
345 pub(crate) wait_for_graph: Arc<crate::wait_for_graph::VmWaitForGraph>,
347 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
349 pub(crate) inherited_held_keys: Arc<Vec<crate::synchronization::VmSyncHeldKey>>,
357 pub(crate) task_scopes: Vec<TaskScope>,
363 pub(crate) task_counter: u64,
365 pub(crate) runtime_context_counter: u64,
367 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
369 pub(crate) deadlines: Vec<(Instant, usize)>,
371 pub(crate) execution_deadline: Arc<ExecutionDeadlineState>,
373 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
378 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
384 pub(crate) pending_function_bp: Option<String>,
389 pub(crate) step_mode: bool,
391 pub(crate) step_frame_depth: usize,
393 pub(crate) stopped: bool,
395 pub(crate) last_line: usize,
397 pub(crate) source_dir: Option<std::path::PathBuf>,
399 pub(crate) package_execution_guard:
401 Option<Arc<harn_modules::package_execution::PackageExecutionGuard>>,
402 pub(crate) imported_paths: Vec<std::path::PathBuf>,
404 pub(crate) deferred_cyclic_imports: Vec<super::modules::DeferredCyclicImport>,
408 pub(crate) module_cache: ModuleCache,
410 pub(crate) prepared_module_cache: crate::PreparedModuleCache,
413 pub(crate) prepared_module_validation: crate::prepared_module::PreparedModuleValidation,
415 pub(crate) module_provenance: crate::module_artifact::ModuleProvenance,
418 pub(crate) module_phase_recorder: Option<super::ModulePhaseRecorder>,
420 pub(crate) lazy_callable_modules: LazyCallableModuleCache,
424 pub(crate) source_cache: Arc<BTreeMap<std::path::PathBuf, Arc<str>>>,
428 pub(crate) graph_link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
433 pub(crate) linked_program_repository:
437 Option<Arc<crate::linked_program::LinkedProgramRepository>>,
438 pub(crate) source_file: Option<String>,
440 pub(crate) source_text: Option<String>,
442 pub(crate) coverage: Option<crate::coverage::Coverage>,
445 pub(crate) bridge: Option<Arc<crate::bridge::HostBridge>>,
447 pub(crate) denied_builtins: Arc<HashSet<String>>,
449 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
451 pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
452 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
457 pub(crate) interrupt_handlers: Vec<InterruptHandler>,
459 pub(crate) next_interrupt_handle: i64,
460 pub(crate) pending_interrupt_signal: Option<String>,
461 pub(crate) interrupted: bool,
462 pub(crate) dispatching_interrupt: bool,
463 pub(crate) interrupt_handler_deadline: Option<Instant>,
464 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
466 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
469 pub(crate) project_root: Option<std::path::PathBuf>,
472 pub(crate) globals: Arc<crate::value::DictMap>,
475 pub(crate) root_harness: Option<VmValue>,
480 pub(crate) runtime_effects: crate::orchestration::RuntimeEffectState,
482 pub(crate) debug_hook: Option<parking_lot::Mutex<Box<DebugHook>>>,
484 pub(crate) runtime_limits: RuntimeLimits,
486}
487
488#[derive(Clone)]
496pub struct VmBaseline {
497 builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
498 async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
499 capability_methods:
500 Arc<BTreeMap<harn_builtin_meta::CapabilityId, BTreeMap<String, VmBuiltinDispatch>>>,
501 builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
502 builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
503 builtin_id_collisions: Arc<HashSet<BuiltinId>>,
504 source_dir: Option<std::path::PathBuf>,
505 source_file: Option<String>,
506 source_text: Option<String>,
507 project_root: Option<std::path::PathBuf>,
508 globals: Arc<crate::value::DictMap>,
509 root_harness: Option<VmValue>,
510 denied_builtins: Arc<HashSet<String>>,
511 prepared_module_cache: crate::PreparedModuleCache,
512 module_provenance: crate::module_artifact::ModuleProvenance,
513 graph_link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
516 linked_program_repository: Option<Arc<crate::linked_program::LinkedProgramRepository>>,
517 runtime_limits: RuntimeLimits,
518}
519
520impl VmBaseline {
521 pub fn from_vm(vm: &Vm) -> Self {
522 Self {
523 builtins: Arc::clone(&vm.builtins),
524 async_builtins: Arc::clone(&vm.async_builtins),
525 capability_methods: Arc::clone(&vm.capability_methods),
526 builtin_metadata: Arc::clone(&vm.builtin_metadata),
527 builtins_by_id: Arc::clone(&vm.builtins_by_id),
528 builtin_id_collisions: Arc::clone(&vm.builtin_id_collisions),
529 source_dir: vm.source_dir.clone(),
530 source_file: vm.source_file.clone(),
531 source_text: vm.source_text.clone(),
532 project_root: vm.project_root.clone(),
533 globals: Arc::clone(&vm.globals),
534 root_harness: vm.root_harness.clone(),
535 denied_builtins: Arc::clone(&vm.denied_builtins),
536 prepared_module_cache: vm.prepared_module_cache.clone(),
537 module_provenance: vm.module_provenance,
538 graph_link_table: vm.graph_link_table.clone(),
539 linked_program_repository: vm.linked_program_repository.clone(),
540 runtime_limits: vm.runtime_limits,
541 }
542 }
543
544 pub fn instantiate(&self) -> Vm {
545 crate::initialize_runtime_assets();
546 let mut source_cache = BTreeMap::new();
547 if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
548 source_cache.insert(std::path::PathBuf::from(file), Arc::from(text.as_str()));
549 }
550 if let Some(dir) = &self.source_dir {
551 crate::stdlib::set_thread_source_dir(dir);
552 }
553
554 let mut vm = Vm {
555 stack: Vec::with_capacity(256),
556 env: VmEnv::new(),
557 output: String::new(),
558 builtins: Arc::clone(&self.builtins),
559 async_builtins: Arc::clone(&self.async_builtins),
560 capability_methods: Arc::clone(&self.capability_methods),
561 builtin_metadata: Arc::clone(&self.builtin_metadata),
562 builtins_by_id: Arc::clone(&self.builtins_by_id),
563 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
564 iterators: Vec::new(),
565 frames: Vec::new(),
566 exception_handlers: Vec::new(),
567 spawned_tasks: BTreeMap::new(),
568 process_exit_request: Arc::new(ProcessExitRequest::new()),
569 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
570 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
571 worker_registry: crate::stdlib::agents::agents_workers::active_worker_registry(),
572 daemon_registry: crate::stdlib::agents_daemon::active_daemon_registry(),
573 trigger_registry: crate::triggers::registry::active_trigger_registry(),
574 session_runtime: crate::agent_sessions::active_session_runtime(),
575 tracing_runtime: crate::tracing::active_tracing_runtime(),
576 execution_id: crate::observability::execution_scope::mint_execution_scope(),
577 owns_execution: true,
578 agent_host_session_runtime:
579 crate::llm::agent_session_host::active_agent_host_session_runtime(),
580 connector_clients: Arc::new(crate::connectors::VmConnectorClients::default()),
581 inline_cache_sets: Vec::new(),
582 inline_cache_set_by_chunk: HashMap::new(),
583 pool_registry: crate::stdlib::pool::new_pool_registry(),
584 llm_mock_context: crate::llm::mock::LlmMockContext::for_new_vm(),
585 package_snapshot_registry: Arc::new(Default::default()),
586 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
587 held_sync_guards: Vec::new(),
588 inherited_held_keys: Arc::new(Vec::new()),
589 task_scopes: Vec::new(),
590 task_counter: 0,
591 runtime_context_counter: 0,
592 runtime_context: crate::runtime_context::RuntimeContext::root(),
593 deadlines: Vec::new(),
594 execution_deadline: super::execution::new_execution_deadline_state(None),
595 breakpoints: BTreeMap::new(),
596 function_breakpoints: std::collections::BTreeSet::new(),
597 pending_function_bp: None,
598 step_mode: false,
599 step_frame_depth: 0,
600 stopped: false,
601 last_line: 0,
602 source_dir: self.source_dir.clone(),
603 package_execution_guard: None,
604 imported_paths: Vec::new(),
605 deferred_cyclic_imports: Vec::new(),
606 module_cache: Arc::new(BTreeMap::new()),
607 prepared_module_cache: self.prepared_module_cache.clone(),
608 prepared_module_validation: crate::prepared_module::PreparedModuleValidation::default(),
609 module_provenance: self.module_provenance,
610 module_phase_recorder: None,
611 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
612 source_cache: Arc::new(source_cache),
613 graph_link_table: self.graph_link_table.clone(),
614 linked_program_repository: self.linked_program_repository.clone(),
615 source_file: self.source_file.clone(),
616 source_text: self.source_text.clone(),
617 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
618 flight_recorder: None,
619 flight_recorder_max_events: None,
620 bridge: None,
621 denied_builtins: Arc::clone(&self.denied_builtins),
622 cancel_token: None,
623 interrupt_signal_token: None,
624 cancel_grace_instructions_remaining: None,
625 interrupt_handlers: Vec::new(),
626 next_interrupt_handle: 1,
627 pending_interrupt_signal: None,
628 interrupted: false,
629 dispatching_interrupt: false,
630 interrupt_handler_deadline: None,
631 error_stack_trace: Vec::new(),
632 yield_sender: None,
633 project_root: self.project_root.clone(),
634 globals: Arc::clone(&self.globals),
635 root_harness: self.root_harness.clone(),
636 runtime_effects: crate::orchestration::RuntimeEffectState::fresh(),
637 debug_hook: None,
638 runtime_limits: self.runtime_limits,
639 };
640
641 crate::stdlib::rebind_execution_state_builtins(&mut vm);
642 vm
643 }
644}
645
646impl Vm {
647 pub(crate) fn ensure_execution_available(&self) -> Result<(), VmError> {
648 if self.execution_deadline.is_abandoned() {
649 return Err(VmError::AbandonedExecution);
650 }
651 Ok(())
652 }
653
654 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
655 chunk
656 .local_slots
657 .iter()
658 .map(|_| LocalSlot {
659 value: VmValue::Nil,
660 initialized: false,
661 synced: false,
662 })
663 .collect()
664 }
665
666 pub(crate) fn bind_param_slots(
667 slots: &mut [LocalSlot],
668 func: &crate::chunk::CompiledFunction,
669 args: &[VmValue],
670 synced: bool,
671 ) {
672 Self::bind_param_slots_args(slots, func, &super::CallArgs::Slice(args), synced);
673 }
674
675 pub(crate) fn bind_param_slots_args(
676 slots: &mut [LocalSlot],
677 func: &crate::chunk::CompiledFunction,
678 args: &super::CallArgs<'_>,
679 synced: bool,
680 ) {
681 let param_count = func.params.len();
682 for (i, _param) in func.params.iter().enumerate() {
683 if i >= slots.len() {
684 break;
685 }
686 if func.has_rest_param && i == param_count - 1 {
687 let rest_args = args.to_vec_from(i);
688 slots[i].value = VmValue::List(std::sync::Arc::new(rest_args));
689 slots[i].initialized = true;
690 slots[i].synced = synced;
691 } else if let Some(arg) = args.get(i) {
692 slots[i].value = arg.clone();
693 slots[i].initialized = true;
694 slots[i].synced = synced;
695 }
696 }
697 }
698
699 pub(crate) fn visible_variables(&self) -> crate::value::DictMap {
700 let mut vars = self.env.all_variables();
701 let Some(frame) = self.frames.last() else {
702 return vars;
703 };
704 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
705 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
706 vars.insert(crate::value::intern_key(&info.name), slot.value.clone());
707 }
708 }
709 vars
710 }
711
712 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
713 let frames = &mut self.frames;
714 let env = &mut self.env;
715 let Some(frame) = frames.last_mut() else {
716 return;
717 };
718 let local_scope_base = frame.local_scope_base;
719 let local_scope_depth = frame.local_scope_depth;
720 for (slot, info) in frame
721 .local_slots
722 .iter_mut()
723 .zip(frame.chunk.local_slots.iter())
724 {
725 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
726 slot.synced = true;
727 let scope_idx = local_scope_base + info.scope_depth;
728 while env.scopes.len() <= scope_idx {
729 env.push_scope();
730 }
731 Arc::make_mut(&mut env.scopes[scope_idx].vars).insert(
735 info.name.clone(),
736 crate::value::Binding::Value {
737 value: slot.value.clone(),
738 mutable: info.mutable,
739 },
740 );
741 }
742 }
743 }
744
745 pub(crate) fn closure_call_env_for_current_frame(
746 &self,
747 closure: &crate::value::VmClosure,
748 ) -> VmEnv {
749 if closure.module_state().is_some() {
750 return closure.env.cloned_for_call();
751 }
752 let call_env = Self::closure_call_env(&self.env, closure);
753 if !closure.func.chunk.references_outer_names {
758 return call_env;
759 }
760 let mut call_env = call_env;
761 let Some(frame) = self.frames.last() else {
762 return call_env;
763 };
764 for (slot, info) in frame
765 .local_slots
766 .iter()
767 .zip(frame.chunk.local_slots.iter())
768 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
769 {
770 if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
771 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
772 }
773 }
774 call_env
775 }
776
777 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
778 let frame = self.frames.last()?;
779 let idx = self.active_local_slot_index(name)?;
780 frame.local_slots.get(idx).map(|slot| slot.value.clone())
781 }
782
783 pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
788 let frame = self.frames.last()?;
789 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
790 if info.name == name && info.scope_depth <= frame.local_scope_depth {
791 if let Some(slot) = frame.local_slots.get(idx) {
792 if slot.initialized {
793 return Some(idx);
794 }
795 }
796 }
797 }
798 None
799 }
800
801 pub(crate) fn assign_active_local_slot(
802 &mut self,
803 name: &str,
804 value: VmValue,
805 debug: bool,
806 ) -> Result<bool, VmError> {
807 let Some(frame) = self.frames.last_mut() else {
808 return Ok(false);
809 };
810 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
811 if info.name == name && info.scope_depth <= frame.local_scope_depth {
812 if !debug && !info.mutable {
813 return Err(VmError::ImmutableAssignment(name.to_string()));
814 }
815 if let Some(slot) = frame.local_slots.get_mut(idx) {
816 crate::value::recursion::dismantle(std::mem::replace(&mut slot.value, value));
817 slot.initialized = true;
818 slot.synced = false;
819 return Ok(true);
820 }
821 }
822 }
823 Ok(false)
824 }
825
826 pub fn new() -> Self {
827 crate::initialize_runtime_assets();
828 Self {
829 stack: Vec::with_capacity(256),
830 env: VmEnv::new(),
831 output: String::new(),
832 builtins: Arc::new(BTreeMap::new()),
833 async_builtins: Arc::new(BTreeMap::new()),
834 capability_methods: Arc::new(BTreeMap::new()),
835 builtin_metadata: Arc::new(BTreeMap::new()),
836 builtins_by_id: Arc::new(HashMap::new()),
837 builtin_id_collisions: Arc::new(HashSet::new()),
838 iterators: Vec::new(),
839 frames: Vec::new(),
840 exception_handlers: Vec::new(),
841 spawned_tasks: BTreeMap::new(),
842 process_exit_request: Arc::new(ProcessExitRequest::new()),
843 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
844 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
845 worker_registry: crate::stdlib::agents::agents_workers::active_worker_registry(),
846 daemon_registry: crate::stdlib::agents_daemon::active_daemon_registry(),
847 trigger_registry: crate::triggers::registry::active_trigger_registry(),
848 session_runtime: crate::agent_sessions::active_session_runtime(),
849 tracing_runtime: crate::tracing::active_tracing_runtime(),
850 execution_id: crate::observability::execution_scope::mint_execution_scope(),
851 owns_execution: true,
852 agent_host_session_runtime:
853 crate::llm::agent_session_host::active_agent_host_session_runtime(),
854 connector_clients: Arc::new(crate::connectors::VmConnectorClients::default()),
855 inline_cache_sets: Vec::new(),
856 inline_cache_set_by_chunk: HashMap::new(),
857 pool_registry: crate::stdlib::pool::new_pool_registry(),
858 llm_mock_context: crate::llm::mock::LlmMockContext::for_new_vm(),
859 package_snapshot_registry: Arc::new(Default::default()),
860 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
861 held_sync_guards: Vec::new(),
862 inherited_held_keys: Arc::new(Vec::new()),
863 task_scopes: Vec::new(),
864 task_counter: 0,
865 runtime_context_counter: 0,
866 runtime_context: crate::runtime_context::RuntimeContext::root(),
867 deadlines: Vec::new(),
868 execution_deadline: super::execution::new_execution_deadline_state(None),
869 breakpoints: BTreeMap::new(),
870 function_breakpoints: std::collections::BTreeSet::new(),
871 pending_function_bp: None,
872 step_mode: false,
873 step_frame_depth: 0,
874 stopped: false,
875 last_line: 0,
876 source_dir: None,
877 package_execution_guard: None,
878 imported_paths: Vec::new(),
879 deferred_cyclic_imports: Vec::new(),
880 module_cache: Arc::new(BTreeMap::new()),
881 prepared_module_cache: crate::PreparedModuleCache::default(),
882 prepared_module_validation: crate::prepared_module::PreparedModuleValidation::default(),
883 module_provenance: crate::module_artifact::ModuleProvenance::User,
884 module_phase_recorder: None,
885 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
886 source_cache: Arc::new(BTreeMap::new()),
887 graph_link_table: None,
888 linked_program_repository: None,
889 source_file: None,
890 source_text: None,
891 coverage: crate::coverage::for_primary(None),
892 flight_recorder: None,
893 flight_recorder_max_events: None,
894 bridge: None,
895 denied_builtins: Arc::new(HashSet::new()),
896 cancel_token: None,
897 interrupt_signal_token: None,
898 cancel_grace_instructions_remaining: None,
899 interrupt_handlers: Vec::new(),
900 next_interrupt_handle: 1,
901 pending_interrupt_signal: None,
902 interrupted: false,
903 dispatching_interrupt: false,
904 interrupt_handler_deadline: None,
905 error_stack_trace: Vec::new(),
906 yield_sender: None,
907 project_root: None,
908 globals: Arc::new(crate::value::DictMap::new()),
909 root_harness: None,
910 runtime_effects: crate::orchestration::RuntimeEffectState::fresh(),
911 debug_hook: None,
912 runtime_limits: RuntimeLimits::default(),
913 }
914 }
915
916 pub fn baseline(&self) -> VmBaseline {
917 VmBaseline::from_vm(self)
918 }
919
920 pub fn executed_effects(&self) -> Vec<crate::orchestration::EffectRecord> {
922 self.runtime_effects.snapshot()
923 }
924
925 pub fn clear_executed_effects(&mut self) {
927 self.runtime_effects.clear();
928 }
929
930 pub(crate) fn record_capability_effects(
931 &mut self,
932 capability: harn_builtin_meta::CapabilityId,
933 method: &str,
934 args: &[VmValue],
935 ) {
936 self.runtime_effects
937 .record_capability(capability, method, args);
938 }
939
940 pub(crate) fn record_builtin_contract_effects(&mut self, name: &str, args: &[VmValue]) {
941 let Some(entry) = crate::stdlib::recorded_effect_builtin_manifest_entry(name) else {
942 return;
943 };
944 self.record_builtin_effect_specs(entry.contract.effects, args);
945 }
946
947 pub(crate) fn record_builtin_effect_specs(
948 &mut self,
949 specs: &'static [harn_builtin_meta::EffectSpec],
950 args: &[VmValue],
951 ) {
952 self.runtime_effects.record_specs(specs, args);
953 }
954
955 pub fn set_prepared_module_cache(&mut self, cache: crate::PreparedModuleCache) {
958 self.prepared_module_cache = cache;
959 self.prepared_module_validation =
960 crate::prepared_module::PreparedModuleValidation::default();
961 }
962
963 pub fn set_graph_link_table(
971 &mut self,
972 link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
973 ) {
974 self.graph_link_table = link_table;
975 }
976
977 pub fn set_linked_program_runtime(
981 &mut self,
982 runtime: &crate::linked_program::LinkedProgramRuntime,
983 ) {
984 self.linked_program_repository = Some(Arc::clone(&runtime.repository));
985 self.graph_link_table = None;
986 }
987
988 pub fn runtime_limits(&self) -> RuntimeLimits {
990 self.runtime_limits
991 }
992
993 pub fn runtime_limit_report(&self) -> crate::RuntimeLimitsReport {
995 self.runtime_limits.report()
996 }
997
998 #[inline]
1012 pub(crate) fn debugger_attached(&self) -> bool {
1013 self.debug_hook.is_some()
1014 || !self.breakpoints.is_empty()
1015 || !self.function_breakpoints.is_empty()
1016 }
1017
1018 pub fn set_bridge(&mut self, bridge: Arc<crate::bridge::HostBridge>) {
1020 self.bridge = Some(bridge);
1021 }
1022
1023 pub fn set_denied_builtins(&mut self, mut denied: HashSet<String>) {
1026 let denied_canonical_names = denied
1030 .iter()
1031 .filter_map(|name| crate::stdlib::builtin_manifest_entry(name))
1032 .map(|entry| entry.canonical_name)
1033 .collect::<HashSet<_>>();
1034 if !denied_canonical_names.is_empty() {
1035 denied.extend(
1036 crate::stdlib::all_builtin_manifest()
1037 .iter()
1038 .filter(|entry| denied_canonical_names.contains(entry.canonical_name))
1039 .map(|entry| entry.name.to_string()),
1040 );
1041 }
1042 self.denied_builtins = Arc::new(denied);
1043 }
1044
1045 pub fn set_source_info(&mut self, file: &str, text: &str) {
1047 self.source_file = Some(file.to_string());
1048 self.source_text = Some(text.to_string());
1049 if let Some(cov) = self.coverage.as_mut() {
1050 cov.set_primary_file(file);
1051 }
1052 Arc::make_mut(&mut self.source_cache)
1053 .insert(std::path::PathBuf::from(file), Arc::from(text));
1054 }
1055
1056 pub fn start(&mut self, chunk: &Chunk) -> Result<(), VmError> {
1058 self.ensure_execution_available()?;
1059 let debugger = self.debugger_attached();
1066 let initial_env = if debugger {
1067 Some(self.env.clone())
1068 } else {
1069 None
1070 };
1071 let initial_local_slots = if debugger {
1072 Some(Self::fresh_local_slots(chunk))
1073 } else {
1074 None
1075 };
1076 let chunk = Arc::new(chunk.clone());
1077 let local_slots = Self::fresh_local_slots(&chunk);
1078 let inline_cache_set = self.inline_cache_set_index_for_chunk(&chunk);
1079 self.frames.push(CallFrame {
1080 chunk,
1081 inline_cache_set,
1082 ip: 0,
1083 stack_base: self.stack.len(),
1084 saved_env: self.env.clone(),
1085 initial_env,
1086 initial_local_slots,
1087 saved_iterator_depth: self.iterators.len(),
1088 fn_name: crate::value::HarnStr::new(),
1089 argc: 0,
1090 saved_source_dir: None,
1091 module_functions: None,
1092 module_state: None,
1093 local_slots,
1094 local_scope_base: self.env.scope_depth().saturating_sub(1),
1095 local_scope_depth: 0,
1096 });
1097 Ok(())
1098 }
1099
1100 pub(crate) fn child_vm(&self) -> Vm {
1103 Vm {
1104 stack: Vec::with_capacity(64),
1105 env: self.env.clone(),
1106 output: String::new(),
1107 builtins: Arc::clone(&self.builtins),
1108 async_builtins: Arc::clone(&self.async_builtins),
1109 capability_methods: Arc::clone(&self.capability_methods),
1110 builtin_metadata: Arc::clone(&self.builtin_metadata),
1111 builtins_by_id: Arc::clone(&self.builtins_by_id),
1112 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
1113 iterators: Vec::new(),
1114 frames: Vec::new(),
1115 exception_handlers: Vec::new(),
1116 spawned_tasks: BTreeMap::new(),
1117 process_exit_request: Arc::clone(&self.process_exit_request),
1118 sync_runtime: self.sync_runtime.clone(),
1119 shared_state_runtime: self.shared_state_runtime.clone(),
1120 worker_registry: self.worker_registry.clone(),
1121 daemon_registry: self.daemon_registry.clone(),
1122 trigger_registry: self.trigger_registry.clone(),
1123 session_runtime: self.session_runtime.clone(),
1124 tracing_runtime: self.tracing_runtime.clone(),
1125 execution_id: self.execution_id.clone(),
1126 owns_execution: false,
1127 agent_host_session_runtime: self.agent_host_session_runtime.clone(),
1128 connector_clients: self.connector_clients.clone(),
1129 inline_cache_sets: Vec::new(),
1130 inline_cache_set_by_chunk: HashMap::new(),
1131 pool_registry: self.pool_registry.clone(),
1132 llm_mock_context: self.llm_mock_context.clone(),
1133 package_snapshot_registry: self.package_snapshot_registry.clone(),
1134 wait_for_graph: self.wait_for_graph.clone(),
1135 held_sync_guards: Vec::new(),
1136 inherited_held_keys: Arc::new(Vec::new()),
1137 task_scopes: Vec::new(),
1138 task_counter: 0,
1139 runtime_context_counter: self.runtime_context_counter,
1140 runtime_context: self.runtime_context.clone(),
1141 deadlines: self.deadlines.clone(),
1142 execution_deadline: self.execution_deadline.fork(),
1143 breakpoints: BTreeMap::new(),
1144 function_breakpoints: std::collections::BTreeSet::new(),
1145 pending_function_bp: None,
1146 step_mode: false,
1147 step_frame_depth: 0,
1148 stopped: false,
1149 last_line: 0,
1150 source_dir: self.source_dir.clone(),
1151 package_execution_guard: self.package_execution_guard.clone(),
1152 imported_paths: Vec::new(),
1153 deferred_cyclic_imports: Vec::new(),
1154 module_cache: Arc::clone(&self.module_cache),
1155 prepared_module_cache: self.prepared_module_cache.clone(),
1156 prepared_module_validation: self.prepared_module_validation.clone(),
1157 module_provenance: self.module_provenance,
1158 module_phase_recorder: self.module_phase_recorder.clone(),
1159 lazy_callable_modules: Arc::clone(&self.lazy_callable_modules),
1160 source_cache: Arc::clone(&self.source_cache),
1161 graph_link_table: self.graph_link_table.clone(),
1162 linked_program_repository: self.linked_program_repository.clone(),
1163 source_file: self.source_file.clone(),
1164 source_text: self.source_text.clone(),
1165 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
1166 flight_recorder: self.flight_recorder.clone(),
1167 flight_recorder_max_events: None,
1168 bridge: self.bridge.clone(),
1169 denied_builtins: Arc::clone(&self.denied_builtins),
1170 cancel_token: self.cancel_token.clone(),
1171 interrupt_signal_token: self.interrupt_signal_token.clone(),
1172 cancel_grace_instructions_remaining: None,
1173 interrupt_handlers: Vec::new(),
1174 next_interrupt_handle: 1,
1175 pending_interrupt_signal: None,
1176 interrupted: self.interrupted,
1177 dispatching_interrupt: false,
1178 interrupt_handler_deadline: None,
1179 error_stack_trace: Vec::new(),
1180 yield_sender: None,
1181 project_root: self.project_root.clone(),
1182 globals: Arc::clone(&self.globals),
1183 root_harness: self.root_harness.clone(),
1184 runtime_effects: crate::orchestration::RuntimeEffectState::with_shared_recorder(
1185 Arc::clone(&self.runtime_effects.recorder),
1186 ),
1187 debug_hook: None,
1188 runtime_limits: self.runtime_limits,
1189 }
1190 }
1191
1192 pub(crate) fn child_vm_for_host(&self) -> Vm {
1195 self.child_vm()
1196 }
1197
1198 pub(crate) fn interrupt_sources(
1203 &self,
1204 ) -> (
1205 Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
1206 Option<std::time::Instant>,
1207 ) {
1208 let scope_deadline = self.deadlines.last().map(|(deadline, _)| *deadline);
1209 let deadline = match (scope_deadline, self.interrupt_handler_deadline) {
1210 (Some(scope), Some(interrupt)) => Some(scope.min(interrupt)),
1211 (scope, interrupt) => scope.or(interrupt),
1212 };
1213 (self.cancel_token.clone(), deadline)
1214 }
1215
1216 pub(crate) fn request_process_exit(&self, code: i32) {
1217 self.process_exit_request.request(code);
1218 }
1219
1220 pub(crate) fn requested_process_exit(&self) -> Option<i32> {
1221 self.process_exit_request.code()
1222 }
1223
1224 pub(crate) fn cancel_spawned_tasks(&mut self) {
1228 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
1229 task.cancel_token
1230 .store(true, std::sync::atomic::Ordering::SeqCst);
1231 task.handle.abort();
1232 }
1233 }
1234
1235 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
1238 let dir = crate::stdlib::process::normalize_context_path(dir);
1239 self.source_dir = Some(dir.clone());
1240 crate::stdlib::set_thread_source_dir(&dir);
1241 if self.project_root.is_none() {
1243 self.project_root = crate::stdlib::process::find_project_root(&dir);
1244 }
1245 }
1246
1247 pub fn set_project_root(&mut self, root: &std::path::Path) {
1250 self.project_root = Some(root.to_path_buf());
1251 }
1252
1253 pub(crate) fn explicit_project_root(&self) -> Option<&std::path::Path> {
1256 self.project_root.as_deref()
1257 }
1258
1259 pub fn project_root(&self) -> Option<&std::path::Path> {
1261 self.project_root.as_deref().or(self.source_dir.as_deref())
1262 }
1263
1264 pub fn set_global(&mut self, name: &str, value: VmValue) {
1267 Arc::make_mut(&mut self.globals).insert(crate::value::intern_key(name), value);
1268 }
1269
1270 pub fn global(&self, name: &str) -> Option<&VmValue> {
1272 self.globals.get(name)
1273 }
1274
1275 pub fn set_harness(&mut self, harness: crate::harness::Harness) {
1279 self.root_harness = Some(harness.into_vm_value());
1280 }
1281
1282 pub fn set_connector_clients(&mut self, clients: crate::connectors::VmConnectorClients) {
1284 self.connector_clients = Arc::new(clients);
1285 }
1286
1287 pub(crate) fn harness(&self) -> Option<&crate::harness::VmHarness> {
1288 match self.root_harness.as_ref() {
1289 Some(VmValue::Harness(handle)) => Some(handle),
1290 _ => None,
1291 }
1292 }
1293
1294 pub fn root_harness_value(&self) -> Option<VmValue> {
1297 self.root_harness.clone()
1298 }
1299
1300 pub fn output(&self) -> &str {
1302 &self.output
1303 }
1304
1305 pub fn take_output(&mut self) -> String {
1309 std::mem::take(&mut self.output)
1310 }
1311
1312 pub fn append_output(&mut self, text: &str) {
1316 self.output.push_str(text);
1317 }
1318
1319 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
1320 self.stack.pop().ok_or(VmError::StackUnderflow)
1321 }
1322
1323 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
1324 self.stack.last().ok_or(VmError::StackUnderflow)
1325 }
1326
1327 pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
1328 match c {
1329 Constant::String(s) => Ok(s.as_str()),
1330 _ => Err(VmError::TypeError("expected string constant".into())),
1331 }
1332 }
1333
1334 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
1335 let depth = self.env.scope_depth();
1336 self.held_sync_guards
1337 .retain(|guard| guard.env_scope_depth < depth);
1338 self.cancel_task_scopes_where(|s| s.env_scope_depth >= depth);
1341 }
1342
1343 pub(crate) fn release_sync_guards_after_unwind(
1344 &mut self,
1345 frame_depth: usize,
1346 env_scope_depth: usize,
1347 ) {
1348 self.held_sync_guards.retain(|guard| {
1349 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
1350 });
1351 self.cancel_task_scopes_where(|s| {
1354 !(s.frame_depth <= frame_depth && s.env_scope_depth <= env_scope_depth)
1355 });
1356 }
1357
1358 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
1359 self.held_sync_guards
1360 .retain(|guard| guard.frame_depth != frame_depth);
1361 self.cancel_task_scopes_where(|s| s.frame_depth == frame_depth);
1364 }
1365
1366 pub(crate) fn adopt_sync_permit_for_current_scope(
1367 &mut self,
1368 permit: crate::value::VmSyncPermitHandle,
1369 ) {
1370 if permit.is_released()
1371 || self
1372 .held_sync_guards
1373 .iter()
1374 .any(|guard| guard._permit.same_lease(&permit))
1375 {
1376 return;
1377 }
1378 self.held_sync_guards
1379 .push(crate::synchronization::VmSyncHeldGuard {
1380 _permit: permit,
1381 frame_depth: self.frames.len(),
1382 env_scope_depth: self.env.scope_depth(),
1383 });
1384 }
1385
1386 pub(crate) fn deregister_task_from_scopes(&mut self, id: &str) {
1389 for scope in &mut self.task_scopes {
1390 scope.task_ids.retain(|t| t != id);
1391 }
1392 }
1393
1394 fn cancel_task_scopes_where<F: Fn(&TaskScope) -> bool>(&mut self, doomed: F) {
1397 let mut i = 0;
1398 while i < self.task_scopes.len() {
1399 if doomed(&self.task_scopes[i]) {
1400 let scope = self.task_scopes.remove(i);
1401 for id in &scope.task_ids {
1402 if let Some(task) = self.spawned_tasks.remove(id) {
1403 task.cancel_token
1404 .store(true, std::sync::atomic::Ordering::SeqCst);
1405 task.handle.abort();
1406 }
1407 }
1408 } else {
1409 i += 1;
1410 }
1411 }
1412 }
1413
1414 pub(crate) fn held_permits_for(&self, kind: &str, key: &str) -> u32 {
1418 let own: u32 = self
1419 .held_sync_guards
1420 .iter()
1421 .filter(|guard| {
1422 !guard._permit.is_released()
1423 && guard._permit.kind() == kind
1424 && guard._permit.key() == key
1425 })
1426 .map(|guard| guard._permit.permits())
1427 .sum();
1428 let inherited: u32 = self
1429 .inherited_held_keys
1430 .iter()
1431 .filter(|held| held.kind == kind && held.key == key)
1432 .map(|held| held.permits)
1433 .sum();
1434 own + inherited
1435 }
1436
1437 pub(crate) fn combined_held_keys(&self) -> Vec<crate::synchronization::VmSyncHeldKey> {
1440 let mut keys: Vec<crate::synchronization::VmSyncHeldKey> = self
1441 .held_sync_guards
1442 .iter()
1443 .filter_map(|guard| crate::synchronization::VmSyncHeldKey::from_permit(&guard._permit))
1444 .collect();
1445 keys.extend(self.inherited_held_keys.iter().cloned());
1446 keys
1447 }
1448
1449 pub(crate) fn child_vm_inline(&self) -> Vm {
1455 let mut child = self.child_vm();
1456 child.inherited_held_keys = Arc::new(self.combined_held_keys());
1457 child.execution_deadline = Arc::clone(&self.execution_deadline);
1458 child
1459 }
1460}
1461
1462impl Drop for Vm {
1463 fn drop(&mut self) {
1464 if let Some(coverage) = self.coverage.take() {
1465 crate::coverage::merge_into_global(coverage);
1466 }
1467 self.cancel_spawned_tasks();
1468 }
1469}
1470
1471impl Default for Vm {
1472 fn default() -> Self {
1473 Self::new()
1474 }
1475}
1476
1477#[cfg(test)]
1478#[path = "state_tests.rs"]
1479mod tests;