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