1use std::borrow::Cow;
42use std::collections::{BTreeMap, HashMap, HashSet};
43use std::fmt;
44use std::path::{Path, PathBuf};
45use std::sync::atomic::{AtomicBool, Ordering};
46use std::sync::{Arc, Mutex, PoisonError, Weak};
47use std::time::Duration;
48
49use futures::FutureExt;
50use futures::future::BoxFuture;
51use futures::stream::FuturesUnordered;
52use monty_types::{CallArgs, ExcType, MontyException, MontyObject, ObjectRef, PrintWriterCallback, ResourceLimits};
53use serde::{Deserialize, Deserializer, Serialize};
54use serde_json::json;
55use strands::interrupt::{InterruptError, InterruptSource};
56use strands::types::{JsonValue, ToolResultBlock, ToolResultContent, ToolResultStatus, ToolSpec};
57use strands::{CancelSignal, RefusedCall, Tool, ToolAgent, ToolContext, ToolOutcome, ToolStream};
58use tokio::sync::Semaphore;
59
60use crate::env::Env;
61
62mod in_process;
63#[cfg(feature = "monty-pool")]
64mod worker;
65
66pub const DEFAULT_PROGRAMMATIC_TOOL_CALLER_DESCRIPTION: &str = concat!(
68 "Execute Python code that orchestrates the agent's other tools, each exposed as an async function ",
69 "taking keyword arguments -- always `await` them, e.g. `result = await read(path=\"/etc/hosts\")`. ",
70 "The code runs in an async context, so `await` and `asyncio.gather(...)` work without boilerplate. ",
71 "A tool result that is structured content or JSON text (an object or array) arrives parsed, as a ",
72 "dict/list; anything else arrives as a string. A tool that fails raises RuntimeError, which you can ",
73 "catch. ",
74 "Only text sent to `print()` is returned to you: a tool's return value stays in the code's local ",
75 "scope unless you print it. A tool whose name is not a valid Python identifier (for example ",
76 "`fetch-url` or `ns.fetch`) is also available with those characters replaced by underscores ",
77 "(`fetch_url`, `ns_fetch`). The code runs in a sandboxed Python subset: `asyncio`, `json`, `re`, ",
78 "`math`, `datetime`, `collections`, `itertools`, `functools`, `dataclasses`, `typing`, `base64` ",
79 "are importable; filesystem, network, and subprocess access do not exist -- use the agent's tools ",
80 "for those. Generators (`yield`), class inheritance, `match`, and `del` are not supported. Use this ",
81 "to chain, loop over, filter, or parallelize tool calls in a single turn instead of one tool call ",
82 "per model round-trip, keeping large intermediate results out of the conversation."
83);
84
85pub(crate) const MAX_CONCURRENT_TOOL_CALLS: usize = 10;
88
89pub const DEFAULT_PROGRAMMATIC_TOOL_CALLER_TIMEOUT: Duration = Duration::from_secs(900);
91
92pub const MONTY_WORKER_VERSION: &str = "1.5.0";
95
96pub const MONTY_WORKER_ENV: &str = "MONTY_BIN";
99
100const DEFAULT_NAME: &str = "programmatic_tool_caller";
101
102const USER_CODE_FILENAME: &str = "<programmatic_tool_caller>";
103
104const MAX_OUTPUT_CHARS: usize = 200_000;
106
107const MAX_VALUE_DEPTH: usize = 128;
110
111const CODE_DESCRIPTION: &str = "Python code to execute. Use `await tool_name(...)` to call tools.";
112
113const CANCELLED_CALL: &str = "programmatic_tool_caller was cancelled; no further tool calls are made.";
114
115const NO_INNER_INTERRUPTS: &str = "Interrupts are not supported from programmatic_tool_caller.";
116
117#[derive(Debug, Clone, Copy, PartialEq)]
121struct Limits {
122 max_duration: Duration,
123 max_memory: usize,
124 max_suspensions: usize,
125}
126
127impl Limits {
128 fn resource_limits(self) -> ResourceLimits {
129 ResourceLimits {
130 max_feed_duration: Some(self.max_duration),
131 max_memory: Some(self.max_memory),
132 max_suspensions: self.max_suspensions,
133 ..ResourceLimits::default()
134 }
135 }
136}
137
138const LIMITS: Limits = Limits {
139 max_duration: Duration::from_secs(60),
140 max_memory: 256 * 1024 * 1024,
141 max_suspensions: 1_000,
142};
143
144#[derive(Debug, Clone, Default, PartialEq, Eq)]
146#[non_exhaustive]
147pub enum Isolation {
148 #[default]
153 Auto,
154 Subprocess(PathBuf),
157 InProcess,
159}
160
161#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, bon::Builder)]
172#[serde(rename_all = "camelCase", deny_unknown_fields)]
173pub struct ProgrammaticToolCallerConfig {
174 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub allowed_tools: Option<Vec<String>>,
178 #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
181 pub timeout: Option<Option<f64>>,
182}
183
184fn present<'de, D, T>(deserializer: D) -> Result<Option<Option<T>>, D::Error>
185where
186 D: Deserializer<'de>,
187 T: Deserialize<'de>,
188{
189 Option::<T>::deserialize(deserializer).map(Some)
190}
191
192#[derive(Debug, Clone, Default, bon::Builder)]
194#[builder(on(String, into))]
195pub struct MakeProgrammaticToolCallerOptions {
196 pub allowed_tools: Option<Vec<String>>,
199 pub name: Option<String>,
201 pub description: Option<String>,
204 pub timeout: Option<Option<Duration>>,
207 #[builder(default)]
209 pub isolation: Isolation,
210}
211
212#[derive(Clone)]
217pub struct ProgrammaticToolCaller {
218 inner: Arc<Inner>,
219}
220
221struct Inner {
222 name: String,
223 spec: ToolSpec,
224 allowed_tools: Option<Vec<String>>,
225 timeout: Option<Duration>,
226 isolation: Isolation,
227 limits: Limits,
228 threaded: bool,
229}
230
231static INSTANCES: Mutex<Vec<Weak<Inner>>> = Mutex::new(Vec::new());
235
236fn register(inner: &Arc<Inner>) {
237 let mut instances = INSTANCES.lock().unwrap_or_else(PoisonError::into_inner);
238 instances.retain(|instance| instance.strong_count() > 0);
239 instances.push(Arc::downgrade(inner));
240}
241
242fn is_caller(tool: &dyn Tool) -> bool {
243 let name = tool.name().as_ptr();
244 INSTANCES
245 .lock()
246 .unwrap_or_else(PoisonError::into_inner)
247 .iter()
248 .filter_map(Weak::upgrade)
249 .any(|inner| std::ptr::eq(inner.name.as_ptr(), name))
250}
251
252#[must_use]
264pub fn programmatic_tool_caller(config: ProgrammaticToolCallerConfig) -> ProgrammaticToolCaller {
265 let timeout = config
266 .timeout
267 .map(|timeout| timeout.map(|seconds| Duration::try_from_secs_f64(seconds).unwrap_or(Duration::ZERO)));
268 make_programmatic_tool_caller(MakeProgrammaticToolCallerOptions {
269 allowed_tools: config.allowed_tools,
270 timeout,
271 ..MakeProgrammaticToolCallerOptions::default()
272 })
273}
274
275#[must_use]
295pub fn make_programmatic_tool_caller(options: MakeProgrammaticToolCallerOptions) -> ProgrammaticToolCaller {
296 let name = options.name.unwrap_or_else(|| DEFAULT_NAME.to_owned());
297 let description = options
298 .description
299 .unwrap_or_else(|| DEFAULT_PROGRAMMATIC_TOOL_CALLER_DESCRIPTION.to_owned());
300 let schema = json!({
301 "type": "object",
302 "properties": {"code": {"type": "string", "description": CODE_DESCRIPTION}},
303 "required": ["code"],
304 "additionalProperties": false
305 });
306 let inner = Arc::new(Inner {
307 spec: ToolSpec::new(&name, description).with_input_schema(schema),
308 name,
309 allowed_tools: options.allowed_tools,
310 timeout: options
311 .timeout
312 .unwrap_or(Some(DEFAULT_PROGRAMMATIC_TOOL_CALLER_TIMEOUT)),
313 isolation: options.isolation,
314 limits: LIMITS,
315 threaded: true,
316 });
317 register(&inner);
318 ProgrammaticToolCaller { inner }
319}
320
321impl ProgrammaticToolCaller {
322 #[cfg(test)]
325 fn with_limits(self, limits: Limits, isolation: Isolation, threaded: bool) -> Self {
326 let inner = Arc::new(Inner {
327 name: self.inner.name.clone(),
328 spec: self.inner.spec.clone(),
329 allowed_tools: self.inner.allowed_tools.clone(),
330 timeout: self.inner.timeout,
331 isolation,
332 limits,
333 threaded,
334 });
335 register(&inner);
336 Self { inner }
337 }
338}
339
340impl fmt::Debug for ProgrammaticToolCaller {
341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342 f.debug_struct("ProgrammaticToolCaller")
343 .field("name", &self.inner.name)
344 .field("allowed_tools", &self.inner.allowed_tools)
345 .field("timeout", &self.inner.timeout)
346 .field("isolation", &self.inner.isolation)
347 .finish_non_exhaustive()
348 }
349}
350
351impl Tool for ProgrammaticToolCaller {
352 fn name(&self) -> &str {
353 &self.inner.name
354 }
355
356 fn description(&self) -> &str {
357 &self.inner.spec.description
358 }
359
360 fn tool_spec(&self) -> ToolSpec {
361 self.inner.spec.clone()
362 }
363
364 fn stream(&self, context: ToolContext) -> ToolStream {
365 let inner = self.inner.clone();
366 ToolStream::from_future(async move {
367 let tool_use_id = context.tool_use().tool_use_id.clone();
368 let result = match inner.execute(&context).await {
369 Ok(text) => ToolResultBlock::success(&tool_use_id, vec![ToolResultContent::text(text)]),
370 Err(message) => {
371 ToolResultBlock::error(&tool_use_id, vec![ToolResultContent::text(format!("Error: {message}"))])
372 }
373 };
374 ToolOutcome::from(result)
375 })
376 }
377}
378
379enum Stop {
381 Cancelled,
382 TimedOut,
383 Failed(String),
384}
385
386enum Engine {
388 InProcess,
389 Worker { path: PathBuf, explicit: bool },
390}
391
392static WARNED_IN_PROCESS: AtomicBool = AtomicBool::new(false);
393
394fn warn_in_process(reason: &str) {
395 if !WARNED_IN_PROCESS.swap(true, Ordering::Relaxed) {
396 tracing::warn!(
397 "reason=<{reason}> | programmatic_tool_caller runs the interpreter in-process with no crash isolation and no cap on its total memory, install the worker with cargo install monty-runtime --version {MONTY_WORKER_VERSION} --locked or set {MONTY_WORKER_ENV}"
398 );
399 }
400}
401
402struct WorkerSearch<'a> {
404 path: Option<&'a std::ffi::OsStr>,
405 exe: Option<&'a Path>,
406}
407
408const WORKSPACE_SEARCH_DEPTH: usize = 6;
410
411fn worker_binary_name() -> String {
412 format!("monty{}", std::env::consts::EXE_SUFFIX)
413}
414
415fn worker_on_path(path: Option<&std::ffi::OsStr>) -> Option<PathBuf> {
417 let binary = worker_binary_name();
418 std::env::split_paths(path?)
419 .map(|dir| dir.join(&binary))
420 .find(|candidate| candidate.is_file())
421}
422
423fn worker_in_workspace(exe: Option<&Path>) -> Option<PathBuf> {
426 let binary = worker_binary_name();
427 exe?.ancestors()
428 .skip(1)
429 .take(WORKSPACE_SEARCH_DEPTH)
430 .filter(|dir| dir.join("Cargo.toml").is_file())
431 .flat_map(|dir| ["debug", "release"].map(|profile| dir.join("target").join(profile).join(&binary)))
432 .find(|candidate| candidate.is_file())
433}
434
435impl Isolation {
436 fn engine(&self, env: &Env, search: &WorkerSearch<'_>) -> Engine {
437 match self {
438 Self::InProcess => Engine::InProcess,
439 Self::Subprocess(path) => Engine::Worker {
440 path: path.clone(),
441 explicit: true,
442 },
443 Self::Auto => auto_engine(env, search),
444 }
445 }
446}
447
448fn auto_engine(env: &Env, search: &WorkerSearch<'_>) -> Engine {
449 if let Some(named) = env.get(MONTY_WORKER_ENV).filter(|named| !named.is_empty()) {
450 let path = PathBuf::from(named);
451 if path.is_file() {
452 return Engine::Worker { path, explicit: true };
453 }
454 tracing::debug!(
455 "{MONTY_WORKER_ENV}=<{}> | no file at the named monty worker",
456 path.display()
457 );
458 }
459 let found = worker_on_path(search.path).or_else(|| worker_in_workspace(search.exe));
460 match found {
461 Some(path) => Engine::Worker { path, explicit: false },
462 None => Engine::InProcess,
463 }
464}
465
466impl Inner {
467 async fn execute(&self, context: &ToolContext) -> Result<String, String> {
469 let Some(code) = context.tool_use().input.get("code").and_then(JsonValue::as_str) else {
470 return Err("Invalid input: expected string for \"code\".".to_owned());
471 };
472 let cancel = context.cancel_signal().clone();
473 let output = Arc::new(Output::default());
474 let host = Host {
475 agent: context.agent().clone(),
476 functions: Arc::new(self.functions(context.agent())),
477 slots: Arc::new(Semaphore::new(MAX_CONCURRENT_TOOL_CALLS)),
478 output: output.clone(),
479 cancel: cancel.clone(),
480 limits: self.limits,
481 };
482 let deadline = async {
483 match self.timeout {
484 Some(timeout) => tokio::time::sleep(timeout).await,
485 None => futures::future::pending().await,
486 }
487 };
488 let outcome = if cancel.is_cancelled() {
489 Err(Stop::Cancelled)
490 } else {
491 tokio::select! {
492 biased;
493 () = cancel.cancelled() => Err(Stop::Cancelled),
494 () = deadline => Err(Stop::TimedOut),
495 outcome = self.drive(&host, code.to_owned()) => outcome,
496 }
497 };
498 match outcome {
499 Ok(()) => {
500 let text = output.text();
501 Ok(if text.is_empty() {
502 "(no output)".to_owned()
503 } else {
504 text
505 })
506 }
507 Err(Stop::Cancelled) => Err("Execution cancelled.".to_owned()),
508 Err(Stop::TimedOut) => {
509 let seconds = self.timeout.map_or(0.0, |timeout| timeout.as_secs_f64());
510 Err(output.with_error(&format!("Execution error: timed out after {seconds} seconds.")))
511 }
512 Err(Stop::Failed(message)) => Err(message),
513 }
514 }
515
516 async fn drive(&self, host: &Host, code: String) -> Result<(), Stop> {
518 let path = std::env::var_os("PATH");
519 let exe = std::env::current_exe().ok();
520 let search = WorkerSearch {
521 path: path.as_deref(),
522 exe: exe.as_deref(),
523 };
524 match self.isolation.engine(&Env::process(), &search) {
525 Engine::InProcess => {
526 if self.isolation == Isolation::Auto {
527 warn_in_process("no monty worker found");
528 }
529 in_process::drive(host, code, self.threaded).await
530 }
531 Engine::Worker { path, explicit } => self.drive_worker(host, code, &path, explicit).await,
532 }
533 }
534
535 #[cfg(feature = "monty-pool")]
536 async fn drive_worker(&self, host: &Host, code: String, path: &Path, explicit: bool) -> Result<(), Stop> {
537 match worker::drive(host, &code, path).await {
538 Err(worker::Failure::Unavailable(error)) if !explicit => {
539 warn_in_process(&format!(
540 "the monty worker at {} did not start: {error}",
541 path.display()
542 ));
543 in_process::drive(host, code, self.threaded).await
544 }
545 Err(worker::Failure::Unavailable(error)) => Err(Stop::Failed(host.output.with_error(&format!(
546 "Execution error: the monty worker at {} did not start: {error}",
547 path.display()
548 )))),
549 Err(worker::Failure::Stopped(stop)) => Err(stop),
550 Ok(()) => Ok(()),
551 }
552 }
553
554 #[cfg(not(feature = "monty-pool"))]
555 async fn drive_worker(&self, host: &Host, code: String, path: &Path, explicit: bool) -> Result<(), Stop> {
556 if explicit {
557 return Err(Stop::Failed(format!(
558 "Execution error: running the interpreter in the monty worker at {} needs the strands-harness feature \"monty-pool\".",
559 path.display()
560 )));
561 }
562 warn_in_process("the strands-harness feature \"monty-pool\" is off");
563 in_process::drive(host, code, self.threaded).await
564 }
565
566 fn functions(&self, agent: &ToolAgent) -> HashMap<String, String> {
571 let available: Vec<String> = agent
572 .tool_registry()
573 .list()
574 .into_iter()
575 .filter(|tool| !is_caller(tool.as_ref()))
576 .map(|tool| tool.name().to_owned())
577 .filter(|name| self.allowed_tools.as_ref().is_none_or(|allowed| allowed.contains(name)))
578 .collect();
579 let mut functions: HashMap<String, String> =
580 available.iter().map(|name| (name.clone(), name.clone())).collect();
581 let mut sorted = available.clone();
582 sorted.sort();
583 let mut aliases: BTreeMap<String, String> = BTreeMap::new();
584 let mut ambiguous: HashSet<String> = HashSet::new();
585 for name in sorted {
586 if is_identifier(&name) {
587 continue;
588 }
589 let alias: String = name
590 .chars()
591 .map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' })
592 .collect();
593 if !is_identifier(&alias) || available.contains(&alias) {
594 continue;
595 }
596 if aliases.contains_key(&alias) {
597 ambiguous.insert(alias);
598 continue;
599 }
600 aliases.insert(alias, name);
601 }
602 for alias in &ambiguous {
603 aliases.remove(alias);
604 tracing::warn!("alias=<{alias}> | multiple tools normalize to the alias, no alias injected");
605 }
606 functions.extend(aliases);
607 functions
608 }
609}
610
611fn is_identifier(name: &str) -> bool {
612 let mut chars = name.chars();
613 chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
614 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
615}
616
617type CallResult = Result<MontyObject, MontyException>;
619
620type Pending = FuturesUnordered<BoxFuture<'static, (u32, CallResult)>>;
621
622struct Host {
625 agent: ToolAgent,
626 functions: Arc<HashMap<String, String>>,
627 slots: Arc<Semaphore>,
628 output: Arc<Output>,
629 cancel: CancelSignal,
630 limits: Limits,
631}
632
633impl Host {
634 fn call_future(&self, call_id: u32, tool_name: String, input: JsonValue) -> BoxFuture<'static, (u32, CallResult)> {
636 let agent = self.agent.clone();
637 let slots = self.slots.clone();
638 let cancel = self.cancel.clone();
639 async move {
640 let _slot = slots.acquire_owned().await;
641 if cancel.is_cancelled() {
643 return (call_id, Err(runtime_error(CANCELLED_CALL)));
644 }
645 let refused_name = tool_name.clone();
646 let result = agent
647 .call_tool_without_interrupts(&tool_name, input, move |error| approval_refusal(&refused_name, error))
648 .await;
649 (call_id, call_result(&tool_name, result))
650 }
651 .boxed()
652 }
653
654 fn lookup(&self, name: &str) -> Option<MontyObject> {
656 self.functions
657 .contains_key(name)
658 .then(|| MontyObject::function(name.to_owned(), None))
659 }
660}
661
662fn prepare_call(
664 functions: &HashMap<String, String>,
665 function: &str,
666 args: &CallArgs,
667) -> Result<(String, JsonValue), MontyException> {
668 let Some(tool_name) = functions.get(function) else {
669 return Err(MontyException::new(
670 ExcType::NameError,
671 Some(format!("name '{function}' is not defined")),
672 ));
673 };
674 if args.args().next().is_some() {
675 return Err(type_error(format!(
676 "{function}() takes keyword arguments only, e.g. {function}(key=value)"
677 )));
678 }
679 let mut input = serde_json::Map::new();
680 for (key, value) in args.kwargs() {
681 let value = to_json(value, 0).ok_or_else(|| {
682 type_error(format!(
683 "{function}() argument is nested more than {MAX_VALUE_DEPTH} levels deep"
684 ))
685 })?;
686 input.insert(key.as_str().map_or_else(|| key.to_string(), str::to_owned), value);
687 }
688 Ok((tool_name.clone(), JsonValue::Object(input)))
689}
690
691fn type_error(message: String) -> MontyException {
692 MontyException::new(ExcType::TypeError, Some(message))
693}
694
695fn runtime_error(message: impl Into<String>) -> MontyException {
696 MontyException::new(ExcType::RuntimeError, Some(message.into()))
697}
698
699fn call_result(tool_name: &str, result: Result<ToolResultBlock, RefusedCall>) -> CallResult {
701 let result = match result {
702 Ok(result) => result,
703 Err(refused) => return Err(runtime_error(refusal(tool_name, &refused))),
704 };
705 if result.status == ToolResultStatus::Error {
706 let text = extract_text(&result.content);
707 let text = if text.is_empty() {
708 "Unknown error".to_owned()
709 } else {
710 text
711 };
712 return Err(runtime_error(format!("Tool '{tool_name}' error: {text}")));
713 }
714 to_monty(&unwrap_result(&result), 0).ok_or_else(|| {
715 runtime_error(format!(
716 "Tool '{tool_name}' returned a result nested more than {MAX_VALUE_DEPTH} levels deep"
717 ))
718 })
719}
720
721fn refusal(tool_name: &str, refused: &RefusedCall) -> String {
725 let text = match &refused.result {
726 Some(result) => extract_text(&result.content),
727 None => String::new(),
728 };
729 let text = if !text.is_empty() {
730 text
731 } else if refused.result.is_some() {
732 approval_refusal(tool_name, &refused.interrupts)
733 } else {
734 interrupt_refusal(tool_name, &refused.interrupts)
735 };
736 format!("Failed to execute tool '{tool_name}': {text}")
737}
738
739fn interrupt_refusal(tool_name: &str, error: &InterruptError) -> String {
741 match error.interrupts.first() {
742 Some(interrupt) if interrupt.source != InterruptSource::Tool => approval_refusal(tool_name, error),
743 _ => NO_INNER_INTERRUPTS.to_owned(),
744 }
745}
746
747fn approval_refusal(tool_name: &str, error: &InterruptError) -> String {
750 let approval = match error
751 .interrupts
752 .first()
753 .map(|interrupt| (&interrupt.reason, &interrupt.name))
754 {
755 Some((Some(JsonValue::String(reason)), _)) => reason.clone(),
756 Some((Some(JsonValue::Null) | None, name)) => name.clone(),
757 Some((Some(reason), _)) => reason.to_string(),
758 None => "no reason given".to_owned(),
759 };
760 format!(
761 "Tool '{tool_name}' needs approval ({approval}), which programmatic_tool_caller cannot prompt for; call it as a normal tool call instead."
762 )
763}
764
765fn extract_text(content: &[ToolResultContent]) -> String {
766 content
767 .iter()
768 .filter_map(|block| match block {
769 ToolResultContent::Text(text) => Some(text.text.clone()),
770 ToolResultContent::Json(json) => Some(json.json.to_string()),
771 _ => None,
772 })
773 .collect::<Vec<_>>()
774 .join("\n")
775}
776
777fn unwrap_result(result: &ToolResultBlock) -> JsonValue {
780 if let [ToolResultContent::Json(json)] = result.content.as_slice() {
781 return json.json.clone();
782 }
783 let text = extract_text(&result.content);
784 if result.content.len() == 1
785 && (text.starts_with('{') || text.starts_with('['))
786 && let Ok(value) = serde_json::from_str(&text)
787 {
788 return value;
789 }
790 JsonValue::String(text)
791}
792
793fn to_monty(value: &JsonValue, depth: usize) -> Option<MontyObject> {
795 if depth > MAX_VALUE_DEPTH {
796 return None;
797 }
798 Some(match value {
799 JsonValue::Null => MontyObject::none(),
800 JsonValue::Bool(value) => MontyObject::bool(*value),
801 JsonValue::Number(number) => number.as_i64().map_or_else(
802 || MontyObject::float(number.as_f64().unwrap_or(f64::NAN)),
803 MontyObject::int,
804 ),
805 JsonValue::String(text) => MontyObject::string(text.clone()),
806 JsonValue::Array(items) => MontyObject::list(
807 items
808 .iter()
809 .map(|item| to_monty(item, depth + 1))
810 .collect::<Option<Vec<_>>>()?,
811 ),
812 JsonValue::Object(map) => MontyObject::dict(
813 map.iter()
814 .map(|(key, value)| Some((MontyObject::string(key.clone()), to_monty(value, depth + 1)?)))
815 .collect::<Option<Vec<_>>>()?,
816 ),
817 })
818}
819
820fn to_json(value: ObjectRef<'_>, depth: usize) -> Option<JsonValue> {
822 if depth > MAX_VALUE_DEPTH {
823 return None;
824 }
825 let number = |value: Option<f64>| {
826 value
827 .and_then(serde_json::Number::from_f64)
828 .map_or(JsonValue::Null, JsonValue::Number)
829 };
830 Some(match value.type_name() {
831 "NoneType" => JsonValue::Null,
832 "bool" => value.as_bool().map_or(JsonValue::Null, JsonValue::Bool),
833 "int" => value.as_int().map_or_else(|| number(value.as_float()), JsonValue::from),
834 "float" => number(value.as_float()),
835 "str" => JsonValue::String(value.as_str().unwrap_or_default().to_owned()),
836 "dict" if value.pairs().is_some() => JsonValue::Object(
837 value
838 .pairs()
839 .into_iter()
840 .flatten()
841 .map(|(key, value)| {
842 let key = key.as_str().map_or_else(|| key.to_string(), str::to_owned);
843 Some((key, to_json(value, depth + 1)?))
844 })
845 .collect::<Option<_>>()?,
846 ),
847 _ => match value.items() {
848 Some(items) => JsonValue::Array(
849 items
850 .into_iter()
851 .map(|item| to_json(item, depth + 1))
852 .collect::<Option<_>>()?,
853 ),
854 None => JsonValue::String(value.to_string()),
855 },
856 })
857}
858
859#[derive(Debug, Default)]
862struct Output {
863 buffer: Mutex<OutputBuffer>,
864}
865
866#[derive(Debug, Default)]
867struct OutputBuffer {
868 text: String,
869 chars: usize,
870}
871
872impl Output {
873 fn write(&self, text: &str) {
874 let mut buffer = self.buffer.lock().unwrap_or_else(PoisonError::into_inner);
875 let room = (MAX_OUTPUT_CHARS + 1).saturating_sub(buffer.chars);
876 if room == 0 {
877 return;
878 }
879 let kept: String = text.chars().take(room).collect();
880 buffer.chars += kept.chars().count();
881 buffer.text.push_str(&kept);
882 }
883
884 fn raw(&self) -> String {
885 self.buffer.lock().unwrap_or_else(PoisonError::into_inner).text.clone()
886 }
887
888 fn text(&self) -> String {
889 cap(&self.raw(), MAX_OUTPUT_CHARS)
890 }
891
892 fn with_error(&self, message: &str) -> String {
895 let raw = self.raw();
896 let raw_chars = raw.chars().count();
897 let message_limit = MAX_OUTPUT_CHARS.saturating_sub(raw_chars).max(MAX_OUTPUT_CHARS / 2);
898 let capped = cap(message, message_limit);
899 let printed = cap(&raw, MAX_OUTPUT_CHARS - capped.chars().count().min(message_limit));
900 if printed.is_empty() {
901 capped
902 } else {
903 format!("{printed}\n\n{capped}")
904 }
905 }
906}
907
908struct Printer(Arc<Output>);
910
911impl PrintWriterCallback for Printer {
912 fn stdout_write(&mut self, output: Cow<'_, str>) -> Result<(), MontyException> {
913 self.0.write(&output);
914 Ok(())
915 }
916
917 fn stdout_push(&mut self, end: char) -> Result<(), MontyException> {
918 self.0.write(end.encode_utf8(&mut [0; 4]));
919 Ok(())
920 }
921}
922
923fn cap(raw: &str, limit: usize) -> String {
926 if raw.chars().count() <= limit {
927 return raw.trim().to_owned();
928 }
929 let kept: String = raw.chars().take(limit).collect();
930 format!("{}\n[output truncated at {limit} characters]", kept.trim())
931}
932
933#[cfg(test)]
934mod tests;