forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallbacks.rs
More file actions
1803 lines (1718 loc) · 73.1 KB
/
Copy pathcallbacks.rs
File metadata and controls
1803 lines (1718 loc) · 73.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! VM callback bridges — connects the bytecode VM to a real `Runtime`.
//!
//! Three `ActorVmCallbacks`/`DistributedVmCallbacks` implementations, split
//! out of `runtime/mod.rs` (2026-08-02) since they're a cohesive, mostly
//! self-contained layer (built-in effect dispatch, heap alloc routing) with
//! no state of their own beyond a `Runtime` handle:
//! - [`RuntimeVmCallbacks`] — `Rc<RefCell<Runtime>>` handle, used by the
//! top-level VM (outside any scheduler-driven behavior): `main.rs`,
//! integration tests, `runtime/tests.rs`.
//! - `BytecodeRuntimeCallbacks` — raw `*mut Runtime` handle, used when the
//! runtime drives a behavior's bytecode from inside the scheduler
//! (`run_bytecode_at_offset` and friends in `runtime/mod.rs`, plus
//! `runtime/workflow.rs`).
//! - `BytecodeDistributedCallbacks` — same raw-pointer pattern, for the
//! `DistributedVmCallbacks` trait (`RSend`/`RAsk`/`Migrate`/`RSpawn`/
//! `Gossip` opcodes).
#[cfg(feature = "ai-runtime")]
use super::agent;
use super::cluster::NodeId;
use super::distributed::{send_distributed, spawn_on_node, ActorAddress};
use super::http_server::HttpServerState;
use super::Runtime;
#[cfg(feature = "ai-runtime")]
use nulang_ai::{LlmMessage, LlmRequest};
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
/// Bridges the standalone VM to a real `Runtime`.
///
/// Used in tests and in any context where bytecode should create real actors
/// and allocate on the current actor's heap.
pub struct RuntimeVmCallbacks {
runtime: Rc<RefCell<Runtime>>,
}
impl RuntimeVmCallbacks {
pub fn new(runtime: Rc<RefCell<Runtime>>) -> Self {
RuntimeVmCallbacks { runtime }
}
/// Allocate a fresh heap string via `self.alloc` (the current actor's
/// heap, or `Runtime::main_heap` outside any actor context) and copy
/// `s`'s bytes into it, null-terminated. Mirrors `VM::allocate_string`,
/// but through THIS callback's own (now-correct) allocator rather than
/// reaching into `Runtime.vm` — a separate, lazily-created VM instance
/// used only to run actor bytecode, whose heap is not the heap this
/// callback's caller (e.g. `main()`'s own top-level VM) can read back
/// from. Builtin effects that produce a NEW string (`Int.to_string`,
/// `Float.to_string`, JSON/LLM results, ...) must allocate through this
/// helper, not `rt.vm.allocate_string`.
fn alloc_string(&mut self, s: &str) -> crate::vm::Value {
let bytes = s.as_bytes();
match crate::vm::ActorVmCallbacks::alloc(
self,
bytes.len() + 1,
crate::runtime::heap::TypeTag::String,
) {
Some(ptr) => {
// SAFETY: `alloc` just returned a fresh allocation of
// exactly `bytes.len() + 1` bytes; writing `bytes.len()`
// payload bytes plus a trailing NUL fits exactly.
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, bytes.len());
*ptr.add(bytes.len()) = 0;
}
crate::vm::Value::ptr(ptr)
}
None => crate::vm::Value::nil(),
}
}
}
impl std::fmt::Debug for RuntimeVmCallbacks {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RuntimeVmCallbacks").finish_non_exhaustive()
}
}
impl crate::vm::ActorVmCallbacks for RuntimeVmCallbacks {
fn current_actor_id(&self) -> Option<u64> {
self.runtime.borrow().current_actor
}
fn alloc(&mut self, size: usize, type_tag: crate::runtime::heap::TypeTag) -> Option<*mut u8> {
let mut rt = self.runtime.borrow_mut();
if let Some(actor_id) = rt.current_actor {
if let Some(actor) = rt.actors.get_mut(&actor_id) {
return actor.heap.alloc(size, type_tag);
}
}
// No actor context (e.g. `main()`'s own top-level bytecode): fall
// back to the runtime's dedicated main heap rather than silently
// failing every allocation. See `Runtime::main_heap`'s doc comment.
rt.main_heap.alloc(size, type_tag)
}
// SAFETY: trait-impl signature is fixed; `ptr` always comes from the
// VM's own heap allocations (the current actor's ActorHeap, or the
// runtime's main heap when there is no current actor).
#[allow(clippy::not_unsafe_ptr_arg_deref)]
fn drop_ref(&mut self, ptr: *mut u8) {
let mut rt = self.runtime.borrow_mut();
if let Some(actor_id) = rt.current_actor {
if let Some(actor) = rt.actors.get_mut(&actor_id) {
// Route through ORCA so objects with outstanding foreign
// references are deferred instead of freed out from under
// other actors.
unsafe {
actor.orca_gc.drop_local_ref(&mut actor.heap, ptr);
}
return;
}
}
unsafe {
let rt = &mut *rt;
rt.main_gc.drop_local_ref(&mut rt.main_heap, ptr);
}
}
// SAFETY: trait-impl signature is fixed; `ptr` always comes from the
// VM's own heap allocations (the current actor's ActorHeap, or the
// runtime's main heap when there is no current actor).
#[allow(clippy::not_unsafe_ptr_arg_deref)]
fn retain_ref(&mut self, ptr: *mut u8) {
let mut rt = self.runtime.borrow_mut();
if let Some(actor_id) = rt.current_actor {
if let Some(actor) = rt.actors.get_mut(&actor_id) {
unsafe {
actor.orca_gc.local_ref(&actor.heap, ptr);
}
return;
}
}
unsafe {
let rt = &mut *rt;
rt.main_gc.local_ref(&rt.main_heap, ptr);
}
}
// SAFETY: trait-impl signature is fixed; `ptr` always comes from the
// VM's own heap allocations (the current actor's ActorHeap, or the
// runtime's main heap when there is no current actor). `header_of` is a
// pure pointer-arithmetic read relative to `ptr` itself, so it needs no
// actor/heap lookup at all beyond confirming there's a valid execution
// context to be reading from.
#[allow(clippy::not_unsafe_ptr_arg_deref)]
fn array_len(&self, ptr: *mut u8) -> Option<usize> {
unsafe {
let header = &*crate::runtime::heap::ActorHeap::header_of(ptr);
if header.type_tag == crate::runtime::heap::TypeTag::Array {
let payload_size = header
.size
.saturating_sub(crate::runtime::heap::ActorHeap::HEADER_SIZE);
Some(payload_size / std::mem::size_of::<crate::vm::Value>())
} else {
None
}
}
}
fn spawn_actor(
&mut self,
module: &crate::bytecode::CodeModule,
behavior_idx: usize,
init: Vec<(String, crate::vm::Value)>,
) -> crate::vm::Value {
self.runtime
.borrow_mut()
.spawn_from_module(module, behavior_idx, init)
}
fn send_message(
&mut self,
target: crate::vm::Value,
behavior_id: u16,
args: &[crate::vm::Value],
) {
if let Some(actor_id) = target.as_actor_id() {
let mut rt = self.runtime.borrow_mut();
rt.send_message_by_id(actor_id, behavior_id, args);
}
}
fn ask_actor(
&mut self,
target: crate::vm::Value,
behavior_id: u16,
args: &[crate::vm::Value],
) -> crate::vm::Value {
if let Some(actor_id) = target.as_actor_id() {
let mut rt = self.runtime.borrow_mut();
match rt.ask_actor_sync(actor_id, behavior_id, args) {
Ok(value) => return value,
Err(_) => {}
}
}
crate::vm::Value::nil()
}
fn get_state_field(&self, field: &str) -> crate::vm::Value {
let rt = self.runtime.borrow();
if let Some(actor_id) = rt.current_actor {
if let Some(actor) = rt.actors.get(&actor_id) {
return actor
.get_state_field(field)
.unwrap_or(crate::vm::Value::nil());
}
}
crate::vm::Value::nil()
}
fn set_state_field(&mut self, field: &str, value: crate::vm::Value) {
let mut rt = self.runtime.borrow_mut();
if let Some(actor_id) = rt.current_actor {
if let Some(actor) = rt.actors.get_mut(&actor_id) {
actor.set_state_field(field, value);
}
}
}
fn emit_event(&mut self, event: &str, args: &[crate::vm::Value]) {
let mut rt = self.runtime.borrow_mut();
if let Some(actor_id) = rt.current_actor {
rt.emit_event(actor_id, event, args);
}
}
fn perform_effect(
&mut self,
effect_name: &str,
regs: &[crate::vm::Value],
) -> Option<crate::vm::Value> {
if effect_name != "Timer" {
return None;
}
let mut rt = self.runtime.borrow_mut();
let actor_id = rt.current_actor?;
if !rt.actor_is_workflow(actor_id) {
return Some(crate::vm::Value::unit());
}
let name = {
let vm = rt.vm.as_mut()?;
let module_idx = vm.current_module_idx()?;
let string_id = regs.get(0)?.as_string_id()?;
vm.constant_string(module_idx, string_id)?
};
let duration_ms = regs.get(1)?.as_int()? as u64;
rt.schedule_workflow_timer(actor_id, &name, duration_ms);
Some(crate::vm::Value::unit())
}
#[cfg_attr(not(feature = "ai-runtime"), allow(unused_variables))]
fn perform_builtin_effect(
&mut self,
effect_name: &str,
op_name: Option<&str>,
constants: &[crate::bytecode::Constant],
regs: &[crate::vm::Value],
) -> Option<crate::vm::Value> {
if effect_name == "Workflow" && op_name == Some("query") {
let workflow_id = regs.get(0)?.as_actor_id()?;
let string_id = regs.get(1)?.as_string_id()?;
let query_name = match constants.get(string_id as usize) {
Some(crate::bytecode::Constant::String(s)) => s.clone(),
_ => return None,
};
let mut rt = self.runtime.borrow_mut();
return rt.query_workflow(workflow_id, &query_name);
}
#[cfg(feature = "sqlite")]
if effect_name == "DB" && op_name == Some("query") {
let sql = match regs.first().and_then(|v| v.as_string_id()) {
Some(id) => match constants.get(id as usize) {
Some(crate::bytecode::Constant::String(s)) => s.clone(),
_ => return Some(crate::vm::Value::nil()),
},
None => return Some(crate::vm::Value::nil()),
};
let params: Vec<crate::vm::Value> = regs.iter().skip(1).copied().collect();
let rt = self.runtime.borrow_mut();
let query_result = rt.persistence.query(&sql, ¶ms);
drop(rt);
let result = match query_result {
Ok(rows) => {
let json = serde_json::to_string(&rows).unwrap_or_default();
self.alloc_string(&json)
}
Err(_) => crate::vm::Value::nil(),
};
return Some(result);
}
if effect_name == "Timer" && op_name == Some("after") {
let ms = regs.first().and_then(|v| v.as_int()).unwrap_or(0);
if ms > 0 {
let callback_id = regs.get(1).and_then(|v| v.as_string_id());
let callback_name = callback_id.and_then(|id| {
constants.get(id as usize).and_then(|c| match c {
crate::bytecode::Constant::String(s) => Some(s.clone()),
_ => None,
})
});
if let Some(callback_name) = callback_name {
let rt = self.runtime.borrow_mut();
let actor_id = rt.current_actor.unwrap_or(0);
let behavior_id = rt.behavior_id_for(actor_id, &callback_name).unwrap_or(0);
if behavior_id > 0 {
rt.timer_wheel.send_after(
std::time::Duration::from_millis(ms as u64),
actor_id,
behavior_id,
vec![],
);
}
}
}
return Some(crate::vm::Value::unit());
}
if effect_name == "Int" && op_name == Some("to_string") {
let n = regs.first().and_then(|v| v.as_int()).unwrap_or(0);
let s = format!("{}", n);
return Some(self.alloc_string(&s));
}
if effect_name == "Int" && op_name == Some("to_float") {
let n = regs.first().and_then(|v| v.as_int()).unwrap_or(0);
return Some(crate::vm::Value::float(n as f64));
}
if effect_name == "Float" && op_name == Some("to_int") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
return Some(crate::vm::Value::int(x as i64));
}
if effect_name == "Float" && op_name == Some("to_string") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
let s = format!("{}", x);
return Some(self.alloc_string(&s));
}
if effect_name == "String" && op_name == Some("to_int") {
let s = crate::vm::resolve_value_string(
constants,
*regs.first().unwrap_or(&crate::vm::Value::nil()),
);
let n: i64 = s.parse().unwrap_or(0);
return Some(crate::vm::Value::int(n));
}
if effect_name == "String" && op_name == Some("to_float") {
let s = crate::vm::resolve_value_string(
constants,
*regs.first().unwrap_or(&crate::vm::Value::nil()),
);
let f: f64 = s.parse().unwrap_or(0.0);
return Some(crate::vm::Value::float(f));
}
if effect_name == "String" && op_name == Some("length") {
let s = crate::vm::resolve_value_string(
constants,
*regs.first().unwrap_or(&crate::vm::Value::nil()),
);
return Some(crate::vm::Value::int(s.len() as i64));
}
if effect_name == "String" && op_name == Some("charAt") {
let s = crate::vm::resolve_value_string(
constants,
*regs.first().unwrap_or(&crate::vm::Value::nil()),
);
let idx = regs.get(1).and_then(|v| v.as_int()).unwrap_or(-1);
if idx < 0 || idx as usize >= s.len() {
return Some(crate::vm::Value::int(-1));
}
return Some(crate::vm::Value::int(s.as_bytes()[idx as usize] as i64));
}
if effect_name == "Provider" && op_name == Some("ask") {
// General runtime-registered provider dispatch. The first arg is
// the provider name (string); the second is the prompt/request
// (string). This is the longevity path: `perform Provider.ask`
// references no transient technology, only an eternal "provider"
// abstraction. The "llm" provider reuses the existing LLM client.
let provider = match regs.get(0).and_then(|v| v.as_string_id()) {
Some(id) => match constants.get(id as usize) {
Some(crate::bytecode::Constant::String(s)) => s.clone(),
_ => return None,
},
None => return None,
};
let prompt = match regs.get(1) {
Some(v) => {
if let Some(id) = v.as_string_id() {
constants
.get(id as usize)
.and_then(|c| match c {
crate::bytecode::Constant::String(s) => Some(s.clone()),
_ => None,
})
.unwrap_or_default()
} else {
v.to_string_repr()
}
}
None => return None,
};
if provider == "llm" {
#[cfg(feature = "ai-runtime")]
{
let rt = self.runtime.borrow_mut();
if rt.llm.client.is_none() {
return Some(crate::vm::Value::nil());
}
let request = nulang_ai::LlmRequest {
model: String::new(),
messages: vec![nulang_ai::LlmMessage {
role: "user".to_string(),
content: prompt,
}],
tools: Vec::new(),
memory: Vec::new(),
pricing: None,
response_format: None,
};
let result = rt.complete_llm_request(request, Vec::new());
drop(rt);
return Some(match result {
Ok(resp) => match resp.content {
Some(c) => self.alloc_string(&c),
None => crate::vm::Value::nil(),
},
Err(_) => crate::vm::Value::nil(),
});
}
#[cfg(not(feature = "ai-runtime"))]
{
return Some(crate::vm::Value::nil());
}
}
return None;
}
if effect_name == "Debug" && op_name == Some("inspect") {
let target_id = regs.first().and_then(|v| v.as_int()).unwrap_or(0) as u64;
let rt = self.runtime.borrow();
let info = serde_json::json!({
"state": rt.actors.get(&target_id).map(|a| {
a.state_data.iter().map(|(k, v)| {
(k.clone(), crate::vm::resolve_value_string(constants, *v))
}).collect::<std::collections::HashMap<_, _>>()
}).unwrap_or_default(),
"mailbox_size": rt.actors.get(&target_id).map(|a| a.mailbox.len()).unwrap_or(0),
"behaviors": rt.actors.get(&target_id).map(|a| {
a.behavior_table.iter().map(|b| b.name.clone()).collect::<Vec<_>>()
}).unwrap_or_default(),
"supervisor": rt.supervisors.get(&target_id).map(|_s| target_id),
});
drop(rt);
let json = serde_json::to_string(&info).unwrap_or_default();
return Some(self.alloc_string(&json));
}
if effect_name == "Actor" {
let mut rt = self.runtime.borrow_mut();
let actor_id = rt.current_actor;
return rt.perform_actor_builtin(actor_id, op_name, constants, regs);
}
if effect_name == "IO" {
if let (Some("print") | Some("println"), Some(first)) = (op_name, regs.first()) {
let msg = crate::vm::resolve_value_string(constants, *first);
println!("{}", msg);
return Some(crate::vm::Value::unit());
}
}
#[cfg(feature = "python")]
if effect_name == "Python" {
let mut rt = self.runtime.borrow_mut();
return rt.perform_python_builtin(op_name, constants, regs);
}
if effect_name == "CRDT" {
let mut rt = self.runtime.borrow_mut();
return rt.perform_crdt_builtin(op_name, constants, regs);
}
self.perform_effect(effect_name, regs)
}
fn perform_builtin_effect_in_module(
&mut self,
effect_name: &str,
op_name: Option<&str>,
module: &crate::bytecode::CodeModule,
regs: &[crate::vm::Value],
) -> Option<crate::vm::Value> {
let qualified = match op_name {
Some(op) => format!("{}.{}", effect_name, op),
None => effect_name.to_string(),
};
// Check test handlers before real dispatch — allows tests to
// intercept effects without a `handle` block in source.
{
let rt = self.runtime.borrow();
if let Some(result) = rt.check_test_handler(&qualified, regs) {
return Some(result);
}
}
if effect_name == "Otp" {
let mut rt = self.runtime.borrow_mut();
return rt.perform_otp_builtin(op_name, module, regs);
}
if effect_name == "Http" && op_name == Some("serve") {
let port = regs.first().and_then(|v| v.as_int()).unwrap_or(0) as u16;
let func_idx = match regs.get(1) {
Some(v) if v.is_closure() => {
let payload = v.as_raw() & crate::value_layout::PAYLOAD_MASK;
if payload & crate::vm::CLOSURE_ENV_FLAG != 0 {
return Some(crate::vm::Value::nil());
}
payload as usize
}
Some(v) => {
// Function index passed as raw Int (from func_map lookup).
v.as_int().unwrap_or(0) as usize
}
None => return Some(crate::vm::Value::nil()),
};
return match HttpServerState::bind(port, module.clone(), func_idx) {
Ok(server) => {
let actual_port = server.port;
self.runtime.borrow_mut().http_server = Some(server);
Some(crate::vm::Value::int(actual_port as i64))
}
Err(_) => Some(crate::vm::Value::nil()),
};
}
self.perform_builtin_effect(effect_name, op_name, &module.constants, regs)
}
#[cfg_attr(not(feature = "ai-runtime"), allow(unused_variables))]
fn perform_async(
&mut self,
effect_op: &str,
constants: &[crate::bytecode::Constant],
args: &[crate::vm::Value],
) -> crate::vm::PerformAsyncResult {
match effect_op {
#[cfg(feature = "ai-runtime")]
"Inference.ask" | "LLM.ask" => {
let prompt = resolve_first_string(constants, args);
let result = self.complete_llm("", &prompt);
crate::vm::PerformAsyncResult::Ready(result)
}
"Timer.sleep" => {
let ms = args.first().and_then(|v| v.as_int()).unwrap_or(0) as u64;
let mut rt = self.runtime.borrow_mut();
let actor_id = rt.current_actor.unwrap_or(0);
if let Some(actor) = rt.actors.get_mut(&actor_id) {
if actor.timer_sleep_fired {
actor.timer_sleep_fired = false;
return crate::vm::PerformAsyncResult::Ready(None);
}
}
if ms == 0 {
return crate::vm::PerformAsyncResult::Ready(None);
}
if ms > 0 {
rt.timer_wheel
.timer_sleep_wake(std::time::Duration::from_millis(ms), actor_id);
}
crate::vm::PerformAsyncResult::Pending
}
#[cfg(feature = "ai-runtime")]
"Pipeline.new" => {
let id = self.runtime.borrow_mut().pipeline_new();
crate::vm::PerformAsyncResult::Ready(Some(id.to_string()))
}
#[cfg(feature = "ai-runtime")]
"Pipeline.stage" => {
let id = id_arg(constants, args, 0);
let name = string_arg(constants, args, 1);
let actor = actor_arg(args, 2);
let template = string_arg(constants, args, 3);
let result = self
.runtime
.borrow_mut()
.pipeline_stage(id, &name, actor, &template);
let r = result.map(|id| id as i64).unwrap_or(-1);
crate::vm::PerformAsyncResult::Ready(Some(r.to_string()))
}
#[cfg(feature = "ai-runtime")]
"Pipeline.run" => {
let id = id_arg(constants, args, 0);
let input = string_arg(constants, args, 1);
let result = self.runtime.borrow_mut().pipeline_run(id, &input).ok();
crate::vm::PerformAsyncResult::Ready(result)
}
#[cfg(feature = "ai-runtime")]
"Supervisor.new" => {
let id = self.runtime.borrow_mut().supervisor_new();
crate::vm::PerformAsyncResult::Ready(Some(id.to_string()))
}
#[cfg(feature = "ai-runtime")]
"Supervisor.worker" => {
let id = id_arg(constants, args, 0);
let name = string_arg(constants, args, 1);
let actor = actor_arg(args, 2);
let description = string_arg(constants, args, 3);
let result =
self.runtime
.borrow_mut()
.supervisor_worker(id, &name, actor, &description);
let r = result.map(|id| id as i64).unwrap_or(-1);
crate::vm::PerformAsyncResult::Ready(Some(r.to_string()))
}
#[cfg(feature = "ai-runtime")]
"Supervisor.run" => {
let id = id_arg(constants, args, 0);
let task = string_arg(constants, args, 1);
let result = self.runtime.borrow_mut().supervisor_run(id, &task).ok();
crate::vm::PerformAsyncResult::Ready(result)
}
#[cfg(feature = "ai-runtime")]
"Debate.new" => {
let topic = string_arg(constants, args, 0);
let rounds = int_arg(args, 1);
let threshold = float_arg(args, 2);
let id = self
.runtime
.borrow_mut()
.debate_new(&topic, rounds, threshold);
crate::vm::PerformAsyncResult::Ready(Some(id.to_string()))
}
#[cfg(feature = "ai-runtime")]
"Debate.participant" => {
let id = id_arg(constants, args, 0);
let name = string_arg(constants, args, 1);
let stance = string_arg(constants, args, 2);
let actor = actor_arg(args, 3);
let result = self
.runtime
.borrow_mut()
.debate_participant(id, &name, &stance, actor);
let r = result.map(|id| id as i64).unwrap_or(-1);
crate::vm::PerformAsyncResult::Ready(Some(r.to_string()))
}
#[cfg(feature = "ai-runtime")]
"Debate.run" => {
let id = id_arg(constants, args, 0);
let result = self.runtime.borrow_mut().debate_run(id).ok();
crate::vm::PerformAsyncResult::Ready(result)
}
_ => crate::vm::PerformAsyncResult::Ready(None),
}
}
#[cfg(feature = "ai-runtime")]
fn complete_llm(&mut self, model: &str, prompt: &str) -> Option<String> {
let mut rt = self.runtime.borrow_mut();
if let Some(actor_id) = rt.current_actor {
if rt
.actors
.get(&actor_id)
.map(|a| a.is_agent)
.unwrap_or(false)
{
return rt.complete_agent_llm(actor_id, prompt);
}
}
// Top-level (non-actor) LLM ask: issue a direct request without
// agent state or memory handling.
let request = LlmRequest {
model: model.to_string(),
messages: vec![LlmMessage {
role: "user".to_string(),
content: prompt.to_string(),
}],
tools: Vec::new(),
memory: Vec::new(),
pricing: None,
response_format: None,
};
rt.complete_llm_request(request, Vec::new()).ok()?.content
}
fn try_receive(&mut self) -> Option<(u16, crate::vm::Value)> {
let mut rt = self.runtime.borrow_mut();
let actor_id = rt.current_actor?;
let msg = rt.actors.get_mut(&actor_id)?.mailbox.pop()?;
// ORCA receiver protocol: hold heap pointers carried by the message.
rt.hold_payload_refs(actor_id, &*msg.payload);
let val = msg
.payload
.first()
.cloned()
.unwrap_or(crate::vm::Value::unit());
Some((msg.behavior_id, val))
}
fn try_receive_match(
&mut self,
behavior_ids: &[u16],
) -> Option<(usize, Vec<crate::vm::Value>)> {
let mut rt = self.runtime.borrow_mut();
let actor_id = rt.current_actor?;
let (pos, payload) = rt
.actors
.get_mut(&actor_id)?
.mailbox
.receive_match(behavior_ids)?;
// ORCA receiver protocol: hold heap pointers carried by the message.
rt.hold_payload_refs(actor_id, &*payload);
Some((
pos,
Arc::try_unwrap(payload).unwrap_or_else(|arc| (*arc).clone()),
))
}
fn commit_receive_match(&mut self) {
let mut rt = self.runtime.borrow_mut();
if let Some(actor_id) = rt.current_actor {
if let Some(actor) = rt.actors.get_mut(&actor_id) {
actor.mailbox.commit_receive_match();
}
}
}
fn reset_receive_match(&mut self) {
let mut rt = self.runtime.borrow_mut();
if let Some(actor_id) = rt.current_actor {
if let Some(actor) = rt.actors.get_mut(&actor_id) {
actor.mailbox.reset_receive_match();
}
}
}
}
// Helpers for extracting typed arguments from PerformAsync register values.
#[cfg(feature = "ai-runtime")]
fn int_arg(args: &[crate::vm::Value], idx: usize) -> i64 {
args.get(idx).and_then(|v| v.as_int()).unwrap_or(0)
}
#[cfg(feature = "ai-runtime")]
fn actor_arg(args: &[crate::vm::Value], idx: usize) -> u64 {
args.get(idx).and_then(|v| v.as_actor_id()).unwrap_or(0)
}
#[cfg(feature = "ai-runtime")]
fn float_arg(args: &[crate::vm::Value], idx: usize) -> f64 {
args.get(idx).and_then(|v| v.as_float()).unwrap_or(0.0)
}
#[cfg(feature = "ai-runtime")]
fn string_arg(
constants: &[crate::bytecode::Constant],
args: &[crate::vm::Value],
idx: usize,
) -> String {
args.get(idx).map_or(String::new(), |v| {
if let Some(s) = v.as_string_id() {
constants
.get(s as usize)
.and_then(|c| match c {
crate::bytecode::Constant::String(s) => Some(s.clone()),
_ => None,
})
.unwrap_or_default()
} else {
String::new()
}
})
}
#[cfg(feature = "ai-runtime")]
fn resolve_first_string(
constants: &[crate::bytecode::Constant],
args: &[crate::vm::Value],
) -> String {
string_arg(constants, args, 0)
}
#[cfg(feature = "ai-runtime")]
fn id_arg(constants: &[crate::bytecode::Constant], args: &[crate::vm::Value], idx: usize) -> u64 {
// Try int first (legacy path), then parse string-id from constants as u64.
if let Some(v) = args.get(idx) {
if let Some(n) = v.as_int() {
return n as u64;
}
}
let s = string_arg(constants, args, idx);
s.parse::<u64>().unwrap_or(0)
}
/// Raw-pointer callbacks used when the runtime itself executes an actor's
/// bytecode behavior. Holds a transient borrow of the executing `Runtime`.
#[derive(Debug)]
pub(crate) struct BytecodeRuntimeCallbacks {
runtime: *mut Runtime,
actor_id: u64,
}
unsafe impl Send for BytecodeRuntimeCallbacks {}
unsafe impl Sync for BytecodeRuntimeCallbacks {}
impl BytecodeRuntimeCallbacks {
pub(crate) fn new(runtime: *mut Runtime, actor_id: u64) -> Self {
BytecodeRuntimeCallbacks { runtime, actor_id }
}
}
impl crate::vm::ActorVmCallbacks for BytecodeRuntimeCallbacks {
fn current_actor_id(&self) -> Option<u64> {
Some(self.actor_id)
}
fn alloc(&mut self, size: usize, type_tag: crate::runtime::heap::TypeTag) -> Option<*mut u8> {
unsafe {
(*self.runtime)
.actors
.get_mut(&self.actor_id)?
.heap
.alloc(size, type_tag)
}
}
fn drop_ref(&mut self, ptr: *mut u8) {
unsafe {
if let Some(actor) = (*self.runtime).actors.get_mut(&self.actor_id) {
// Route through ORCA so objects with outstanding foreign
// references are deferred instead of freed out from under
// other actors.
actor.orca_gc.drop_local_ref(&mut actor.heap, ptr);
}
}
}
fn retain_ref(&mut self, ptr: *mut u8) {
unsafe {
if let Some(actor) = (*self.runtime).actors.get_mut(&self.actor_id) {
actor.orca_gc.local_ref(&actor.heap, ptr);
}
}
}
fn array_len(&self, ptr: *mut u8) -> Option<usize> {
unsafe {
let _actor = (*self.runtime).actors.get(&self.actor_id)?;
let header = &*crate::runtime::heap::ActorHeap::header_of(ptr);
if header.type_tag == crate::runtime::heap::TypeTag::Array {
let payload_size = header
.size
.saturating_sub(crate::runtime::heap::ActorHeap::HEADER_SIZE);
Some(payload_size / std::mem::size_of::<crate::vm::Value>())
} else {
None
}
}
}
fn spawn_actor(
&mut self,
module: &crate::bytecode::CodeModule,
behavior_idx: usize,
init: Vec<(String, crate::vm::Value)>,
) -> crate::vm::Value {
// SAFETY: the callback is installed on the shared runtime VM only
// while the runtime drives a behavior on the single scheduler
// thread, so `runtime` is a live, exclusively-borrowed pointer.
// Spawning mutates runtime state but never re-enters the VM.
unsafe { (*self.runtime).spawn_from_module(module, behavior_idx, init) }
}
fn send_message(
&mut self,
target: crate::vm::Value,
behavior_id: u16,
args: &[crate::vm::Value],
) {
if let Some(target_id) = target.as_actor_id() {
// SAFETY: as above. `send_message_by_id` is safe mid-behavior:
// it pushes mail, bumps ORCA foreign counts, and enqueues the
// target; the receive-wait wake is deferred while the shared
// VM is executing (see `Runtime::pending_receive_wakes`).
unsafe { (*self.runtime).send_message_by_id(target_id, behavior_id, args) }
}
}
fn get_state_field(&self, field: &str) -> crate::vm::Value {
unsafe {
if let Some(actor) = (*self.runtime).actors.get(&self.actor_id) {
return actor
.get_state_field(field)
.unwrap_or(crate::vm::Value::nil());
}
}
crate::vm::Value::nil()
}
fn set_state_field(&mut self, field: &str, value: crate::vm::Value) {
unsafe {
if let Some(actor) = (*self.runtime).actors.get_mut(&self.actor_id) {
actor.set_state_field(field, value);
}
}
}
fn emit_event(&mut self, event: &str, args: &[crate::vm::Value]) {
unsafe {
(*self.runtime).emit_event(self.actor_id, event, args);
}
}
fn wait_signal(&mut self, name: &str) -> crate::vm::SignalWaitResult {
unsafe {
if let Some(actor) = (*self.runtime).actors.get(&self.actor_id) {
if actor.received_signals.iter().any(|(n, _)| n == name) {
return crate::vm::SignalWaitResult::Ready(crate::vm::Value::unit());
}
}
crate::vm::SignalWaitResult::NotReady
}
}
fn suspend_for_signal(&mut self, _name: &str, _vm_state: Option<crate::vm::SuspendedVmState>) {
// State capture is handled by run_bytecode_at_offset after run_from
// returns, avoiding aliasing the Runtime through this raw-pointer
// callback while the VM borrow is active.
}
fn perform_effect(
&mut self,
effect_name: &str,
regs: &[crate::vm::Value],
) -> Option<crate::vm::Value> {
unsafe {
if effect_name != "Timer" {
return None;
}
let actor = (*self.runtime).actors.get(&self.actor_id)?;
if !actor.is_workflow {
return Some(crate::vm::Value::unit());
}
let vm = (*self.runtime).vm.as_mut()?;
let module_idx = vm.current_module_idx()?;
let string_id = regs.get(0)?.as_string_id()?;
let name = vm.constant_string(module_idx, string_id)?;
let duration_ms = regs.get(1)?.as_int()? as u64;
(*self.runtime).schedule_workflow_timer(self.actor_id, &name, duration_ms);
Some(crate::vm::Value::unit())
}
}
#[cfg_attr(not(feature = "ai-runtime"), allow(unused_variables))]
fn perform_builtin_effect(
&mut self,
effect_name: &str,
op_name: Option<&str>,
constants: &[crate::bytecode::Constant],
regs: &[crate::vm::Value],
) -> Option<crate::vm::Value> {
unsafe {
if effect_name == "Workflow" && op_name == Some("query") {
let workflow_id = regs.get(0)?.as_actor_id()?;
let string_id = regs.get(1)?.as_string_id()?;
let query_name = match constants.get(string_id as usize) {
Some(crate::bytecode::Constant::String(s)) => s.clone(),
_ => return None,
};
return (*self.runtime).query_workflow(workflow_id, &query_name);
}
#[cfg(feature = "sqlite")]
if effect_name == "DB" && op_name == Some("query") {
let sql = match regs.first().and_then(|v| v.as_string_id()) {
Some(id) => match constants.get(id as usize) {
Some(crate::bytecode::Constant::String(s)) => s.clone(),
_ => return Some(crate::vm::Value::nil()),
},
None => return Some(crate::vm::Value::nil()),
};
let params: Vec<crate::vm::Value> = regs.iter().skip(1).copied().collect();
return match (*self.runtime).persistence.query(&sql, ¶ms) {
Ok(rows) => {
let json = serde_json::to_string(&rows).unwrap_or_default();
if let Some(vm) = &mut (*self.runtime).vm {
Some(vm.allocate_string(&json))
} else {
Some(crate::vm::Value::nil())
}
}
Err(_) => Some(crate::vm::Value::nil()),
};
}
if effect_name == "Actor" {
return (*self.runtime).perform_actor_builtin(
Some(self.actor_id),
op_name,
constants,
regs,
);
}
if effect_name == "Int" && op_name == Some("to_float") {
let n = regs.first().and_then(|v| v.as_int()).unwrap_or(0);
return Some(crate::vm::Value::float(n as f64));
}
if effect_name == "Float" && op_name == Some("to_int") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);