1use std::collections::BTreeMap;
2use std::io::BufRead;
3use std::rc::Rc;
4use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU8, Ordering};
5use std::sync::Arc;
6
7use crate::value::{values_equal, VmAtomicHandle, VmChannelHandle, VmError, VmValue};
8use crate::vm::Vm;
9
10use crate::http::register_http_builtins;
11use crate::llm::register_llm_builtins;
12use crate::mcp::register_mcp_builtins;
13
14fn select_result(index: usize, value: VmValue, channel_name: &str) -> VmValue {
16 let mut result = BTreeMap::new();
17 result.insert("index".to_string(), VmValue::Int(index as i64));
18 result.insert("value".to_string(), value);
19 result.insert(
20 "channel".to_string(),
21 VmValue::String(Rc::from(channel_name)),
22 );
23 VmValue::Dict(Rc::new(result))
24}
25
26fn select_none() -> VmValue {
28 let mut result = BTreeMap::new();
29 result.insert("index".to_string(), VmValue::Int(-1));
30 result.insert("value".to_string(), VmValue::Nil);
31 result.insert("channel".to_string(), VmValue::Nil);
32 VmValue::Dict(Rc::new(result))
33}
34
35fn try_poll_channels(channels: &[VmValue]) -> (Option<(usize, VmValue, String)>, bool) {
39 let mut all_closed = true;
40 for (i, ch_val) in channels.iter().enumerate() {
41 if let VmValue::Channel(ch) = ch_val {
42 if let Ok(mut rx) = ch.receiver.try_lock() {
43 match rx.try_recv() {
44 Ok(val) => return (Some((i, val, ch.name.clone())), false),
45 Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {
46 all_closed = false;
47 }
48 Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {}
49 }
50 } else {
51 all_closed = false;
52 }
53 }
54 }
55 (None, all_closed)
56}
57
58pub fn register_vm_stdlib(vm: &mut Vm) {
60 vm.register_builtin("log", |args, out| {
61 let msg = args.first().map(|a| a.display()).unwrap_or_default();
62 out.push_str(&format!("[harn] {msg}\n"));
63 Ok(VmValue::Nil)
64 });
65 vm.register_builtin("print", |args, out| {
66 let msg = args.first().map(|a| a.display()).unwrap_or_default();
67 out.push_str(&msg);
68 Ok(VmValue::Nil)
69 });
70 vm.register_builtin("println", |args, out| {
71 let msg = args.first().map(|a| a.display()).unwrap_or_default();
72 out.push_str(&format!("{msg}\n"));
73 Ok(VmValue::Nil)
74 });
75 vm.register_builtin("type_of", |args, _out| {
76 let val = args.first().unwrap_or(&VmValue::Nil);
77 Ok(VmValue::String(Rc::from(val.type_name())))
78 });
79 vm.register_builtin("to_string", |args, _out| {
80 let val = args.first().unwrap_or(&VmValue::Nil);
81 Ok(VmValue::String(Rc::from(val.display())))
82 });
83 vm.register_builtin("to_int", |args, _out| {
84 let val = args.first().unwrap_or(&VmValue::Nil);
85 match val {
86 VmValue::Int(n) => Ok(VmValue::Int(*n)),
87 VmValue::Float(n) => Ok(VmValue::Int(*n as i64)),
88 VmValue::String(s) => Ok(s.parse::<i64>().map(VmValue::Int).unwrap_or(VmValue::Nil)),
89 _ => Ok(VmValue::Nil),
90 }
91 });
92 vm.register_builtin("to_float", |args, _out| {
93 let val = args.first().unwrap_or(&VmValue::Nil);
94 match val {
95 VmValue::Float(n) => Ok(VmValue::Float(*n)),
96 VmValue::Int(n) => Ok(VmValue::Float(*n as f64)),
97 VmValue::String(s) => Ok(s.parse::<f64>().map(VmValue::Float).unwrap_or(VmValue::Nil)),
98 _ => Ok(VmValue::Nil),
99 }
100 });
101
102 vm.register_builtin("json_stringify", |args, _out| {
103 let val = args.first().unwrap_or(&VmValue::Nil);
104 Ok(VmValue::String(Rc::from(vm_value_to_json(val))))
105 });
106
107 vm.register_builtin("json_parse", |args, _out| {
108 let text = args.first().map(|a| a.display()).unwrap_or_default();
109 match serde_json::from_str::<serde_json::Value>(&text) {
110 Ok(jv) => Ok(json_to_vm_value(&jv)),
111 Err(e) => Err(VmError::Thrown(VmValue::String(Rc::from(format!(
112 "JSON parse error: {e}"
113 ))))),
114 }
115 });
116
117 vm.register_builtin("env", |args, _out| {
118 let name = args.first().map(|a| a.display()).unwrap_or_default();
119 match std::env::var(&name) {
120 Ok(val) => Ok(VmValue::String(Rc::from(val))),
121 Err(_) => Ok(VmValue::Nil),
122 }
123 });
124
125 vm.register_builtin("timestamp", |_args, _out| {
126 use std::time::{SystemTime, UNIX_EPOCH};
127 let secs = SystemTime::now()
128 .duration_since(UNIX_EPOCH)
129 .map(|d| d.as_secs_f64())
130 .unwrap_or(0.0);
131 Ok(VmValue::Float(secs))
132 });
133
134 vm.register_builtin("read_file", |args, _out| {
135 let path = args.first().map(|a| a.display()).unwrap_or_default();
136 match std::fs::read_to_string(&path) {
137 Ok(content) => Ok(VmValue::String(Rc::from(content))),
138 Err(e) => Err(VmError::Thrown(VmValue::String(Rc::from(format!(
139 "Failed to read file {path}: {e}"
140 ))))),
141 }
142 });
143
144 vm.register_builtin("write_file", |args, _out| {
145 if args.len() >= 2 {
146 let path = args[0].display();
147 let content = args[1].display();
148 std::fs::write(&path, &content).map_err(|e| {
149 VmError::Thrown(VmValue::String(Rc::from(format!(
150 "Failed to write file {path}: {e}"
151 ))))
152 })?;
153 }
154 Ok(VmValue::Nil)
155 });
156
157 vm.register_builtin("exit", |args, _out| {
158 let code = args.first().and_then(|a| a.as_int()).unwrap_or(0);
159 std::process::exit(code as i32);
160 });
161
162 vm.register_builtin("regex_match", |args, _out| {
163 if args.len() >= 2 {
164 let pattern = args[0].display();
165 let text = args[1].display();
166 let re = regex::Regex::new(&pattern).map_err(|e| {
167 VmError::Thrown(VmValue::String(Rc::from(format!("Invalid regex: {e}"))))
168 })?;
169 let matches: Vec<VmValue> = re
170 .find_iter(&text)
171 .map(|m| VmValue::String(Rc::from(m.as_str())))
172 .collect();
173 if matches.is_empty() {
174 return Ok(VmValue::Nil);
175 }
176 return Ok(VmValue::List(Rc::new(matches)));
177 }
178 Ok(VmValue::Nil)
179 });
180
181 vm.register_builtin("regex_replace", |args, _out| {
182 if args.len() >= 3 {
183 let pattern = args[0].display();
184 let replacement = args[1].display();
185 let text = args[2].display();
186 let re = regex::Regex::new(&pattern).map_err(|e| {
187 VmError::Thrown(VmValue::String(Rc::from(format!("Invalid regex: {e}"))))
188 })?;
189 return Ok(VmValue::String(Rc::from(
190 re.replace_all(&text, replacement.as_str()).into_owned(),
191 )));
192 }
193 Ok(VmValue::Nil)
194 });
195
196 vm.register_builtin("prompt_user", |args, out| {
197 let msg = args.first().map(|a| a.display()).unwrap_or_default();
198 out.push_str(&msg);
199 let mut input = String::new();
200 if std::io::stdin().lock().read_line(&mut input).is_ok() {
201 Ok(VmValue::String(Rc::from(input.trim_end())))
202 } else {
203 Ok(VmValue::Nil)
204 }
205 });
206
207 vm.register_builtin("abs", |args, _out| {
210 match args.first().unwrap_or(&VmValue::Nil) {
211 VmValue::Int(n) => Ok(VmValue::Int(n.wrapping_abs())),
212 VmValue::Float(n) => Ok(VmValue::Float(n.abs())),
213 _ => Ok(VmValue::Nil),
214 }
215 });
216
217 vm.register_builtin("min", |args, _out| {
218 if args.len() >= 2 {
219 match (&args[0], &args[1]) {
220 (VmValue::Int(x), VmValue::Int(y)) => Ok(VmValue::Int(*x.min(y))),
221 (VmValue::Float(x), VmValue::Float(y)) => Ok(VmValue::Float(x.min(*y))),
222 (VmValue::Int(x), VmValue::Float(y)) => Ok(VmValue::Float((*x as f64).min(*y))),
223 (VmValue::Float(x), VmValue::Int(y)) => Ok(VmValue::Float(x.min(*y as f64))),
224 _ => Ok(VmValue::Nil),
225 }
226 } else {
227 Ok(VmValue::Nil)
228 }
229 });
230
231 vm.register_builtin("max", |args, _out| {
232 if args.len() >= 2 {
233 match (&args[0], &args[1]) {
234 (VmValue::Int(x), VmValue::Int(y)) => Ok(VmValue::Int(*x.max(y))),
235 (VmValue::Float(x), VmValue::Float(y)) => Ok(VmValue::Float(x.max(*y))),
236 (VmValue::Int(x), VmValue::Float(y)) => Ok(VmValue::Float((*x as f64).max(*y))),
237 (VmValue::Float(x), VmValue::Int(y)) => Ok(VmValue::Float(x.max(*y as f64))),
238 _ => Ok(VmValue::Nil),
239 }
240 } else {
241 Ok(VmValue::Nil)
242 }
243 });
244
245 vm.register_builtin("floor", |args, _out| {
246 match args.first().unwrap_or(&VmValue::Nil) {
247 VmValue::Float(n) => Ok(VmValue::Int(n.floor() as i64)),
248 VmValue::Int(n) => Ok(VmValue::Int(*n)),
249 _ => Ok(VmValue::Nil),
250 }
251 });
252
253 vm.register_builtin("ceil", |args, _out| {
254 match args.first().unwrap_or(&VmValue::Nil) {
255 VmValue::Float(n) => Ok(VmValue::Int(n.ceil() as i64)),
256 VmValue::Int(n) => Ok(VmValue::Int(*n)),
257 _ => Ok(VmValue::Nil),
258 }
259 });
260
261 vm.register_builtin("round", |args, _out| {
262 match args.first().unwrap_or(&VmValue::Nil) {
263 VmValue::Float(n) => Ok(VmValue::Int(n.round() as i64)),
264 VmValue::Int(n) => Ok(VmValue::Int(*n)),
265 _ => Ok(VmValue::Nil),
266 }
267 });
268
269 vm.register_builtin("sqrt", |args, _out| {
270 match args.first().unwrap_or(&VmValue::Nil) {
271 VmValue::Float(n) => Ok(VmValue::Float(n.sqrt())),
272 VmValue::Int(n) => Ok(VmValue::Float((*n as f64).sqrt())),
273 _ => Ok(VmValue::Nil),
274 }
275 });
276
277 vm.register_builtin("pow", |args, _out| {
278 if args.len() >= 2 {
279 match (&args[0], &args[1]) {
280 (VmValue::Int(base), VmValue::Int(exp)) => {
281 if *exp >= 0 && *exp <= u32::MAX as i64 {
282 Ok(VmValue::Int(base.wrapping_pow(*exp as u32)))
283 } else {
284 Ok(VmValue::Float((*base as f64).powf(*exp as f64)))
285 }
286 }
287 (VmValue::Float(base), VmValue::Int(exp)) => {
288 if *exp >= i32::MIN as i64 && *exp <= i32::MAX as i64 {
289 Ok(VmValue::Float(base.powi(*exp as i32)))
290 } else {
291 Ok(VmValue::Float(base.powf(*exp as f64)))
292 }
293 }
294 (VmValue::Int(base), VmValue::Float(exp)) => {
295 Ok(VmValue::Float((*base as f64).powf(*exp)))
296 }
297 (VmValue::Float(base), VmValue::Float(exp)) => Ok(VmValue::Float(base.powf(*exp))),
298 _ => Ok(VmValue::Nil),
299 }
300 } else {
301 Ok(VmValue::Nil)
302 }
303 });
304
305 vm.register_builtin("random", |_args, _out| {
306 use rand::Rng;
307 let val: f64 = rand::thread_rng().gen();
308 Ok(VmValue::Float(val))
309 });
310
311 vm.register_builtin("random_int", |args, _out| {
312 use rand::Rng;
313 if args.len() >= 2 {
314 let min = args[0].as_int().unwrap_or(0);
315 let max = args[1].as_int().unwrap_or(0);
316 if min <= max {
317 let val = rand::thread_rng().gen_range(min..=max);
318 return Ok(VmValue::Int(val));
319 }
320 }
321 Ok(VmValue::Nil)
322 });
323
324 vm.register_builtin("assert", |args, _out| {
327 let condition = args.first().unwrap_or(&VmValue::Nil);
328 if !condition.is_truthy() {
329 let msg = args
330 .get(1)
331 .map(|a| a.display())
332 .unwrap_or_else(|| "Assertion failed".to_string());
333 return Err(VmError::Thrown(VmValue::String(Rc::from(msg))));
334 }
335 Ok(VmValue::Nil)
336 });
337
338 vm.register_builtin("assert_eq", |args, _out| {
339 if args.len() >= 2 {
340 if !values_equal(&args[0], &args[1]) {
341 let msg = args.get(2).map(|a| a.display()).unwrap_or_else(|| {
342 format!(
343 "Assertion failed: expected {}, got {}",
344 args[1].display(),
345 args[0].display()
346 )
347 });
348 return Err(VmError::Thrown(VmValue::String(Rc::from(msg))));
349 }
350 Ok(VmValue::Nil)
351 } else {
352 Err(VmError::Thrown(VmValue::String(Rc::from(
353 "assert_eq requires at least 2 arguments",
354 ))))
355 }
356 });
357
358 vm.register_builtin("assert_ne", |args, _out| {
359 if args.len() >= 2 {
360 if values_equal(&args[0], &args[1]) {
361 let msg = args.get(2).map(|a| a.display()).unwrap_or_else(|| {
362 format!(
363 "Assertion failed: values should not be equal: {}",
364 args[0].display()
365 )
366 });
367 return Err(VmError::Thrown(VmValue::String(Rc::from(msg))));
368 }
369 Ok(VmValue::Nil)
370 } else {
371 Err(VmError::Thrown(VmValue::String(Rc::from(
372 "assert_ne requires at least 2 arguments",
373 ))))
374 }
375 });
376
377 vm.register_builtin("__range__", |args, _out| {
378 let start = args.first().and_then(|a| a.as_int()).unwrap_or(0);
379 let end = args.get(1).and_then(|a| a.as_int()).unwrap_or(0);
380 let inclusive = args.get(2).map(|a| a.is_truthy()).unwrap_or(false);
381 let items: Vec<VmValue> = if inclusive {
382 (start..=end).map(VmValue::Int).collect()
383 } else {
384 (start..end).map(VmValue::Int).collect()
385 };
386 Ok(VmValue::List(Rc::new(items)))
387 });
388
389 vm.register_builtin("file_exists", |args, _out| {
394 let path = args.first().map(|a| a.display()).unwrap_or_default();
395 Ok(VmValue::Bool(std::path::Path::new(&path).exists()))
396 });
397
398 vm.register_builtin("delete_file", |args, _out| {
399 let path = args.first().map(|a| a.display()).unwrap_or_default();
400 let p = std::path::Path::new(&path);
401 if p.is_dir() {
402 std::fs::remove_dir_all(&path).map_err(|e| {
403 VmError::Thrown(VmValue::String(Rc::from(format!(
404 "Failed to delete directory {path}: {e}"
405 ))))
406 })?;
407 } else {
408 std::fs::remove_file(&path).map_err(|e| {
409 VmError::Thrown(VmValue::String(Rc::from(format!(
410 "Failed to delete file {path}: {e}"
411 ))))
412 })?;
413 }
414 Ok(VmValue::Nil)
415 });
416
417 vm.register_builtin("append_file", |args, _out| {
418 use std::io::Write;
419 if args.len() >= 2 {
420 let path = args[0].display();
421 let content = args[1].display();
422 let mut file = std::fs::OpenOptions::new()
423 .append(true)
424 .create(true)
425 .open(&path)
426 .map_err(|e| {
427 VmError::Thrown(VmValue::String(Rc::from(format!(
428 "Failed to open file {path}: {e}"
429 ))))
430 })?;
431 file.write_all(content.as_bytes()).map_err(|e| {
432 VmError::Thrown(VmValue::String(Rc::from(format!(
433 "Failed to append to file {path}: {e}"
434 ))))
435 })?;
436 }
437 Ok(VmValue::Nil)
438 });
439
440 vm.register_builtin("list_dir", |args, _out| {
441 let path = args
442 .first()
443 .map(|a| a.display())
444 .unwrap_or_else(|| ".".to_string());
445 let entries = std::fs::read_dir(&path).map_err(|e| {
446 VmError::Thrown(VmValue::String(Rc::from(format!(
447 "Failed to list directory {path}: {e}"
448 ))))
449 })?;
450 let mut result = Vec::new();
451 for entry in entries {
452 let entry =
453 entry.map_err(|e| VmError::Thrown(VmValue::String(Rc::from(e.to_string()))))?;
454 let name = entry.file_name().to_string_lossy().to_string();
455 result.push(VmValue::String(Rc::from(name.as_str())));
456 }
457 result.sort_by_key(|a| a.display());
458 Ok(VmValue::List(Rc::new(result)))
459 });
460
461 vm.register_builtin("mkdir", |args, _out| {
462 let path = args.first().map(|a| a.display()).unwrap_or_default();
463 std::fs::create_dir_all(&path).map_err(|e| {
464 VmError::Thrown(VmValue::String(Rc::from(format!(
465 "Failed to create directory {path}: {e}"
466 ))))
467 })?;
468 Ok(VmValue::Nil)
469 });
470
471 vm.register_builtin("path_join", |args, _out| {
472 let mut path = std::path::PathBuf::new();
473 for arg in args {
474 path.push(arg.display());
475 }
476 Ok(VmValue::String(Rc::from(
477 path.to_string_lossy().to_string().as_str(),
478 )))
479 });
480
481 vm.register_builtin("copy_file", |args, _out| {
482 if args.len() >= 2 {
483 let src = args[0].display();
484 let dst = args[1].display();
485 std::fs::copy(&src, &dst).map_err(|e| {
486 VmError::Thrown(VmValue::String(Rc::from(format!(
487 "Failed to copy {src} to {dst}: {e}"
488 ))))
489 })?;
490 }
491 Ok(VmValue::Nil)
492 });
493
494 vm.register_builtin("temp_dir", |_args, _out| {
495 Ok(VmValue::String(Rc::from(
496 std::env::temp_dir().to_string_lossy().to_string().as_str(),
497 )))
498 });
499
500 vm.register_builtin("stat", |args, _out| {
501 let path = args.first().map(|a| a.display()).unwrap_or_default();
502 let metadata = std::fs::metadata(&path).map_err(|e| {
503 VmError::Thrown(VmValue::String(Rc::from(format!(
504 "Failed to stat {path}: {e}"
505 ))))
506 })?;
507 let mut info = BTreeMap::new();
508 info.insert("size".to_string(), VmValue::Int(metadata.len() as i64));
509 info.insert("is_file".to_string(), VmValue::Bool(metadata.is_file()));
510 info.insert("is_dir".to_string(), VmValue::Bool(metadata.is_dir()));
511 info.insert(
512 "readonly".to_string(),
513 VmValue::Bool(metadata.permissions().readonly()),
514 );
515 if let Ok(modified) = metadata.modified() {
516 if let Ok(dur) = modified.duration_since(std::time::UNIX_EPOCH) {
517 info.insert("modified".to_string(), VmValue::Float(dur.as_secs_f64()));
518 }
519 }
520 Ok(VmValue::Dict(Rc::new(info)))
521 });
522
523 vm.register_builtin("exec", |args, _out| {
528 if args.is_empty() {
529 return Err(VmError::Thrown(VmValue::String(Rc::from(
530 "exec: command is required",
531 ))));
532 }
533 let cmd = args[0].display();
534 let cmd_args: Vec<String> = args[1..].iter().map(|a| a.display()).collect();
535 let output = std::process::Command::new(&cmd)
536 .args(&cmd_args)
537 .output()
538 .map_err(|e| VmError::Thrown(VmValue::String(Rc::from(format!("exec failed: {e}")))))?;
539 Ok(vm_output_to_value(output))
540 });
541
542 vm.register_builtin("shell", |args, _out| {
543 let cmd = args.first().map(|a| a.display()).unwrap_or_default();
544 if cmd.is_empty() {
545 return Err(VmError::Thrown(VmValue::String(Rc::from(
546 "shell: command string is required",
547 ))));
548 }
549 let shell = if cfg!(target_os = "windows") {
550 "cmd"
551 } else {
552 "sh"
553 };
554 let flag = if cfg!(target_os = "windows") {
555 "/C"
556 } else {
557 "-c"
558 };
559 let output = std::process::Command::new(shell)
560 .arg(flag)
561 .arg(&cmd)
562 .output()
563 .map_err(|e| {
564 VmError::Thrown(VmValue::String(Rc::from(format!("shell failed: {e}"))))
565 })?;
566 Ok(vm_output_to_value(output))
567 });
568
569 vm.register_builtin("date_now", |_args, _out| {
574 use std::time::{SystemTime, UNIX_EPOCH};
575 let now = SystemTime::now()
576 .duration_since(UNIX_EPOCH)
577 .unwrap_or_default();
578 let total_secs = now.as_secs();
579 let (y, m, d, hour, minute, second, dow) = vm_civil_from_timestamp(total_secs);
580 let mut result = BTreeMap::new();
581 result.insert("year".to_string(), VmValue::Int(y));
582 result.insert("month".to_string(), VmValue::Int(m));
583 result.insert("day".to_string(), VmValue::Int(d));
584 result.insert("hour".to_string(), VmValue::Int(hour));
585 result.insert("minute".to_string(), VmValue::Int(minute));
586 result.insert("second".to_string(), VmValue::Int(second));
587 result.insert("weekday".to_string(), VmValue::Int(dow));
588 result.insert("timestamp".to_string(), VmValue::Float(now.as_secs_f64()));
589 Ok(VmValue::Dict(Rc::new(result)))
590 });
591
592 vm.register_builtin("date_format", |args, _out| {
593 let ts = match args.first() {
594 Some(VmValue::Float(f)) => *f,
595 Some(VmValue::Int(n)) => *n as f64,
596 Some(VmValue::Dict(map)) => map
597 .get("timestamp")
598 .and_then(|v| match v {
599 VmValue::Float(f) => Some(*f),
600 VmValue::Int(n) => Some(*n as f64),
601 _ => None,
602 })
603 .unwrap_or(0.0),
604 _ => 0.0,
605 };
606 let fmt = args
607 .get(1)
608 .map(|a| a.display())
609 .unwrap_or_else(|| "%Y-%m-%d %H:%M:%S".to_string());
610
611 let (y, m, d, hour, minute, second, _dow) = vm_civil_from_timestamp(ts as u64);
612
613 let result = fmt
614 .replace("%Y", &format!("{y:04}"))
615 .replace("%m", &format!("{m:02}"))
616 .replace("%d", &format!("{d:02}"))
617 .replace("%H", &format!("{hour:02}"))
618 .replace("%M", &format!("{minute:02}"))
619 .replace("%S", &format!("{second:02}"));
620
621 Ok(VmValue::String(Rc::from(result.as_str())))
622 });
623
624 vm.register_builtin("date_parse", |args, _out| {
625 let s = args.first().map(|a| a.display()).unwrap_or_default();
626 let parts: Vec<&str> = s.split(|c: char| !c.is_ascii_digit()).collect();
627 let parts: Vec<i64> = parts.iter().filter_map(|p| p.parse().ok()).collect();
628 if parts.len() < 3 {
629 return Err(VmError::Thrown(VmValue::String(Rc::from(format!(
630 "Cannot parse date: {s}"
631 )))));
632 }
633 let (y, m, d) = (parts[0], parts[1], parts[2]);
634 let hour = parts.get(3).copied().unwrap_or(0);
635 let minute = parts.get(4).copied().unwrap_or(0);
636 let second = parts.get(5).copied().unwrap_or(0);
637
638 let (y_adj, m_adj) = if m <= 2 {
639 (y - 1, (m + 9) as u64)
640 } else {
641 (y, (m - 3) as u64)
642 };
643 let era = if y_adj >= 0 { y_adj } else { y_adj - 399 } / 400;
644 let yoe = (y_adj - era * 400) as u64;
645 let doy = (153 * m_adj + 2) / 5 + d as u64 - 1;
646 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
647 let days = era * 146097 + doe as i64 - 719468;
648 let ts = days * 86400 + hour * 3600 + minute * 60 + second;
649 Ok(VmValue::Float(ts as f64))
650 });
651
652 vm.register_builtin("format", |args, _out| {
657 let template = args.first().map(|a| a.display()).unwrap_or_default();
658 let mut result = String::with_capacity(template.len());
659 let mut arg_iter = args.iter().skip(1);
660 let mut rest = template.as_str();
661 while let Some(pos) = rest.find("{}") {
662 result.push_str(&rest[..pos]);
663 if let Some(arg) = arg_iter.next() {
664 result.push_str(&arg.display());
665 } else {
666 result.push_str("{}");
667 }
668 rest = &rest[pos + 2..];
669 }
670 result.push_str(rest);
671 Ok(VmValue::String(Rc::from(result.as_str())))
672 });
673
674 vm.register_builtin("trim", |args, _out| {
679 let s = args.first().map(|a| a.display()).unwrap_or_default();
680 Ok(VmValue::String(Rc::from(s.trim())))
681 });
682
683 vm.register_builtin("lowercase", |args, _out| {
684 let s = args.first().map(|a| a.display()).unwrap_or_default();
685 Ok(VmValue::String(Rc::from(s.to_lowercase().as_str())))
686 });
687
688 vm.register_builtin("uppercase", |args, _out| {
689 let s = args.first().map(|a| a.display()).unwrap_or_default();
690 Ok(VmValue::String(Rc::from(s.to_uppercase().as_str())))
691 });
692
693 vm.register_builtin("split", |args, _out| {
694 let s = args.first().map(|a| a.display()).unwrap_or_default();
695 let sep = args
696 .get(1)
697 .map(|a| a.display())
698 .unwrap_or_else(|| " ".to_string());
699 let parts: Vec<VmValue> = s
700 .split(&sep)
701 .map(|p| VmValue::String(Rc::from(p)))
702 .collect();
703 Ok(VmValue::List(Rc::new(parts)))
704 });
705
706 vm.register_builtin("starts_with", |args, _out| {
707 let s = args.first().map(|a| a.display()).unwrap_or_default();
708 let prefix = args.get(1).map(|a| a.display()).unwrap_or_default();
709 Ok(VmValue::Bool(s.starts_with(&prefix)))
710 });
711
712 vm.register_builtin("ends_with", |args, _out| {
713 let s = args.first().map(|a| a.display()).unwrap_or_default();
714 let suffix = args.get(1).map(|a| a.display()).unwrap_or_default();
715 Ok(VmValue::Bool(s.ends_with(&suffix)))
716 });
717
718 vm.register_builtin("contains", |args, _out| {
719 match args.first().unwrap_or(&VmValue::Nil) {
720 VmValue::String(s) => {
721 let substr = args.get(1).map(|a| a.display()).unwrap_or_default();
722 Ok(VmValue::Bool(s.contains(&substr)))
723 }
724 VmValue::List(items) => {
725 let target = args.get(1).unwrap_or(&VmValue::Nil);
726 Ok(VmValue::Bool(
727 items.iter().any(|item| values_equal(item, target)),
728 ))
729 }
730 _ => Ok(VmValue::Bool(false)),
731 }
732 });
733
734 vm.register_builtin("replace", |args, _out| {
735 let s = args.first().map(|a| a.display()).unwrap_or_default();
736 let old = args.get(1).map(|a| a.display()).unwrap_or_default();
737 let new = args.get(2).map(|a| a.display()).unwrap_or_default();
738 Ok(VmValue::String(Rc::from(s.replace(&old, &new).as_str())))
739 });
740
741 vm.register_builtin("join", |args, _out| {
742 let sep = args.get(1).map(|a| a.display()).unwrap_or_default();
743 match args.first() {
744 Some(VmValue::List(items)) => {
745 let parts: Vec<String> = items.iter().map(|v| v.display()).collect();
746 Ok(VmValue::String(Rc::from(parts.join(&sep).as_str())))
747 }
748 _ => Ok(VmValue::String(Rc::from(""))),
749 }
750 });
751
752 vm.register_builtin("len", |args, _out| {
753 match args.first().unwrap_or(&VmValue::Nil) {
754 VmValue::String(s) => Ok(VmValue::Int(s.len() as i64)),
755 VmValue::List(items) => Ok(VmValue::Int(items.len() as i64)),
756 VmValue::Dict(map) => Ok(VmValue::Int(map.len() as i64)),
757 _ => Ok(VmValue::Int(0)),
758 }
759 });
760
761 vm.register_builtin("substring", |args, _out| {
762 let s = args.first().map(|a| a.display()).unwrap_or_default();
763 let start = args.get(1).and_then(|a| a.as_int()).unwrap_or(0) as usize;
764 let start = start.min(s.len());
765 match args.get(2).and_then(|a| a.as_int()) {
766 Some(length) => {
767 let length = (length as usize).min(s.len() - start);
768 Ok(VmValue::String(Rc::from(&s[start..start + length])))
769 }
770 None => Ok(VmValue::String(Rc::from(&s[start..]))),
771 }
772 });
773
774 vm.register_builtin("dirname", |args, _out| {
779 let path = args.first().map(|a| a.display()).unwrap_or_default();
780 let p = std::path::Path::new(&path);
781 match p.parent() {
782 Some(parent) => Ok(VmValue::String(Rc::from(parent.to_string_lossy().as_ref()))),
783 None => Ok(VmValue::String(Rc::from(""))),
784 }
785 });
786
787 vm.register_builtin("basename", |args, _out| {
788 let path = args.first().map(|a| a.display()).unwrap_or_default();
789 let p = std::path::Path::new(&path);
790 match p.file_name() {
791 Some(name) => Ok(VmValue::String(Rc::from(name.to_string_lossy().as_ref()))),
792 None => Ok(VmValue::String(Rc::from(""))),
793 }
794 });
795
796 vm.register_builtin("extname", |args, _out| {
797 let path = args.first().map(|a| a.display()).unwrap_or_default();
798 let p = std::path::Path::new(&path);
799 match p.extension() {
800 Some(ext) => Ok(VmValue::String(Rc::from(
801 format!(".{}", ext.to_string_lossy()).as_str(),
802 ))),
803 None => Ok(VmValue::String(Rc::from(""))),
804 }
805 });
806
807 vm.register_builtin("render", |args, _out| {
812 let path = args.first().map(|a| a.display()).unwrap_or_default();
813 let template = std::fs::read_to_string(&path).map_err(|e| {
814 VmError::Thrown(VmValue::String(Rc::from(format!(
815 "Failed to read template {path}: {e}"
816 ))))
817 })?;
818 if let Some(bindings) = args.get(1).and_then(|a| a.as_dict()) {
819 let mut result = template;
820 for (key, val) in bindings.iter() {
821 result = result.replace(&format!("{{{{{key}}}}}"), &val.display());
822 }
823 Ok(VmValue::String(Rc::from(result)))
824 } else {
825 Ok(VmValue::String(Rc::from(template)))
826 }
827 });
828
829 vm.register_builtin("log_debug", |args, out| {
834 vm_write_log("debug", 0, args, out);
835 Ok(VmValue::Nil)
836 });
837
838 vm.register_builtin("log_info", |args, out| {
839 vm_write_log("info", 1, args, out);
840 Ok(VmValue::Nil)
841 });
842
843 vm.register_builtin("log_warn", |args, out| {
844 vm_write_log("warn", 2, args, out);
845 Ok(VmValue::Nil)
846 });
847
848 vm.register_builtin("log_error", |args, out| {
849 vm_write_log("error", 3, args, out);
850 Ok(VmValue::Nil)
851 });
852
853 vm.register_builtin("log_set_level", |args, _out| {
854 let level_str = args.first().map(|a| a.display()).unwrap_or_default();
855 match vm_level_to_u8(&level_str) {
856 Some(n) => {
857 VM_MIN_LOG_LEVEL.store(n, Ordering::Relaxed);
858 Ok(VmValue::Nil)
859 }
860 None => Err(VmError::Thrown(VmValue::String(Rc::from(format!(
861 "log_set_level: invalid level '{}'. Expected debug, info, warn, or error",
862 level_str
863 ))))),
864 }
865 });
866
867 vm.register_builtin("trace_start", |args, _out| {
872 use rand::Rng;
873 let name = args.first().map(|a| a.display()).unwrap_or_default();
874 let trace_id = VM_TRACE_STACK.with(|stack| {
875 stack
876 .borrow()
877 .last()
878 .map(|t| t.trace_id.clone())
879 .unwrap_or_else(|| {
880 let val: u32 = rand::thread_rng().gen();
881 format!("{val:08x}")
882 })
883 });
884 let span_id = {
885 let val: u32 = rand::thread_rng().gen();
886 format!("{val:08x}")
887 };
888 let start_ms = std::time::SystemTime::now()
889 .duration_since(std::time::UNIX_EPOCH)
890 .unwrap_or_default()
891 .as_millis() as i64;
892
893 VM_TRACE_STACK.with(|stack| {
894 stack.borrow_mut().push(VmTraceContext {
895 trace_id: trace_id.clone(),
896 span_id: span_id.clone(),
897 });
898 });
899
900 let mut span = BTreeMap::new();
901 span.insert(
902 "trace_id".to_string(),
903 VmValue::String(Rc::from(trace_id.as_str())),
904 );
905 span.insert(
906 "span_id".to_string(),
907 VmValue::String(Rc::from(span_id.as_str())),
908 );
909 span.insert("name".to_string(), VmValue::String(Rc::from(name.as_str())));
910 span.insert("start_ms".to_string(), VmValue::Int(start_ms));
911 Ok(VmValue::Dict(Rc::new(span)))
912 });
913
914 vm.register_builtin("trace_end", |args, out| {
915 let span = match args.first() {
916 Some(VmValue::Dict(d)) => d,
917 _ => {
918 return Err(VmError::Thrown(VmValue::String(Rc::from(
919 "trace_end: argument must be a span dict from trace_start",
920 ))));
921 }
922 };
923
924 let end_ms = std::time::SystemTime::now()
925 .duration_since(std::time::UNIX_EPOCH)
926 .unwrap_or_default()
927 .as_millis() as i64;
928
929 let start_ms = span
930 .get("start_ms")
931 .and_then(|v| v.as_int())
932 .unwrap_or(end_ms);
933 let duration_ms = end_ms - start_ms;
934 let name = span.get("name").map(|v| v.display()).unwrap_or_default();
935 let trace_id = span
936 .get("trace_id")
937 .map(|v| v.display())
938 .unwrap_or_default();
939 let span_id = span.get("span_id").map(|v| v.display()).unwrap_or_default();
940
941 VM_TRACE_STACK.with(|stack| {
942 stack.borrow_mut().pop();
943 });
944
945 let level_num = 1_u8;
946 if level_num >= VM_MIN_LOG_LEVEL.load(Ordering::Relaxed) {
947 let mut fields = BTreeMap::new();
948 fields.insert(
949 "trace_id".to_string(),
950 VmValue::String(Rc::from(trace_id.as_str())),
951 );
952 fields.insert(
953 "span_id".to_string(),
954 VmValue::String(Rc::from(span_id.as_str())),
955 );
956 fields.insert("name".to_string(), VmValue::String(Rc::from(name.as_str())));
957 fields.insert("duration_ms".to_string(), VmValue::Int(duration_ms));
958 let line = vm_build_log_line("info", "span_end", Some(&fields));
959 out.push_str(&line);
960 }
961
962 Ok(VmValue::Nil)
963 });
964
965 vm.register_builtin("trace_id", |_args, _out| {
966 let id = VM_TRACE_STACK.with(|stack| stack.borrow().last().map(|t| t.trace_id.clone()));
967 match id {
968 Some(trace_id) => Ok(VmValue::String(Rc::from(trace_id.as_str()))),
969 None => Ok(VmValue::Nil),
970 }
971 });
972
973 vm.register_builtin("tool_registry", |_args, _out| {
978 let mut registry = BTreeMap::new();
979 registry.insert(
980 "_type".to_string(),
981 VmValue::String(Rc::from("tool_registry")),
982 );
983 registry.insert("tools".to_string(), VmValue::List(Rc::new(Vec::new())));
984 Ok(VmValue::Dict(Rc::new(registry)))
985 });
986
987 vm.register_builtin("tool_add", |args, _out| {
988 if args.len() < 4 {
989 return Err(VmError::Thrown(VmValue::String(Rc::from(
990 "tool_add: requires registry, name, description, and handler",
991 ))));
992 }
993
994 let registry = match &args[0] {
995 VmValue::Dict(map) => (**map).clone(),
996 _ => {
997 return Err(VmError::Thrown(VmValue::String(Rc::from(
998 "tool_add: first argument must be a tool registry",
999 ))));
1000 }
1001 };
1002
1003 match registry.get("_type") {
1004 Some(VmValue::String(t)) if &**t == "tool_registry" => {}
1005 _ => {
1006 return Err(VmError::Thrown(VmValue::String(Rc::from(
1007 "tool_add: first argument must be a tool registry",
1008 ))));
1009 }
1010 }
1011
1012 let name = args[1].display();
1013 let description = args[2].display();
1014 let handler = args[3].clone();
1015 let parameters = if args.len() > 4 {
1016 args[4].clone()
1017 } else {
1018 VmValue::Dict(Rc::new(BTreeMap::new()))
1019 };
1020
1021 let mut tool_entry = BTreeMap::new();
1022 tool_entry.insert("name".to_string(), VmValue::String(Rc::from(name.as_str())));
1023 tool_entry.insert(
1024 "description".to_string(),
1025 VmValue::String(Rc::from(description.as_str())),
1026 );
1027 tool_entry.insert("handler".to_string(), handler);
1028 tool_entry.insert("parameters".to_string(), parameters);
1029
1030 let mut tools: Vec<VmValue> = match registry.get("tools") {
1031 Some(VmValue::List(list)) => list
1032 .iter()
1033 .filter(|t| {
1034 if let VmValue::Dict(e) = t {
1035 e.get("name").map(|v| v.display()).as_deref() != Some(name.as_str())
1036 } else {
1037 true
1038 }
1039 })
1040 .cloned()
1041 .collect(),
1042 _ => Vec::new(),
1043 };
1044 tools.push(VmValue::Dict(Rc::new(tool_entry)));
1045
1046 let mut new_registry = registry;
1047 new_registry.insert("tools".to_string(), VmValue::List(Rc::new(tools)));
1048 Ok(VmValue::Dict(Rc::new(new_registry)))
1049 });
1050
1051 vm.register_builtin("tool_list", |args, _out| {
1052 let registry = match args.first() {
1053 Some(VmValue::Dict(map)) => map,
1054 _ => {
1055 return Err(VmError::Thrown(VmValue::String(Rc::from(
1056 "tool_list: requires a tool registry",
1057 ))));
1058 }
1059 };
1060 vm_validate_registry("tool_list", registry)?;
1061
1062 let tools = vm_get_tools(registry);
1063 let mut result = Vec::new();
1064 for tool in tools {
1065 if let VmValue::Dict(entry) = tool {
1066 let mut desc = BTreeMap::new();
1067 if let Some(name) = entry.get("name") {
1068 desc.insert("name".to_string(), name.clone());
1069 }
1070 if let Some(description) = entry.get("description") {
1071 desc.insert("description".to_string(), description.clone());
1072 }
1073 if let Some(parameters) = entry.get("parameters") {
1074 desc.insert("parameters".to_string(), parameters.clone());
1075 }
1076 result.push(VmValue::Dict(Rc::new(desc)));
1077 }
1078 }
1079 Ok(VmValue::List(Rc::new(result)))
1080 });
1081
1082 vm.register_builtin("tool_find", |args, _out| {
1083 if args.len() < 2 {
1084 return Err(VmError::Thrown(VmValue::String(Rc::from(
1085 "tool_find: requires registry and name",
1086 ))));
1087 }
1088
1089 let registry = match &args[0] {
1090 VmValue::Dict(map) => map,
1091 _ => {
1092 return Err(VmError::Thrown(VmValue::String(Rc::from(
1093 "tool_find: first argument must be a tool registry",
1094 ))));
1095 }
1096 };
1097 vm_validate_registry("tool_find", registry)?;
1098
1099 let target_name = args[1].display();
1100 let tools = vm_get_tools(registry);
1101
1102 for tool in tools {
1103 if let VmValue::Dict(entry) = tool {
1104 if let Some(VmValue::String(name)) = entry.get("name") {
1105 if &**name == target_name.as_str() {
1106 return Ok(tool.clone());
1107 }
1108 }
1109 }
1110 }
1111 Ok(VmValue::Nil)
1112 });
1113
1114 vm.register_builtin("tool_describe", |args, _out| {
1115 let registry = match args.first() {
1116 Some(VmValue::Dict(map)) => map,
1117 _ => {
1118 return Err(VmError::Thrown(VmValue::String(Rc::from(
1119 "tool_describe: requires a tool registry",
1120 ))));
1121 }
1122 };
1123 vm_validate_registry("tool_describe", registry)?;
1124
1125 let tools = vm_get_tools(registry);
1126
1127 if tools.is_empty() {
1128 return Ok(VmValue::String(Rc::from("Available tools:\n(none)")));
1129 }
1130
1131 let mut tool_infos: Vec<(String, String, String)> = Vec::new();
1132 for tool in tools {
1133 if let VmValue::Dict(entry) = tool {
1134 let name = entry.get("name").map(|v| v.display()).unwrap_or_default();
1135 let description = entry
1136 .get("description")
1137 .map(|v| v.display())
1138 .unwrap_or_default();
1139 let params_str = vm_format_parameters(entry.get("parameters"));
1140 tool_infos.push((name, params_str, description));
1141 }
1142 }
1143
1144 tool_infos.sort_by(|a, b| a.0.cmp(&b.0));
1145
1146 let mut lines = vec!["Available tools:".to_string()];
1147 for (name, params, desc) in &tool_infos {
1148 lines.push(format!("- {name}({params}): {desc}"));
1149 }
1150
1151 Ok(VmValue::String(Rc::from(lines.join("\n").as_str())))
1152 });
1153
1154 vm.register_builtin("tool_remove", |args, _out| {
1155 if args.len() < 2 {
1156 return Err(VmError::Thrown(VmValue::String(Rc::from(
1157 "tool_remove: requires registry and name",
1158 ))));
1159 }
1160
1161 let registry = match &args[0] {
1162 VmValue::Dict(map) => (**map).clone(),
1163 _ => {
1164 return Err(VmError::Thrown(VmValue::String(Rc::from(
1165 "tool_remove: first argument must be a tool registry",
1166 ))));
1167 }
1168 };
1169 vm_validate_registry("tool_remove", ®istry)?;
1170
1171 let target_name = args[1].display();
1172
1173 let tools = match registry.get("tools") {
1174 Some(VmValue::List(list)) => (**list).clone(),
1175 _ => Vec::new(),
1176 };
1177
1178 let filtered: Vec<VmValue> = tools
1179 .into_iter()
1180 .filter(|tool| {
1181 if let VmValue::Dict(entry) = tool {
1182 if let Some(VmValue::String(name)) = entry.get("name") {
1183 return &**name != target_name.as_str();
1184 }
1185 }
1186 true
1187 })
1188 .collect();
1189
1190 let mut new_registry = registry;
1191 new_registry.insert("tools".to_string(), VmValue::List(Rc::new(filtered)));
1192 Ok(VmValue::Dict(Rc::new(new_registry)))
1193 });
1194
1195 vm.register_builtin("tool_count", |args, _out| {
1196 let registry = match args.first() {
1197 Some(VmValue::Dict(map)) => map,
1198 _ => {
1199 return Err(VmError::Thrown(VmValue::String(Rc::from(
1200 "tool_count: requires a tool registry",
1201 ))));
1202 }
1203 };
1204 vm_validate_registry("tool_count", registry)?;
1205 let count = vm_get_tools(registry).len();
1206 Ok(VmValue::Int(count as i64))
1207 });
1208
1209 vm.register_builtin("tool_schema", |args, _out| {
1210 let registry = match args.first() {
1211 Some(VmValue::Dict(map)) => {
1212 vm_validate_registry("tool_schema", map)?;
1213 map
1214 }
1215 _ => {
1216 return Err(VmError::Thrown(VmValue::String(Rc::from(
1217 "tool_schema: requires a tool registry",
1218 ))));
1219 }
1220 };
1221
1222 let components = args.get(1).and_then(|v| v.as_dict()).cloned();
1223
1224 let tools = match registry.get("tools") {
1225 Some(VmValue::List(list)) => list,
1226 _ => return Ok(VmValue::Dict(Rc::new(vm_build_empty_schema()))),
1227 };
1228
1229 let mut tool_schemas = Vec::new();
1230 for tool in tools.iter() {
1231 if let VmValue::Dict(entry) = tool {
1232 let name = entry.get("name").map(|v| v.display()).unwrap_or_default();
1233 let description = entry
1234 .get("description")
1235 .map(|v| v.display())
1236 .unwrap_or_default();
1237
1238 let input_schema =
1239 vm_build_input_schema(entry.get("parameters"), components.as_ref());
1240
1241 let mut tool_def = BTreeMap::new();
1242 tool_def.insert("name".to_string(), VmValue::String(Rc::from(name.as_str())));
1243 tool_def.insert(
1244 "description".to_string(),
1245 VmValue::String(Rc::from(description.as_str())),
1246 );
1247 tool_def.insert("inputSchema".to_string(), input_schema);
1248 tool_schemas.push(VmValue::Dict(Rc::new(tool_def)));
1249 }
1250 }
1251
1252 let mut schema = BTreeMap::new();
1253 schema.insert(
1254 "schema_version".to_string(),
1255 VmValue::String(Rc::from("harn-tools/1.0")),
1256 );
1257
1258 if let Some(comps) = &components {
1259 let mut comp_wrapper = BTreeMap::new();
1260 comp_wrapper.insert("schemas".to_string(), VmValue::Dict(Rc::new(comps.clone())));
1261 schema.insert(
1262 "components".to_string(),
1263 VmValue::Dict(Rc::new(comp_wrapper)),
1264 );
1265 }
1266
1267 schema.insert("tools".to_string(), VmValue::List(Rc::new(tool_schemas)));
1268 Ok(VmValue::Dict(Rc::new(schema)))
1269 });
1270
1271 vm.register_builtin("tool_parse_call", |args, _out| {
1272 let text = args.first().map(|a| a.display()).unwrap_or_default();
1273
1274 let mut results = Vec::new();
1275 let mut search_from = 0;
1276
1277 while let Some(start) = text[search_from..].find("<tool_call>") {
1278 let abs_start = search_from + start + "<tool_call>".len();
1279 if let Some(end) = text[abs_start..].find("</tool_call>") {
1280 let json_str = text[abs_start..abs_start + end].trim();
1281 if let Ok(jv) = serde_json::from_str::<serde_json::Value>(json_str) {
1282 results.push(json_to_vm_value(&jv));
1283 }
1284 search_from = abs_start + end + "</tool_call>".len();
1285 } else {
1286 break;
1287 }
1288 }
1289
1290 Ok(VmValue::List(Rc::new(results)))
1291 });
1292
1293 vm.register_builtin("tool_format_result", |args, _out| {
1294 if args.len() < 2 {
1295 return Err(VmError::Thrown(VmValue::String(Rc::from(
1296 "tool_format_result: requires name and result",
1297 ))));
1298 }
1299 let name = args[0].display();
1300 let result = args[1].display();
1301
1302 let json_name = vm_escape_json_str(&name);
1303 let json_result = vm_escape_json_str(&result);
1304 Ok(VmValue::String(Rc::from(
1305 format!(
1306 "<tool_result>{{\"name\": \"{json_name}\", \"result\": \"{json_result}\"}}</tool_result>"
1307 )
1308 .as_str(),
1309 )))
1310 });
1311
1312 vm.register_builtin("tool_prompt", |args, _out| {
1313 let registry = match args.first() {
1314 Some(VmValue::Dict(map)) => {
1315 vm_validate_registry("tool_prompt", map)?;
1316 map
1317 }
1318 _ => {
1319 return Err(VmError::Thrown(VmValue::String(Rc::from(
1320 "tool_prompt: requires a tool registry",
1321 ))));
1322 }
1323 };
1324
1325 let tools = match registry.get("tools") {
1326 Some(VmValue::List(list)) => list,
1327 _ => {
1328 return Ok(VmValue::String(Rc::from("No tools are available.")));
1329 }
1330 };
1331
1332 if tools.is_empty() {
1333 return Ok(VmValue::String(Rc::from("No tools are available.")));
1334 }
1335
1336 let mut prompt = String::from("# Available Tools\n\n");
1337 prompt.push_str("You have access to the following tools. To use a tool, output a tool call in this exact format:\n\n");
1338 prompt.push_str("<tool_call>{\"name\": \"tool_name\", \"arguments\": {\"param\": \"value\"}}</tool_call>\n\n");
1339 prompt.push_str("You may make multiple tool calls in a single response. Wait for tool results before proceeding.\n\n");
1340 prompt.push_str("## Tools\n\n");
1341
1342 let mut tool_infos: Vec<(&BTreeMap<String, VmValue>, String)> = Vec::new();
1343 for tool in tools.iter() {
1344 if let VmValue::Dict(entry) = tool {
1345 let name = entry.get("name").map(|v| v.display()).unwrap_or_default();
1346 tool_infos.push((entry, name));
1347 }
1348 }
1349 tool_infos.sort_by(|a, b| a.1.cmp(&b.1));
1350
1351 for (entry, name) in &tool_infos {
1352 let description = entry
1353 .get("description")
1354 .map(|v| v.display())
1355 .unwrap_or_default();
1356 let params_str = vm_format_parameters(entry.get("parameters"));
1357
1358 prompt.push_str(&format!("### {name}\n"));
1359 prompt.push_str(&format!("{description}\n"));
1360 if !params_str.is_empty() {
1361 prompt.push_str(&format!("Parameters: {params_str}\n"));
1362 }
1363 prompt.push('\n');
1364 }
1365
1366 Ok(VmValue::String(Rc::from(prompt.trim_end())))
1367 });
1368
1369 vm.register_builtin("channel", |args, _out| {
1374 let name = args
1375 .first()
1376 .map(|a| a.display())
1377 .unwrap_or_else(|| "default".to_string());
1378 let capacity = args.get(1).and_then(|a| a.as_int()).unwrap_or(256) as usize;
1379 let capacity = capacity.max(1);
1380 let (tx, rx) = tokio::sync::mpsc::channel(capacity);
1381 #[allow(clippy::arc_with_non_send_sync)]
1382 Ok(VmValue::Channel(VmChannelHandle {
1383 name,
1384 sender: Arc::new(tx),
1385 receiver: Arc::new(tokio::sync::Mutex::new(rx)),
1386 closed: Arc::new(AtomicBool::new(false)),
1387 }))
1388 });
1389
1390 vm.register_builtin("close_channel", |args, _out| {
1391 if args.is_empty() {
1392 return Err(VmError::Thrown(VmValue::String(Rc::from(
1393 "close_channel: requires a channel",
1394 ))));
1395 }
1396 if let VmValue::Channel(ch) = &args[0] {
1397 ch.closed.store(true, Ordering::SeqCst);
1398 Ok(VmValue::Nil)
1399 } else {
1400 Err(VmError::Thrown(VmValue::String(Rc::from(
1401 "close_channel: first argument must be a channel",
1402 ))))
1403 }
1404 });
1405
1406 vm.register_builtin("try_receive", |args, _out| {
1407 if args.is_empty() {
1408 return Err(VmError::Thrown(VmValue::String(Rc::from(
1409 "try_receive: requires a channel",
1410 ))));
1411 }
1412 if let VmValue::Channel(ch) = &args[0] {
1413 match ch.receiver.try_lock() {
1414 Ok(mut rx) => match rx.try_recv() {
1415 Ok(val) => Ok(val),
1416 Err(_) => Ok(VmValue::Nil),
1417 },
1418 Err(_) => Ok(VmValue::Nil),
1419 }
1420 } else {
1421 Err(VmError::Thrown(VmValue::String(Rc::from(
1422 "try_receive: first argument must be a channel",
1423 ))))
1424 }
1425 });
1426
1427 vm.register_builtin("atomic", |args, _out| {
1432 let initial = match args.first() {
1433 Some(VmValue::Int(n)) => *n,
1434 Some(VmValue::Float(f)) => *f as i64,
1435 Some(VmValue::Bool(b)) => {
1436 if *b {
1437 1
1438 } else {
1439 0
1440 }
1441 }
1442 _ => 0,
1443 };
1444 Ok(VmValue::Atomic(VmAtomicHandle {
1445 value: Arc::new(AtomicI64::new(initial)),
1446 }))
1447 });
1448
1449 vm.register_builtin("atomic_get", |args, _out| {
1450 if let Some(VmValue::Atomic(a)) = args.first() {
1451 Ok(VmValue::Int(a.value.load(Ordering::SeqCst)))
1452 } else {
1453 Ok(VmValue::Nil)
1454 }
1455 });
1456
1457 vm.register_builtin("atomic_set", |args, _out| {
1458 if args.len() >= 2 {
1459 if let (VmValue::Atomic(a), Some(val)) = (&args[0], args[1].as_int()) {
1460 let old = a.value.swap(val, Ordering::SeqCst);
1461 return Ok(VmValue::Int(old));
1462 }
1463 }
1464 Ok(VmValue::Nil)
1465 });
1466
1467 vm.register_builtin("atomic_add", |args, _out| {
1468 if args.len() >= 2 {
1469 if let (VmValue::Atomic(a), Some(delta)) = (&args[0], args[1].as_int()) {
1470 let prev = a.value.fetch_add(delta, Ordering::SeqCst);
1471 return Ok(VmValue::Int(prev));
1472 }
1473 }
1474 Ok(VmValue::Nil)
1475 });
1476
1477 vm.register_builtin("atomic_cas", |args, _out| {
1478 if args.len() >= 3 {
1479 if let (VmValue::Atomic(a), Some(expected), Some(new_val)) =
1480 (&args[0], args[1].as_int(), args[2].as_int())
1481 {
1482 let result =
1483 a.value
1484 .compare_exchange(expected, new_val, Ordering::SeqCst, Ordering::SeqCst);
1485 return Ok(VmValue::Bool(result.is_ok()));
1486 }
1487 }
1488 Ok(VmValue::Bool(false))
1489 });
1490
1491 vm.register_async_builtin("sleep", |args| async move {
1497 let ms = match args.first() {
1498 Some(VmValue::Duration(ms)) => *ms,
1499 Some(VmValue::Int(n)) => *n as u64,
1500 _ => 0,
1501 };
1502 if ms > 0 {
1503 tokio::time::sleep(tokio::time::Duration::from_millis(ms)).await;
1504 }
1505 Ok(VmValue::Nil)
1506 });
1507
1508 vm.register_async_builtin("send", |args| async move {
1510 if args.len() < 2 {
1511 return Err(VmError::Thrown(VmValue::String(Rc::from(
1512 "send: requires channel and value",
1513 ))));
1514 }
1515 if let VmValue::Channel(ch) = &args[0] {
1516 if ch.closed.load(Ordering::SeqCst) {
1517 return Ok(VmValue::Bool(false));
1518 }
1519 let val = args[1].clone();
1520 match ch.sender.send(val).await {
1521 Ok(()) => Ok(VmValue::Bool(true)),
1522 Err(_) => Ok(VmValue::Bool(false)),
1523 }
1524 } else {
1525 Err(VmError::Thrown(VmValue::String(Rc::from(
1526 "send: first argument must be a channel",
1527 ))))
1528 }
1529 });
1530
1531 vm.register_async_builtin("receive", |args| async move {
1533 if args.is_empty() {
1534 return Err(VmError::Thrown(VmValue::String(Rc::from(
1535 "receive: requires a channel",
1536 ))));
1537 }
1538 if let VmValue::Channel(ch) = &args[0] {
1539 if ch.closed.load(Ordering::SeqCst) {
1540 let mut rx = ch.receiver.lock().await;
1541 return match rx.try_recv() {
1542 Ok(val) => Ok(val),
1543 Err(_) => Ok(VmValue::Nil),
1544 };
1545 }
1546 let mut rx = ch.receiver.lock().await;
1547 match rx.recv().await {
1548 Some(val) => Ok(val),
1549 None => Ok(VmValue::Nil),
1550 }
1551 } else {
1552 Err(VmError::Thrown(VmValue::String(Rc::from(
1553 "receive: first argument must be a channel",
1554 ))))
1555 }
1556 });
1557
1558 vm.register_async_builtin("select", |args| async move {
1560 if args.is_empty() {
1561 return Err(VmError::Thrown(VmValue::String(Rc::from(
1562 "select: requires at least one channel",
1563 ))));
1564 }
1565 for arg in &args {
1566 if !matches!(arg, VmValue::Channel(_)) {
1567 return Err(VmError::Thrown(VmValue::String(Rc::from(
1568 "select: all arguments must be channels",
1569 ))));
1570 }
1571 }
1572 loop {
1573 let (found, all_closed) = try_poll_channels(&args);
1574 if let Some((i, val, name)) = found {
1575 return Ok(select_result(i, val, &name));
1576 }
1577 if all_closed {
1578 return Ok(select_none());
1579 }
1580 tokio::task::yield_now().await;
1581 }
1582 });
1583
1584 vm.register_async_builtin("__select_timeout", |args| async move {
1586 if args.len() < 2 {
1587 return Err(VmError::Thrown(VmValue::String(Rc::from(
1588 "__select_timeout: requires channel list and timeout",
1589 ))));
1590 }
1591 let channels = match &args[0] {
1592 VmValue::List(items) => (**items).clone(),
1593 _ => {
1594 return Err(VmError::Thrown(VmValue::String(Rc::from(
1595 "__select_timeout: first argument must be a list of channels",
1596 ))));
1597 }
1598 };
1599 let timeout_ms = match &args[1] {
1600 VmValue::Int(n) => (*n).max(0) as u64,
1601 VmValue::Duration(ms) => *ms,
1602 _ => 5000,
1603 };
1604 let deadline = tokio::time::Instant::now()
1605 + tokio::time::Duration::from_millis(timeout_ms);
1606 loop {
1607 let (found, all_closed) = try_poll_channels(&channels);
1608 if let Some((i, val, name)) = found {
1609 return Ok(select_result(i, val, &name));
1610 }
1611 if all_closed || tokio::time::Instant::now() >= deadline {
1612 return Ok(select_none());
1613 }
1614 tokio::task::yield_now().await;
1615 }
1616 });
1617
1618 vm.register_async_builtin("__select_try", |args| async move {
1620 if args.is_empty() {
1621 return Err(VmError::Thrown(VmValue::String(Rc::from(
1622 "__select_try: requires channel list",
1623 ))));
1624 }
1625 let channels = match &args[0] {
1626 VmValue::List(items) => (**items).clone(),
1627 _ => {
1628 return Err(VmError::Thrown(VmValue::String(Rc::from(
1629 "__select_try: first argument must be a list of channels",
1630 ))));
1631 }
1632 };
1633 let (found, _) = try_poll_channels(&channels);
1634 if let Some((i, val, name)) = found {
1635 Ok(select_result(i, val, &name))
1636 } else {
1637 Ok(select_none())
1638 }
1639 });
1640
1641 vm.register_async_builtin("__select_list", |args| async move {
1643 if args.is_empty() {
1644 return Err(VmError::Thrown(VmValue::String(Rc::from(
1645 "__select_list: requires channel list",
1646 ))));
1647 }
1648 let channels = match &args[0] {
1649 VmValue::List(items) => (**items).clone(),
1650 _ => {
1651 return Err(VmError::Thrown(VmValue::String(Rc::from(
1652 "__select_list: first argument must be a list of channels",
1653 ))));
1654 }
1655 };
1656 loop {
1657 let (found, all_closed) = try_poll_channels(&channels);
1658 if let Some((i, val, name)) = found {
1659 return Ok(select_result(i, val, &name));
1660 }
1661 if all_closed {
1662 return Ok(select_none());
1663 }
1664 tokio::task::yield_now().await;
1665 }
1666 });
1667
1668 vm.register_builtin("json_validate", |args, _out| {
1673 if args.len() < 2 {
1674 return Err(VmError::Thrown(VmValue::String(Rc::from(
1675 "json_validate requires 2 arguments: data and schema",
1676 ))));
1677 }
1678 let data = &args[0];
1679 let schema = &args[1];
1680 let schema_dict = match schema.as_dict() {
1681 Some(d) => d,
1682 None => {
1683 return Err(VmError::Thrown(VmValue::String(Rc::from(
1684 "json_validate: schema must be a dict",
1685 ))));
1686 }
1687 };
1688 let mut errors = Vec::new();
1689 validate_value(data, schema_dict, "", &mut errors);
1690 if errors.is_empty() {
1691 Ok(VmValue::Bool(true))
1692 } else {
1693 Err(VmError::Thrown(VmValue::String(Rc::from(
1694 errors.join("; "),
1695 ))))
1696 }
1697 });
1698
1699 vm.register_builtin("json_extract", |args, _out| {
1700 if args.is_empty() {
1701 return Err(VmError::Thrown(VmValue::String(Rc::from(
1702 "json_extract requires at least 1 argument: text",
1703 ))));
1704 }
1705 let text = args[0].display();
1706 let key = args.get(1).map(|a| a.display());
1707
1708 let json_str = extract_json_from_text(&text);
1710 let parsed = match serde_json::from_str::<serde_json::Value>(&json_str) {
1711 Ok(jv) => json_to_vm_value(&jv),
1712 Err(e) => {
1713 return Err(VmError::Thrown(VmValue::String(Rc::from(format!(
1714 "json_extract: failed to parse JSON: {e}"
1715 )))));
1716 }
1717 };
1718
1719 match key {
1720 Some(k) => match &parsed {
1721 VmValue::Dict(map) => match map.get(&k) {
1722 Some(val) => Ok(val.clone()),
1723 None => Err(VmError::Thrown(VmValue::String(Rc::from(format!(
1724 "json_extract: key '{}' not found",
1725 k
1726 ))))),
1727 },
1728 _ => Err(VmError::Thrown(VmValue::String(Rc::from(
1729 "json_extract: parsed value is not a dict, cannot extract key",
1730 )))),
1731 },
1732 None => Ok(parsed),
1733 }
1734 });
1735
1736 vm.register_builtin("__assert_dict", |args, _out| {
1745 let val = args.first().cloned().unwrap_or(VmValue::Nil);
1746 if matches!(val, VmValue::Dict(_)) {
1747 Ok(VmValue::Nil)
1748 } else {
1749 Err(VmError::TypeError(format!(
1750 "cannot destructure {} with {{...}} pattern — expected dict",
1751 val.type_name()
1752 )))
1753 }
1754 });
1755
1756 vm.register_builtin("__assert_list", |args, _out| {
1757 let val = args.first().cloned().unwrap_or(VmValue::Nil);
1758 if matches!(val, VmValue::List(_)) {
1759 Ok(VmValue::Nil)
1760 } else {
1761 Err(VmError::TypeError(format!(
1762 "cannot destructure {} with [...] pattern — expected list",
1763 val.type_name()
1764 )))
1765 }
1766 });
1767
1768 vm.register_builtin("__dict_rest", |args, _out| {
1769 let dict = args.first().cloned().unwrap_or(VmValue::Nil);
1771 let keys_list = args.get(1).cloned().unwrap_or(VmValue::Nil);
1772 if let VmValue::Dict(map) = dict {
1773 let exclude: std::collections::HashSet<String> = match keys_list {
1774 VmValue::List(items) => items
1775 .iter()
1776 .filter_map(|v| {
1777 if let VmValue::String(s) = v {
1778 Some(s.to_string())
1779 } else {
1780 None
1781 }
1782 })
1783 .collect(),
1784 _ => std::collections::HashSet::new(),
1785 };
1786 let rest: BTreeMap<String, VmValue> = map
1787 .iter()
1788 .filter(|(k, _)| !exclude.contains(k.as_str()))
1789 .map(|(k, v)| (k.clone(), v.clone()))
1790 .collect();
1791 Ok(VmValue::Dict(Rc::new(rest)))
1792 } else {
1793 Ok(VmValue::Nil)
1794 }
1795 });
1796
1797 register_http_builtins(vm);
1798 register_llm_builtins(vm);
1799 register_mcp_builtins(vm);
1800}
1801
1802pub(crate) fn escape_json_string_vm(s: &str) -> String {
1807 let mut out = String::with_capacity(s.len() + 2);
1808 out.push('"');
1809 for ch in s.chars() {
1810 match ch {
1811 '"' => out.push_str("\\\""),
1812 '\\' => out.push_str("\\\\"),
1813 '\n' => out.push_str("\\n"),
1814 '\r' => out.push_str("\\r"),
1815 '\t' => out.push_str("\\t"),
1816 c if c.is_control() => {
1817 out.push_str(&format!("\\u{:04x}", c as u32));
1818 }
1819 c => out.push(c),
1820 }
1821 }
1822 out.push('"');
1823 out
1824}
1825
1826pub(crate) fn vm_value_to_json(val: &VmValue) -> String {
1827 match val {
1828 VmValue::String(s) => escape_json_string_vm(s),
1829 VmValue::Int(n) => n.to_string(),
1830 VmValue::Float(n) => n.to_string(),
1831 VmValue::Bool(b) => b.to_string(),
1832 VmValue::Nil => "null".to_string(),
1833 VmValue::List(items) => {
1834 let inner: Vec<String> = items.iter().map(vm_value_to_json).collect();
1835 format!("[{}]", inner.join(","))
1836 }
1837 VmValue::Dict(map) => {
1838 let inner: Vec<String> = map
1839 .iter()
1840 .map(|(k, v)| format!("{}:{}", escape_json_string_vm(k), vm_value_to_json(v)))
1841 .collect();
1842 format!("{{{}}}", inner.join(","))
1843 }
1844 _ => "null".to_string(),
1845 }
1846}
1847
1848pub(crate) fn json_to_vm_value(jv: &serde_json::Value) -> VmValue {
1849 match jv {
1850 serde_json::Value::Null => VmValue::Nil,
1851 serde_json::Value::Bool(b) => VmValue::Bool(*b),
1852 serde_json::Value::Number(n) => {
1853 if let Some(i) = n.as_i64() {
1854 VmValue::Int(i)
1855 } else {
1856 VmValue::Float(n.as_f64().unwrap_or(0.0))
1857 }
1858 }
1859 serde_json::Value::String(s) => VmValue::String(Rc::from(s.as_str())),
1860 serde_json::Value::Array(arr) => {
1861 VmValue::List(Rc::new(arr.iter().map(json_to_vm_value).collect()))
1862 }
1863 serde_json::Value::Object(map) => {
1864 let mut m = BTreeMap::new();
1865 for (k, v) in map {
1866 m.insert(k.clone(), json_to_vm_value(v));
1867 }
1868 VmValue::Dict(Rc::new(m))
1869 }
1870 }
1871}
1872
1873fn validate_value(
1878 value: &VmValue,
1879 schema: &BTreeMap<String, VmValue>,
1880 path: &str,
1881 errors: &mut Vec<String>,
1882) {
1883 if let Some(VmValue::String(expected_type)) = schema.get("type") {
1885 let actual_type = value.type_name();
1886 let type_str: &str = expected_type;
1887 if type_str != "any" && actual_type != type_str {
1888 let location = if path.is_empty() {
1889 "root".to_string()
1890 } else {
1891 path.to_string()
1892 };
1893 errors.push(format!(
1894 "at {}: expected type '{}', got '{}'",
1895 location, type_str, actual_type
1896 ));
1897 return; }
1899 }
1900
1901 if let Some(VmValue::List(required_keys)) = schema.get("required") {
1903 if let VmValue::Dict(map) = value {
1904 for key_val in required_keys.iter() {
1905 let key = key_val.display();
1906 if !map.contains_key(&key) {
1907 let location = if path.is_empty() {
1908 "root".to_string()
1909 } else {
1910 path.to_string()
1911 };
1912 errors.push(format!("at {}: missing required key '{}'", location, key));
1913 }
1914 }
1915 }
1916 }
1917
1918 if let Some(VmValue::Dict(prop_schemas)) = schema.get("properties") {
1920 if let VmValue::Dict(map) = value {
1921 for (key, prop_schema) in prop_schemas.iter() {
1922 if let Some(prop_value) = map.get(key) {
1923 if let Some(prop_schema_dict) = prop_schema.as_dict() {
1924 let child_path = if path.is_empty() {
1925 key.clone()
1926 } else {
1927 format!("{}.{}", path, key)
1928 };
1929 validate_value(prop_value, prop_schema_dict, &child_path, errors);
1930 }
1931 }
1932 }
1933 }
1934 }
1935
1936 if let Some(VmValue::Dict(item_schema)) = schema.get("items") {
1938 if let VmValue::List(items) = value {
1939 for (i, item) in items.iter().enumerate() {
1940 let child_path = if path.is_empty() {
1941 format!("[{}]", i)
1942 } else {
1943 format!("{}[{}]", path, i)
1944 };
1945 validate_value(item, item_schema, &child_path, errors);
1946 }
1947 }
1948 }
1949}
1950
1951fn extract_json_from_text(text: &str) -> String {
1956 let trimmed = text.trim();
1957
1958 if let Some(start) = trimmed.find("```") {
1960 let after_backticks = &trimmed[start + 3..];
1961 let content_start = if let Some(nl) = after_backticks.find('\n') {
1963 nl + 1
1964 } else {
1965 0
1966 };
1967 let content = &after_backticks[content_start..];
1968 if let Some(end) = content.find("```") {
1969 return content[..end].trim().to_string();
1970 }
1971 }
1972
1973 if let Some(obj_start) = trimmed.find('{') {
1976 if let Some(obj_end) = trimmed.rfind('}') {
1977 if obj_end > obj_start {
1978 return trimmed[obj_start..=obj_end].to_string();
1979 }
1980 }
1981 }
1982 if let Some(arr_start) = trimmed.find('[') {
1983 if let Some(arr_end) = trimmed.rfind(']') {
1984 if arr_end > arr_start {
1985 return trimmed[arr_start..=arr_end].to_string();
1986 }
1987 }
1988 }
1989
1990 trimmed.to_string()
1992}
1993
1994fn vm_output_to_value(output: std::process::Output) -> VmValue {
1999 let mut result = BTreeMap::new();
2000 result.insert(
2001 "stdout".to_string(),
2002 VmValue::String(Rc::from(
2003 String::from_utf8_lossy(&output.stdout).to_string().as_str(),
2004 )),
2005 );
2006 result.insert(
2007 "stderr".to_string(),
2008 VmValue::String(Rc::from(
2009 String::from_utf8_lossy(&output.stderr).to_string().as_str(),
2010 )),
2011 );
2012 result.insert(
2013 "status".to_string(),
2014 VmValue::Int(output.status.code().unwrap_or(-1) as i64),
2015 );
2016 result.insert(
2017 "success".to_string(),
2018 VmValue::Bool(output.status.success()),
2019 );
2020 VmValue::Dict(Rc::new(result))
2021}
2022
2023fn vm_civil_from_timestamp(total_secs: u64) -> (i64, i64, i64, i64, i64, i64, i64) {
2028 let days = total_secs / 86400;
2029 let time_of_day = total_secs % 86400;
2030 let hour = (time_of_day / 3600) as i64;
2031 let minute = ((time_of_day % 3600) / 60) as i64;
2032 let second = (time_of_day % 60) as i64;
2033
2034 let z = days as i64 + 719468;
2035 let era = if z >= 0 { z } else { z - 146096 } / 146097;
2036 let doe = (z - era * 146097) as u64;
2037 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2038 let y = yoe as i64 + era * 400;
2039 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2040 let mp = (5 * doy + 2) / 153;
2041 let d = (doy - (153 * mp + 2) / 5 + 1) as i64;
2042 let m = if mp < 10 { mp + 3 } else { mp - 9 } as i64;
2043 let y = if m <= 2 { y + 1 } else { y };
2044 let dow = ((days + 4) % 7) as i64;
2045
2046 (y, m, d, hour, minute, second, dow)
2047}
2048
2049pub(crate) static VM_MIN_LOG_LEVEL: AtomicU8 = AtomicU8::new(0);
2054
2055#[derive(Clone)]
2056pub(crate) struct VmTraceContext {
2057 pub(crate) trace_id: String,
2058 pub(crate) span_id: String,
2059}
2060
2061thread_local! {
2062 pub(crate) static VM_TRACE_STACK: std::cell::RefCell<Vec<VmTraceContext>> = const { std::cell::RefCell::new(Vec::new()) };
2063}
2064
2065fn vm_level_to_u8(level: &str) -> Option<u8> {
2066 match level {
2067 "debug" => Some(0),
2068 "info" => Some(1),
2069 "warn" => Some(2),
2070 "error" => Some(3),
2071 _ => None,
2072 }
2073}
2074
2075fn vm_format_timestamp_utc() -> String {
2076 let now = std::time::SystemTime::now()
2077 .duration_since(std::time::UNIX_EPOCH)
2078 .unwrap_or_default();
2079 let total_secs = now.as_secs();
2080 let millis = now.subsec_millis();
2081
2082 let days = total_secs / 86400;
2083 let time_of_day = total_secs % 86400;
2084 let hour = time_of_day / 3600;
2085 let minute = (time_of_day % 3600) / 60;
2086 let second = time_of_day % 60;
2087
2088 let z = days as i64 + 719468;
2089 let era = if z >= 0 { z } else { z - 146096 } / 146097;
2090 let doe = (z - era * 146097) as u64;
2091 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
2092 let y = yoe as i64 + era * 400;
2093 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
2094 let mp = (5 * doy + 2) / 153;
2095 let d = doy - (153 * mp + 2) / 5 + 1;
2096 let m = if mp < 10 { mp + 3 } else { mp - 9 };
2097 let y = if m <= 2 { y + 1 } else { y };
2098
2099 format!("{y:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z")
2100}
2101
2102pub(crate) fn vm_escape_json_str(s: &str) -> String {
2103 let mut out = String::with_capacity(s.len());
2104 for ch in s.chars() {
2105 match ch {
2106 '"' => out.push_str("\\\""),
2107 '\\' => out.push_str("\\\\"),
2108 '\n' => out.push_str("\\n"),
2109 '\r' => out.push_str("\\r"),
2110 '\t' => out.push_str("\\t"),
2111 c if c.is_control() => {
2112 out.push_str(&format!("\\u{:04x}", c as u32));
2113 }
2114 c => out.push(c),
2115 }
2116 }
2117 out
2118}
2119
2120fn vm_escape_json_str_quoted(s: &str) -> String {
2121 let mut out = String::with_capacity(s.len() + 2);
2122 out.push('"');
2123 out.push_str(&vm_escape_json_str(s));
2124 out.push('"');
2125 out
2126}
2127
2128fn vm_value_to_json_fragment(val: &VmValue) -> String {
2129 match val {
2130 VmValue::String(s) => vm_escape_json_str_quoted(s),
2131 VmValue::Int(n) => n.to_string(),
2132 VmValue::Float(n) => {
2133 if n.is_finite() {
2134 n.to_string()
2135 } else {
2136 "null".to_string()
2137 }
2138 }
2139 VmValue::Bool(b) => b.to_string(),
2140 VmValue::Nil => "null".to_string(),
2141 _ => vm_escape_json_str_quoted(&val.display()),
2142 }
2143}
2144
2145fn vm_build_log_line(level: &str, msg: &str, fields: Option<&BTreeMap<String, VmValue>>) -> String {
2146 let ts = vm_format_timestamp_utc();
2147 let mut parts: Vec<String> = Vec::new();
2148 parts.push(format!("\"ts\":{}", vm_escape_json_str_quoted(&ts)));
2149 parts.push(format!("\"level\":{}", vm_escape_json_str_quoted(level)));
2150 parts.push(format!("\"msg\":{}", vm_escape_json_str_quoted(msg)));
2151
2152 VM_TRACE_STACK.with(|stack| {
2153 if let Some(trace) = stack.borrow().last() {
2154 parts.push(format!(
2155 "\"trace_id\":{}",
2156 vm_escape_json_str_quoted(&trace.trace_id)
2157 ));
2158 parts.push(format!(
2159 "\"span_id\":{}",
2160 vm_escape_json_str_quoted(&trace.span_id)
2161 ));
2162 }
2163 });
2164
2165 if let Some(dict) = fields {
2166 for (k, v) in dict {
2167 parts.push(format!(
2168 "{}:{}",
2169 vm_escape_json_str_quoted(k),
2170 vm_value_to_json_fragment(v)
2171 ));
2172 }
2173 }
2174
2175 format!("{{{}}}\n", parts.join(","))
2176}
2177
2178fn vm_write_log(level: &str, level_num: u8, args: &[VmValue], out: &mut String) {
2179 if level_num < VM_MIN_LOG_LEVEL.load(Ordering::Relaxed) {
2180 return;
2181 }
2182 let msg = args.first().map(|a| a.display()).unwrap_or_default();
2183 let fields = args.get(1).and_then(|v| {
2184 if let VmValue::Dict(d) = v {
2185 Some(&**d)
2186 } else {
2187 None
2188 }
2189 });
2190 let line = vm_build_log_line(level, &msg, fields);
2191 out.push_str(&line);
2192}
2193
2194fn vm_validate_registry(name: &str, dict: &BTreeMap<String, VmValue>) -> Result<(), VmError> {
2199 match dict.get("_type") {
2200 Some(VmValue::String(t)) if &**t == "tool_registry" => Ok(()),
2201 _ => Err(VmError::Thrown(VmValue::String(Rc::from(format!(
2202 "{name}: argument must be a tool registry (created with tool_registry())"
2203 ))))),
2204 }
2205}
2206
2207fn vm_get_tools(dict: &BTreeMap<String, VmValue>) -> &[VmValue] {
2208 match dict.get("tools") {
2209 Some(VmValue::List(list)) => list,
2210 _ => &[],
2211 }
2212}
2213
2214fn vm_format_parameters(params: Option<&VmValue>) -> String {
2215 match params {
2216 Some(VmValue::Dict(map)) if !map.is_empty() => {
2217 let mut pairs: Vec<(String, String)> =
2218 map.iter().map(|(k, v)| (k.clone(), v.display())).collect();
2219 pairs.sort_by(|a, b| a.0.cmp(&b.0));
2220 pairs
2221 .iter()
2222 .map(|(k, v)| format!("{k}: {v}"))
2223 .collect::<Vec<_>>()
2224 .join(", ")
2225 }
2226 _ => String::new(),
2227 }
2228}
2229
2230fn vm_build_empty_schema() -> BTreeMap<String, VmValue> {
2231 let mut schema = BTreeMap::new();
2232 schema.insert(
2233 "schema_version".to_string(),
2234 VmValue::String(Rc::from("harn-tools/1.0")),
2235 );
2236 schema.insert("tools".to_string(), VmValue::List(Rc::new(Vec::new())));
2237 schema
2238}
2239
2240fn vm_build_input_schema(
2241 params: Option<&VmValue>,
2242 components: Option<&BTreeMap<String, VmValue>>,
2243) -> VmValue {
2244 let mut schema = BTreeMap::new();
2245 schema.insert("type".to_string(), VmValue::String(Rc::from("object")));
2246
2247 let params_map = match params {
2248 Some(VmValue::Dict(map)) if !map.is_empty() => map,
2249 _ => {
2250 schema.insert(
2251 "properties".to_string(),
2252 VmValue::Dict(Rc::new(BTreeMap::new())),
2253 );
2254 return VmValue::Dict(Rc::new(schema));
2255 }
2256 };
2257
2258 let mut properties = BTreeMap::new();
2259 let mut required = Vec::new();
2260
2261 for (key, val) in params_map.iter() {
2262 let prop = vm_resolve_param_type(val, components);
2263 properties.insert(key.clone(), prop);
2264 required.push(VmValue::String(Rc::from(key.as_str())));
2265 }
2266
2267 schema.insert("properties".to_string(), VmValue::Dict(Rc::new(properties)));
2268 if !required.is_empty() {
2269 required.sort_by_key(|a| a.display());
2270 schema.insert("required".to_string(), VmValue::List(Rc::new(required)));
2271 }
2272
2273 VmValue::Dict(Rc::new(schema))
2274}
2275
2276fn vm_resolve_param_type(val: &VmValue, components: Option<&BTreeMap<String, VmValue>>) -> VmValue {
2277 match val {
2278 VmValue::String(type_name) => {
2279 let json_type = vm_harn_type_to_json_schema(type_name);
2280 let mut prop = BTreeMap::new();
2281 prop.insert("type".to_string(), VmValue::String(Rc::from(json_type)));
2282 VmValue::Dict(Rc::new(prop))
2283 }
2284 VmValue::Dict(map) => {
2285 if let Some(VmValue::String(ref_name)) = map.get("$ref") {
2286 if let Some(comps) = components {
2287 if let Some(resolved) = comps.get(&**ref_name) {
2288 return resolved.clone();
2289 }
2290 }
2291 let mut prop = BTreeMap::new();
2292 prop.insert(
2293 "$ref".to_string(),
2294 VmValue::String(Rc::from(
2295 format!("#/components/schemas/{ref_name}").as_str(),
2296 )),
2297 );
2298 VmValue::Dict(Rc::new(prop))
2299 } else {
2300 VmValue::Dict(Rc::new((**map).clone()))
2301 }
2302 }
2303 _ => {
2304 let mut prop = BTreeMap::new();
2305 prop.insert("type".to_string(), VmValue::String(Rc::from("string")));
2306 VmValue::Dict(Rc::new(prop))
2307 }
2308 }
2309}
2310
2311fn vm_harn_type_to_json_schema(harn_type: &str) -> &str {
2312 match harn_type {
2313 "int" => "integer",
2314 "float" => "number",
2315 "bool" | "boolean" => "boolean",
2316 "list" | "array" => "array",
2317 "dict" | "object" => "object",
2318 _ => "string",
2319 }
2320}