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) agent_host_session_runtime:
319 Arc<crate::llm::agent_session_host::AgentHostSessionRuntime>,
320 pub(crate) connector_clients: Arc<crate::connectors::VmConnectorClients>,
324 pub(crate) inline_cache_sets: Vec<Vec<crate::chunk::InlineCacheEntry>>,
328 pub(crate) inline_cache_set_by_chunk: HashMap<u64, usize>,
329 pub(crate) pool_registry: Arc<crate::stdlib::pool::PoolRegistry>,
331 pub(crate) llm_mock_context: crate::llm::mock::LlmMockContext,
333 pub(crate) package_snapshot_registry: Arc<crate::stdlib::PackageSnapshotRegistry>,
337 pub(crate) wait_for_graph: Arc<crate::wait_for_graph::VmWaitForGraph>,
339 pub(crate) held_sync_guards: Vec<crate::synchronization::VmSyncHeldGuard>,
341 pub(crate) inherited_held_keys: Arc<Vec<crate::synchronization::VmSyncHeldKey>>,
349 pub(crate) task_scopes: Vec<TaskScope>,
355 pub(crate) task_counter: u64,
357 pub(crate) runtime_context_counter: u64,
359 pub(crate) runtime_context: crate::runtime_context::RuntimeContext,
361 pub(crate) deadlines: Vec<(Instant, usize)>,
363 pub(crate) execution_deadline: Arc<ExecutionDeadlineState>,
365 pub(crate) breakpoints: BTreeMap<String, std::collections::BTreeSet<usize>>,
370 pub(crate) function_breakpoints: std::collections::BTreeSet<String>,
376 pub(crate) pending_function_bp: Option<String>,
381 pub(crate) step_mode: bool,
383 pub(crate) step_frame_depth: usize,
385 pub(crate) stopped: bool,
387 pub(crate) last_line: usize,
389 pub(crate) source_dir: Option<std::path::PathBuf>,
391 pub(crate) package_execution_guard:
393 Option<Arc<harn_modules::package_execution::PackageExecutionGuard>>,
394 pub(crate) imported_paths: Vec<std::path::PathBuf>,
396 pub(crate) deferred_cyclic_imports: Vec<super::modules::DeferredCyclicImport>,
400 pub(crate) module_cache: ModuleCache,
402 pub(crate) prepared_module_cache: crate::PreparedModuleCache,
405 pub(crate) prepared_module_validation: crate::prepared_module::PreparedModuleValidation,
407 pub(crate) module_provenance: crate::module_artifact::ModuleProvenance,
410 pub(crate) module_phase_recorder: Option<super::ModulePhaseRecorder>,
412 pub(crate) lazy_callable_modules: LazyCallableModuleCache,
416 pub(crate) source_cache: Arc<BTreeMap<std::path::PathBuf, Arc<str>>>,
420 pub(crate) graph_link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
425 pub(crate) linked_program_repository:
429 Option<Arc<crate::linked_program::LinkedProgramRepository>>,
430 pub(crate) source_file: Option<String>,
432 pub(crate) source_text: Option<String>,
434 pub(crate) coverage: Option<crate::coverage::Coverage>,
437 pub(crate) bridge: Option<Arc<crate::bridge::HostBridge>>,
439 pub(crate) denied_builtins: Arc<HashSet<String>>,
441 pub(crate) cancel_token: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
443 pub(crate) interrupt_signal_token: Option<std::sync::Arc<std::sync::Mutex<Option<String>>>>,
444 pub(crate) cancel_grace_instructions_remaining: Option<usize>,
449 pub(crate) interrupt_handlers: Vec<InterruptHandler>,
451 pub(crate) next_interrupt_handle: i64,
452 pub(crate) pending_interrupt_signal: Option<String>,
453 pub(crate) interrupted: bool,
454 pub(crate) dispatching_interrupt: bool,
455 pub(crate) interrupt_handler_deadline: Option<Instant>,
456 pub(crate) error_stack_trace: Vec<(String, usize, usize, Option<String>)>,
458 pub(crate) yield_sender: Option<tokio::sync::mpsc::Sender<Result<VmValue, VmError>>>,
461 pub(crate) project_root: Option<std::path::PathBuf>,
464 pub(crate) globals: Arc<crate::value::DictMap>,
467 pub(crate) root_harness: Option<VmValue>,
472 pub(crate) runtime_effects: crate::orchestration::RuntimeEffectState,
474 pub(crate) debug_hook: Option<parking_lot::Mutex<Box<DebugHook>>>,
476 pub(crate) runtime_limits: RuntimeLimits,
478}
479
480#[derive(Clone)]
488pub struct VmBaseline {
489 builtins: Arc<BTreeMap<String, VmBuiltinFn>>,
490 async_builtins: Arc<BTreeMap<String, VmAsyncBuiltinFn>>,
491 capability_methods:
492 Arc<BTreeMap<harn_builtin_meta::CapabilityId, BTreeMap<String, VmBuiltinDispatch>>>,
493 builtin_metadata: Arc<BTreeMap<String, VmBuiltinMetadata>>,
494 builtins_by_id: Arc<HashMap<BuiltinId, VmBuiltinEntry>>,
495 builtin_id_collisions: Arc<HashSet<BuiltinId>>,
496 source_dir: Option<std::path::PathBuf>,
497 source_file: Option<String>,
498 source_text: Option<String>,
499 project_root: Option<std::path::PathBuf>,
500 globals: Arc<crate::value::DictMap>,
501 root_harness: Option<VmValue>,
502 denied_builtins: Arc<HashSet<String>>,
503 prepared_module_cache: crate::PreparedModuleCache,
504 module_provenance: crate::module_artifact::ModuleProvenance,
505 graph_link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
508 linked_program_repository: Option<Arc<crate::linked_program::LinkedProgramRepository>>,
509 runtime_limits: RuntimeLimits,
510}
511
512impl VmBaseline {
513 pub fn from_vm(vm: &Vm) -> Self {
514 Self {
515 builtins: Arc::clone(&vm.builtins),
516 async_builtins: Arc::clone(&vm.async_builtins),
517 capability_methods: Arc::clone(&vm.capability_methods),
518 builtin_metadata: Arc::clone(&vm.builtin_metadata),
519 builtins_by_id: Arc::clone(&vm.builtins_by_id),
520 builtin_id_collisions: Arc::clone(&vm.builtin_id_collisions),
521 source_dir: vm.source_dir.clone(),
522 source_file: vm.source_file.clone(),
523 source_text: vm.source_text.clone(),
524 project_root: vm.project_root.clone(),
525 globals: Arc::clone(&vm.globals),
526 root_harness: vm.root_harness.clone(),
527 denied_builtins: Arc::clone(&vm.denied_builtins),
528 prepared_module_cache: vm.prepared_module_cache.clone(),
529 module_provenance: vm.module_provenance,
530 graph_link_table: vm.graph_link_table.clone(),
531 linked_program_repository: vm.linked_program_repository.clone(),
532 runtime_limits: vm.runtime_limits,
533 }
534 }
535
536 pub fn instantiate(&self) -> Vm {
537 crate::initialize_runtime_assets();
538 let mut source_cache = BTreeMap::new();
539 if let (Some(file), Some(text)) = (&self.source_file, &self.source_text) {
540 source_cache.insert(std::path::PathBuf::from(file), Arc::from(text.as_str()));
541 }
542 if let Some(dir) = &self.source_dir {
543 crate::stdlib::set_thread_source_dir(dir);
544 }
545
546 let mut vm = Vm {
547 stack: Vec::with_capacity(256),
548 env: VmEnv::new(),
549 output: String::new(),
550 builtins: Arc::clone(&self.builtins),
551 async_builtins: Arc::clone(&self.async_builtins),
552 capability_methods: Arc::clone(&self.capability_methods),
553 builtin_metadata: Arc::clone(&self.builtin_metadata),
554 builtins_by_id: Arc::clone(&self.builtins_by_id),
555 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
556 iterators: Vec::new(),
557 frames: Vec::new(),
558 exception_handlers: Vec::new(),
559 spawned_tasks: BTreeMap::new(),
560 process_exit_request: Arc::new(ProcessExitRequest::new()),
561 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
562 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
563 worker_registry: crate::stdlib::agents::agents_workers::active_worker_registry(),
564 daemon_registry: crate::stdlib::agents_daemon::active_daemon_registry(),
565 trigger_registry: crate::triggers::registry::active_trigger_registry(),
566 session_runtime: crate::agent_sessions::active_session_runtime(),
567 tracing_runtime: crate::tracing::active_tracing_runtime(),
568 agent_host_session_runtime:
569 crate::llm::agent_session_host::active_agent_host_session_runtime(),
570 connector_clients: Arc::new(crate::connectors::VmConnectorClients::default()),
571 inline_cache_sets: Vec::new(),
572 inline_cache_set_by_chunk: HashMap::new(),
573 pool_registry: crate::stdlib::pool::new_pool_registry(),
574 llm_mock_context: crate::llm::mock::LlmMockContext::for_new_vm(),
575 package_snapshot_registry: Arc::new(Default::default()),
576 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
577 held_sync_guards: Vec::new(),
578 inherited_held_keys: Arc::new(Vec::new()),
579 task_scopes: Vec::new(),
580 task_counter: 0,
581 runtime_context_counter: 0,
582 runtime_context: crate::runtime_context::RuntimeContext::root(),
583 deadlines: Vec::new(),
584 execution_deadline: super::execution::new_execution_deadline_state(None),
585 breakpoints: BTreeMap::new(),
586 function_breakpoints: std::collections::BTreeSet::new(),
587 pending_function_bp: None,
588 step_mode: false,
589 step_frame_depth: 0,
590 stopped: false,
591 last_line: 0,
592 source_dir: self.source_dir.clone(),
593 package_execution_guard: None,
594 imported_paths: Vec::new(),
595 deferred_cyclic_imports: Vec::new(),
596 module_cache: Arc::new(BTreeMap::new()),
597 prepared_module_cache: self.prepared_module_cache.clone(),
598 prepared_module_validation: crate::prepared_module::PreparedModuleValidation::default(),
599 module_provenance: self.module_provenance,
600 module_phase_recorder: None,
601 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
602 source_cache: Arc::new(source_cache),
603 graph_link_table: self.graph_link_table.clone(),
604 linked_program_repository: self.linked_program_repository.clone(),
605 source_file: self.source_file.clone(),
606 source_text: self.source_text.clone(),
607 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
608 bridge: None,
609 denied_builtins: Arc::clone(&self.denied_builtins),
610 cancel_token: None,
611 interrupt_signal_token: None,
612 cancel_grace_instructions_remaining: None,
613 interrupt_handlers: Vec::new(),
614 next_interrupt_handle: 1,
615 pending_interrupt_signal: None,
616 interrupted: false,
617 dispatching_interrupt: false,
618 interrupt_handler_deadline: None,
619 error_stack_trace: Vec::new(),
620 yield_sender: None,
621 project_root: self.project_root.clone(),
622 globals: Arc::clone(&self.globals),
623 root_harness: self.root_harness.clone(),
624 runtime_effects: crate::orchestration::RuntimeEffectState::fresh(),
625 debug_hook: None,
626 runtime_limits: self.runtime_limits,
627 };
628
629 crate::stdlib::rebind_execution_state_builtins(&mut vm);
630 vm
631 }
632}
633
634impl Vm {
635 pub(crate) fn ensure_execution_available(&self) -> Result<(), VmError> {
636 if self.execution_deadline.is_abandoned() {
637 return Err(VmError::AbandonedExecution);
638 }
639 Ok(())
640 }
641
642 pub(crate) fn fresh_local_slots(chunk: &Chunk) -> Vec<LocalSlot> {
643 chunk
644 .local_slots
645 .iter()
646 .map(|_| LocalSlot {
647 value: VmValue::Nil,
648 initialized: false,
649 synced: false,
650 })
651 .collect()
652 }
653
654 pub(crate) fn bind_param_slots(
655 slots: &mut [LocalSlot],
656 func: &crate::chunk::CompiledFunction,
657 args: &[VmValue],
658 synced: bool,
659 ) {
660 Self::bind_param_slots_args(slots, func, &super::CallArgs::Slice(args), synced);
661 }
662
663 pub(crate) fn bind_param_slots_args(
664 slots: &mut [LocalSlot],
665 func: &crate::chunk::CompiledFunction,
666 args: &super::CallArgs<'_>,
667 synced: bool,
668 ) {
669 let param_count = func.params.len();
670 for (i, _param) in func.params.iter().enumerate() {
671 if i >= slots.len() {
672 break;
673 }
674 if func.has_rest_param && i == param_count - 1 {
675 let rest_args = args.to_vec_from(i);
676 slots[i].value = VmValue::List(std::sync::Arc::new(rest_args));
677 slots[i].initialized = true;
678 slots[i].synced = synced;
679 } else if let Some(arg) = args.get(i) {
680 slots[i].value = arg.clone();
681 slots[i].initialized = true;
682 slots[i].synced = synced;
683 }
684 }
685 }
686
687 pub(crate) fn visible_variables(&self) -> crate::value::DictMap {
688 let mut vars = self.env.all_variables();
689 let Some(frame) = self.frames.last() else {
690 return vars;
691 };
692 for (slot, info) in frame.local_slots.iter().zip(frame.chunk.local_slots.iter()) {
693 if slot.initialized && info.scope_depth <= frame.local_scope_depth {
694 vars.insert(crate::value::intern_key(&info.name), slot.value.clone());
695 }
696 }
697 vars
698 }
699
700 pub(crate) fn sync_current_frame_locals_to_env(&mut self) {
701 let frames = &mut self.frames;
702 let env = &mut self.env;
703 let Some(frame) = frames.last_mut() else {
704 return;
705 };
706 let local_scope_base = frame.local_scope_base;
707 let local_scope_depth = frame.local_scope_depth;
708 for (slot, info) in frame
709 .local_slots
710 .iter_mut()
711 .zip(frame.chunk.local_slots.iter())
712 {
713 if slot.initialized && !slot.synced && info.scope_depth <= local_scope_depth {
714 slot.synced = true;
715 let scope_idx = local_scope_base + info.scope_depth;
716 while env.scopes.len() <= scope_idx {
717 env.push_scope();
718 }
719 Arc::make_mut(&mut env.scopes[scope_idx].vars).insert(
723 info.name.clone(),
724 crate::value::Binding::Value {
725 value: slot.value.clone(),
726 mutable: info.mutable,
727 },
728 );
729 }
730 }
731 }
732
733 pub(crate) fn closure_call_env_for_current_frame(
734 &self,
735 closure: &crate::value::VmClosure,
736 ) -> VmEnv {
737 if closure.module_state().is_some() {
738 return closure.env.cloned_for_call();
739 }
740 let call_env = Self::closure_call_env(&self.env, closure);
741 if !closure.func.chunk.references_outer_names {
746 return call_env;
747 }
748 let mut call_env = call_env;
749 let Some(frame) = self.frames.last() else {
750 return call_env;
751 };
752 for (slot, info) in frame
753 .local_slots
754 .iter()
755 .zip(frame.chunk.local_slots.iter())
756 .filter(|(slot, info)| slot.initialized && info.scope_depth <= frame.local_scope_depth)
757 {
758 if matches!(slot.value, VmValue::Closure(_)) && !call_env.contains(&info.name) {
759 let _ = call_env.define(&info.name, slot.value.clone(), info.mutable);
760 }
761 }
762 call_env
763 }
764
765 pub(crate) fn active_local_slot_value(&self, name: &str) -> Option<VmValue> {
766 let frame = self.frames.last()?;
767 let idx = self.active_local_slot_index(name)?;
768 frame.local_slots.get(idx).map(|slot| slot.value.clone())
769 }
770
771 pub(crate) fn active_local_slot_index(&self, name: &str) -> Option<usize> {
776 let frame = self.frames.last()?;
777 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
778 if info.name == name && info.scope_depth <= frame.local_scope_depth {
779 if let Some(slot) = frame.local_slots.get(idx) {
780 if slot.initialized {
781 return Some(idx);
782 }
783 }
784 }
785 }
786 None
787 }
788
789 pub(crate) fn assign_active_local_slot(
790 &mut self,
791 name: &str,
792 value: VmValue,
793 debug: bool,
794 ) -> Result<bool, VmError> {
795 let Some(frame) = self.frames.last_mut() else {
796 return Ok(false);
797 };
798 for (idx, info) in frame.chunk.local_slots.iter().enumerate().rev() {
799 if info.name == name && info.scope_depth <= frame.local_scope_depth {
800 if !debug && !info.mutable {
801 return Err(VmError::ImmutableAssignment(name.to_string()));
802 }
803 if let Some(slot) = frame.local_slots.get_mut(idx) {
804 crate::value::recursion::dismantle(std::mem::replace(&mut slot.value, value));
805 slot.initialized = true;
806 slot.synced = false;
807 return Ok(true);
808 }
809 }
810 }
811 Ok(false)
812 }
813
814 pub fn new() -> Self {
815 crate::initialize_runtime_assets();
816 Self {
817 stack: Vec::with_capacity(256),
818 env: VmEnv::new(),
819 output: String::new(),
820 builtins: Arc::new(BTreeMap::new()),
821 async_builtins: Arc::new(BTreeMap::new()),
822 capability_methods: Arc::new(BTreeMap::new()),
823 builtin_metadata: Arc::new(BTreeMap::new()),
824 builtins_by_id: Arc::new(HashMap::new()),
825 builtin_id_collisions: Arc::new(HashSet::new()),
826 iterators: Vec::new(),
827 frames: Vec::new(),
828 exception_handlers: Vec::new(),
829 spawned_tasks: BTreeMap::new(),
830 process_exit_request: Arc::new(ProcessExitRequest::new()),
831 sync_runtime: Arc::new(crate::synchronization::VmSyncRuntime::new()),
832 shared_state_runtime: Arc::new(crate::shared_state::VmSharedStateRuntime::new()),
833 worker_registry: crate::stdlib::agents::agents_workers::active_worker_registry(),
834 daemon_registry: crate::stdlib::agents_daemon::active_daemon_registry(),
835 trigger_registry: crate::triggers::registry::active_trigger_registry(),
836 session_runtime: crate::agent_sessions::active_session_runtime(),
837 tracing_runtime: crate::tracing::active_tracing_runtime(),
838 agent_host_session_runtime:
839 crate::llm::agent_session_host::active_agent_host_session_runtime(),
840 connector_clients: Arc::new(crate::connectors::VmConnectorClients::default()),
841 inline_cache_sets: Vec::new(),
842 inline_cache_set_by_chunk: HashMap::new(),
843 pool_registry: crate::stdlib::pool::new_pool_registry(),
844 llm_mock_context: crate::llm::mock::LlmMockContext::for_new_vm(),
845 package_snapshot_registry: Arc::new(Default::default()),
846 wait_for_graph: Arc::new(crate::wait_for_graph::VmWaitForGraph::new()),
847 held_sync_guards: Vec::new(),
848 inherited_held_keys: Arc::new(Vec::new()),
849 task_scopes: Vec::new(),
850 task_counter: 0,
851 runtime_context_counter: 0,
852 runtime_context: crate::runtime_context::RuntimeContext::root(),
853 deadlines: Vec::new(),
854 execution_deadline: super::execution::new_execution_deadline_state(None),
855 breakpoints: BTreeMap::new(),
856 function_breakpoints: std::collections::BTreeSet::new(),
857 pending_function_bp: None,
858 step_mode: false,
859 step_frame_depth: 0,
860 stopped: false,
861 last_line: 0,
862 source_dir: None,
863 package_execution_guard: None,
864 imported_paths: Vec::new(),
865 deferred_cyclic_imports: Vec::new(),
866 module_cache: Arc::new(BTreeMap::new()),
867 prepared_module_cache: crate::PreparedModuleCache::default(),
868 prepared_module_validation: crate::prepared_module::PreparedModuleValidation::default(),
869 module_provenance: crate::module_artifact::ModuleProvenance::User,
870 module_phase_recorder: None,
871 lazy_callable_modules: Arc::new(crate::value::VmMutex::new(BTreeMap::new())),
872 source_cache: Arc::new(BTreeMap::new()),
873 graph_link_table: None,
874 linked_program_repository: None,
875 source_file: None,
876 source_text: None,
877 coverage: crate::coverage::for_primary(None),
878 bridge: None,
879 denied_builtins: Arc::new(HashSet::new()),
880 cancel_token: None,
881 interrupt_signal_token: None,
882 cancel_grace_instructions_remaining: None,
883 interrupt_handlers: Vec::new(),
884 next_interrupt_handle: 1,
885 pending_interrupt_signal: None,
886 interrupted: false,
887 dispatching_interrupt: false,
888 interrupt_handler_deadline: None,
889 error_stack_trace: Vec::new(),
890 yield_sender: None,
891 project_root: None,
892 globals: Arc::new(crate::value::DictMap::new()),
893 root_harness: None,
894 runtime_effects: crate::orchestration::RuntimeEffectState::fresh(),
895 debug_hook: None,
896 runtime_limits: RuntimeLimits::default(),
897 }
898 }
899
900 pub fn baseline(&self) -> VmBaseline {
901 VmBaseline::from_vm(self)
902 }
903
904 pub fn executed_effects(&self) -> Vec<crate::orchestration::EffectRecord> {
906 self.runtime_effects.snapshot()
907 }
908
909 pub fn clear_executed_effects(&mut self) {
911 self.runtime_effects.clear();
912 }
913
914 pub(crate) fn record_capability_effects(
915 &mut self,
916 capability: harn_builtin_meta::CapabilityId,
917 method: &str,
918 args: &[VmValue],
919 ) {
920 self.runtime_effects
921 .record_capability(capability, method, args);
922 }
923
924 pub(crate) fn record_builtin_contract_effects(&mut self, name: &str, args: &[VmValue]) {
925 let Some(entry) = crate::stdlib::recorded_effect_builtin_manifest_entry(name) else {
926 return;
927 };
928 self.record_builtin_effect_specs(entry.contract.effects, args);
929 }
930
931 pub(crate) fn record_builtin_effect_specs(
932 &mut self,
933 specs: &'static [harn_builtin_meta::EffectSpec],
934 args: &[VmValue],
935 ) {
936 self.runtime_effects.record_specs(specs, args);
937 }
938
939 pub fn set_prepared_module_cache(&mut self, cache: crate::PreparedModuleCache) {
942 self.prepared_module_cache = cache;
943 self.prepared_module_validation =
944 crate::prepared_module::PreparedModuleValidation::default();
945 }
946
947 pub fn set_graph_link_table(
955 &mut self,
956 link_table: Option<Arc<crate::context_manifest::GraphLinkTable>>,
957 ) {
958 self.graph_link_table = link_table;
959 }
960
961 pub fn set_linked_program_runtime(
965 &mut self,
966 runtime: &crate::linked_program::LinkedProgramRuntime,
967 ) {
968 self.linked_program_repository = Some(Arc::clone(&runtime.repository));
969 self.graph_link_table = None;
970 }
971
972 pub fn runtime_limits(&self) -> RuntimeLimits {
974 self.runtime_limits
975 }
976
977 pub fn runtime_limit_report(&self) -> crate::RuntimeLimitsReport {
979 self.runtime_limits.report()
980 }
981
982 #[inline]
996 pub(crate) fn debugger_attached(&self) -> bool {
997 self.debug_hook.is_some()
998 || !self.breakpoints.is_empty()
999 || !self.function_breakpoints.is_empty()
1000 }
1001
1002 pub fn set_bridge(&mut self, bridge: Arc<crate::bridge::HostBridge>) {
1004 self.bridge = Some(bridge);
1005 }
1006
1007 pub fn set_denied_builtins(&mut self, mut denied: HashSet<String>) {
1010 let denied_canonical_names = denied
1014 .iter()
1015 .filter_map(|name| crate::stdlib::builtin_manifest_entry(name))
1016 .map(|entry| entry.canonical_name)
1017 .collect::<HashSet<_>>();
1018 if !denied_canonical_names.is_empty() {
1019 denied.extend(
1020 crate::stdlib::all_builtin_manifest()
1021 .iter()
1022 .filter(|entry| denied_canonical_names.contains(entry.canonical_name))
1023 .map(|entry| entry.name.to_string()),
1024 );
1025 }
1026 self.denied_builtins = Arc::new(denied);
1027 }
1028
1029 pub fn set_source_info(&mut self, file: &str, text: &str) {
1031 self.source_file = Some(file.to_string());
1032 self.source_text = Some(text.to_string());
1033 if let Some(cov) = self.coverage.as_mut() {
1034 cov.set_primary_file(file);
1035 }
1036 Arc::make_mut(&mut self.source_cache)
1037 .insert(std::path::PathBuf::from(file), Arc::from(text));
1038 }
1039
1040 pub fn start(&mut self, chunk: &Chunk) -> Result<(), VmError> {
1042 self.ensure_execution_available()?;
1043 let debugger = self.debugger_attached();
1050 let initial_env = if debugger {
1051 Some(self.env.clone())
1052 } else {
1053 None
1054 };
1055 let initial_local_slots = if debugger {
1056 Some(Self::fresh_local_slots(chunk))
1057 } else {
1058 None
1059 };
1060 let chunk = Arc::new(chunk.clone());
1061 let local_slots = Self::fresh_local_slots(&chunk);
1062 let inline_cache_set = self.inline_cache_set_index_for_chunk(&chunk);
1063 self.frames.push(CallFrame {
1064 chunk,
1065 inline_cache_set,
1066 ip: 0,
1067 stack_base: self.stack.len(),
1068 saved_env: self.env.clone(),
1069 initial_env,
1070 initial_local_slots,
1071 saved_iterator_depth: self.iterators.len(),
1072 fn_name: crate::value::HarnStr::new(),
1073 argc: 0,
1074 saved_source_dir: None,
1075 module_functions: None,
1076 module_state: None,
1077 local_slots,
1078 local_scope_base: self.env.scope_depth().saturating_sub(1),
1079 local_scope_depth: 0,
1080 });
1081 Ok(())
1082 }
1083
1084 pub(crate) fn child_vm(&self) -> Vm {
1087 Vm {
1088 stack: Vec::with_capacity(64),
1089 env: self.env.clone(),
1090 output: String::new(),
1091 builtins: Arc::clone(&self.builtins),
1092 async_builtins: Arc::clone(&self.async_builtins),
1093 capability_methods: Arc::clone(&self.capability_methods),
1094 builtin_metadata: Arc::clone(&self.builtin_metadata),
1095 builtins_by_id: Arc::clone(&self.builtins_by_id),
1096 builtin_id_collisions: Arc::clone(&self.builtin_id_collisions),
1097 iterators: Vec::new(),
1098 frames: Vec::new(),
1099 exception_handlers: Vec::new(),
1100 spawned_tasks: BTreeMap::new(),
1101 process_exit_request: Arc::clone(&self.process_exit_request),
1102 sync_runtime: self.sync_runtime.clone(),
1103 shared_state_runtime: self.shared_state_runtime.clone(),
1104 worker_registry: self.worker_registry.clone(),
1105 daemon_registry: self.daemon_registry.clone(),
1106 trigger_registry: self.trigger_registry.clone(),
1107 session_runtime: self.session_runtime.clone(),
1108 tracing_runtime: self.tracing_runtime.clone(),
1109 agent_host_session_runtime: self.agent_host_session_runtime.clone(),
1110 connector_clients: self.connector_clients.clone(),
1111 inline_cache_sets: Vec::new(),
1112 inline_cache_set_by_chunk: HashMap::new(),
1113 pool_registry: self.pool_registry.clone(),
1114 llm_mock_context: self.llm_mock_context.clone(),
1115 package_snapshot_registry: self.package_snapshot_registry.clone(),
1116 wait_for_graph: self.wait_for_graph.clone(),
1117 held_sync_guards: Vec::new(),
1118 inherited_held_keys: Arc::new(Vec::new()),
1119 task_scopes: Vec::new(),
1120 task_counter: 0,
1121 runtime_context_counter: self.runtime_context_counter,
1122 runtime_context: self.runtime_context.clone(),
1123 deadlines: self.deadlines.clone(),
1124 execution_deadline: self.execution_deadline.fork(),
1125 breakpoints: BTreeMap::new(),
1126 function_breakpoints: std::collections::BTreeSet::new(),
1127 pending_function_bp: None,
1128 step_mode: false,
1129 step_frame_depth: 0,
1130 stopped: false,
1131 last_line: 0,
1132 source_dir: self.source_dir.clone(),
1133 package_execution_guard: self.package_execution_guard.clone(),
1134 imported_paths: Vec::new(),
1135 deferred_cyclic_imports: Vec::new(),
1136 module_cache: Arc::clone(&self.module_cache),
1137 prepared_module_cache: self.prepared_module_cache.clone(),
1138 prepared_module_validation: self.prepared_module_validation.clone(),
1139 module_provenance: self.module_provenance,
1140 module_phase_recorder: self.module_phase_recorder.clone(),
1141 lazy_callable_modules: Arc::clone(&self.lazy_callable_modules),
1142 source_cache: Arc::clone(&self.source_cache),
1143 graph_link_table: self.graph_link_table.clone(),
1144 linked_program_repository: self.linked_program_repository.clone(),
1145 source_file: self.source_file.clone(),
1146 source_text: self.source_text.clone(),
1147 coverage: crate::coverage::for_primary(self.source_file.as_deref()),
1148 bridge: self.bridge.clone(),
1149 denied_builtins: Arc::clone(&self.denied_builtins),
1150 cancel_token: self.cancel_token.clone(),
1151 interrupt_signal_token: self.interrupt_signal_token.clone(),
1152 cancel_grace_instructions_remaining: None,
1153 interrupt_handlers: Vec::new(),
1154 next_interrupt_handle: 1,
1155 pending_interrupt_signal: None,
1156 interrupted: self.interrupted,
1157 dispatching_interrupt: false,
1158 interrupt_handler_deadline: None,
1159 error_stack_trace: Vec::new(),
1160 yield_sender: None,
1161 project_root: self.project_root.clone(),
1162 globals: Arc::clone(&self.globals),
1163 root_harness: self.root_harness.clone(),
1164 runtime_effects: crate::orchestration::RuntimeEffectState::with_shared_recorder(
1165 Arc::clone(&self.runtime_effects.recorder),
1166 ),
1167 debug_hook: None,
1168 runtime_limits: self.runtime_limits,
1169 }
1170 }
1171
1172 pub(crate) fn child_vm_for_host(&self) -> Vm {
1175 self.child_vm()
1176 }
1177
1178 pub(crate) fn interrupt_sources(
1183 &self,
1184 ) -> (
1185 Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
1186 Option<std::time::Instant>,
1187 ) {
1188 let scope_deadline = self.deadlines.last().map(|(deadline, _)| *deadline);
1189 let deadline = match (scope_deadline, self.interrupt_handler_deadline) {
1190 (Some(scope), Some(interrupt)) => Some(scope.min(interrupt)),
1191 (scope, interrupt) => scope.or(interrupt),
1192 };
1193 (self.cancel_token.clone(), deadline)
1194 }
1195
1196 pub(crate) fn request_process_exit(&self, code: i32) {
1197 self.process_exit_request.request(code);
1198 }
1199
1200 pub(crate) fn requested_process_exit(&self) -> Option<i32> {
1201 self.process_exit_request.code()
1202 }
1203
1204 pub(crate) fn cancel_spawned_tasks(&mut self) {
1208 for (_, task) in std::mem::take(&mut self.spawned_tasks) {
1209 task.cancel_token
1210 .store(true, std::sync::atomic::Ordering::SeqCst);
1211 task.handle.abort();
1212 }
1213 }
1214
1215 pub fn set_source_dir(&mut self, dir: &std::path::Path) {
1218 let dir = crate::stdlib::process::normalize_context_path(dir);
1219 self.source_dir = Some(dir.clone());
1220 crate::stdlib::set_thread_source_dir(&dir);
1221 if self.project_root.is_none() {
1223 self.project_root = crate::stdlib::process::find_project_root(&dir);
1224 }
1225 }
1226
1227 pub fn set_project_root(&mut self, root: &std::path::Path) {
1230 self.project_root = Some(root.to_path_buf());
1231 }
1232
1233 pub(crate) fn explicit_project_root(&self) -> Option<&std::path::Path> {
1236 self.project_root.as_deref()
1237 }
1238
1239 pub fn project_root(&self) -> Option<&std::path::Path> {
1241 self.project_root.as_deref().or(self.source_dir.as_deref())
1242 }
1243
1244 pub fn set_global(&mut self, name: &str, value: VmValue) {
1247 Arc::make_mut(&mut self.globals).insert(crate::value::intern_key(name), value);
1248 }
1249
1250 pub fn global(&self, name: &str) -> Option<&VmValue> {
1252 self.globals.get(name)
1253 }
1254
1255 pub fn set_harness(&mut self, harness: crate::harness::Harness) {
1259 self.root_harness = Some(harness.into_vm_value());
1260 }
1261
1262 pub fn set_connector_clients(&mut self, clients: crate::connectors::VmConnectorClients) {
1264 self.connector_clients = Arc::new(clients);
1265 }
1266
1267 pub(crate) fn harness(&self) -> Option<&crate::harness::VmHarness> {
1268 match self.root_harness.as_ref() {
1269 Some(VmValue::Harness(handle)) => Some(handle),
1270 _ => None,
1271 }
1272 }
1273
1274 pub fn root_harness_value(&self) -> Option<VmValue> {
1277 self.root_harness.clone()
1278 }
1279
1280 pub fn output(&self) -> &str {
1282 &self.output
1283 }
1284
1285 pub fn take_output(&mut self) -> String {
1289 std::mem::take(&mut self.output)
1290 }
1291
1292 pub fn append_output(&mut self, text: &str) {
1296 self.output.push_str(text);
1297 }
1298
1299 pub(crate) fn pop(&mut self) -> Result<VmValue, VmError> {
1300 self.stack.pop().ok_or(VmError::StackUnderflow)
1301 }
1302
1303 pub(crate) fn peek(&self) -> Result<&VmValue, VmError> {
1304 self.stack.last().ok_or(VmError::StackUnderflow)
1305 }
1306
1307 pub(crate) fn const_str(c: &Constant) -> Result<&str, VmError> {
1308 match c {
1309 Constant::String(s) => Ok(s.as_str()),
1310 _ => Err(VmError::TypeError("expected string constant".into())),
1311 }
1312 }
1313
1314 pub(crate) fn release_sync_guards_for_current_scope(&mut self) {
1315 let depth = self.env.scope_depth();
1316 self.held_sync_guards
1317 .retain(|guard| guard.env_scope_depth < depth);
1318 self.cancel_task_scopes_where(|s| s.env_scope_depth >= depth);
1321 }
1322
1323 pub(crate) fn release_sync_guards_after_unwind(
1324 &mut self,
1325 frame_depth: usize,
1326 env_scope_depth: usize,
1327 ) {
1328 self.held_sync_guards.retain(|guard| {
1329 guard.frame_depth <= frame_depth && guard.env_scope_depth <= env_scope_depth
1330 });
1331 self.cancel_task_scopes_where(|s| {
1334 !(s.frame_depth <= frame_depth && s.env_scope_depth <= env_scope_depth)
1335 });
1336 }
1337
1338 pub(crate) fn release_sync_guards_for_frame(&mut self, frame_depth: usize) {
1339 self.held_sync_guards
1340 .retain(|guard| guard.frame_depth != frame_depth);
1341 self.cancel_task_scopes_where(|s| s.frame_depth == frame_depth);
1344 }
1345
1346 pub(crate) fn adopt_sync_permit_for_current_scope(
1347 &mut self,
1348 permit: crate::value::VmSyncPermitHandle,
1349 ) {
1350 if permit.is_released()
1351 || self
1352 .held_sync_guards
1353 .iter()
1354 .any(|guard| guard._permit.same_lease(&permit))
1355 {
1356 return;
1357 }
1358 self.held_sync_guards
1359 .push(crate::synchronization::VmSyncHeldGuard {
1360 _permit: permit,
1361 frame_depth: self.frames.len(),
1362 env_scope_depth: self.env.scope_depth(),
1363 });
1364 }
1365
1366 pub(crate) fn deregister_task_from_scopes(&mut self, id: &str) {
1369 for scope in &mut self.task_scopes {
1370 scope.task_ids.retain(|t| t != id);
1371 }
1372 }
1373
1374 fn cancel_task_scopes_where<F: Fn(&TaskScope) -> bool>(&mut self, doomed: F) {
1377 let mut i = 0;
1378 while i < self.task_scopes.len() {
1379 if doomed(&self.task_scopes[i]) {
1380 let scope = self.task_scopes.remove(i);
1381 for id in &scope.task_ids {
1382 if let Some(task) = self.spawned_tasks.remove(id) {
1383 task.cancel_token
1384 .store(true, std::sync::atomic::Ordering::SeqCst);
1385 task.handle.abort();
1386 }
1387 }
1388 } else {
1389 i += 1;
1390 }
1391 }
1392 }
1393
1394 pub(crate) fn held_permits_for(&self, kind: &str, key: &str) -> u32 {
1398 let own: u32 = self
1399 .held_sync_guards
1400 .iter()
1401 .filter(|guard| {
1402 !guard._permit.is_released()
1403 && guard._permit.kind() == kind
1404 && guard._permit.key() == key
1405 })
1406 .map(|guard| guard._permit.permits())
1407 .sum();
1408 let inherited: u32 = self
1409 .inherited_held_keys
1410 .iter()
1411 .filter(|held| held.kind == kind && held.key == key)
1412 .map(|held| held.permits)
1413 .sum();
1414 own + inherited
1415 }
1416
1417 pub(crate) fn combined_held_keys(&self) -> Vec<crate::synchronization::VmSyncHeldKey> {
1420 let mut keys: Vec<crate::synchronization::VmSyncHeldKey> = self
1421 .held_sync_guards
1422 .iter()
1423 .filter_map(|guard| crate::synchronization::VmSyncHeldKey::from_permit(&guard._permit))
1424 .collect();
1425 keys.extend(self.inherited_held_keys.iter().cloned());
1426 keys
1427 }
1428
1429 pub(crate) fn child_vm_inline(&self) -> Vm {
1435 let mut child = self.child_vm();
1436 child.inherited_held_keys = Arc::new(self.combined_held_keys());
1437 child.execution_deadline = Arc::clone(&self.execution_deadline);
1438 child
1439 }
1440}
1441
1442impl Drop for Vm {
1443 fn drop(&mut self) {
1444 if let Some(coverage) = self.coverage.take() {
1445 crate::coverage::merge_into_global(coverage);
1446 }
1447 self.cancel_spawned_tasks();
1448 }
1449}
1450
1451impl Default for Vm {
1452 fn default() -> Self {
1453 Self::new()
1454 }
1455}
1456
1457#[cfg(test)]
1458#[path = "state_tests.rs"]
1459mod tests;