Skip to main content

strands_harness/tools/
programmatic_tool_caller.rs

1//! `programmatic_tool_caller`: lets the agent orchestrate its other tools with Python code.
2//!
3//! The model calls this tool with a `code` string; the code runs in a [Monty](https://github.com/pydantic/monty)
4//! interpreter with every other registered tool exposed as an `async` function taking keyword
5//! arguments, so the model can chain, loop over, filter and parallelize tool calls in one turn.
6//! Only text the code passes to `print()` is returned to the model.
7//!
8//! Monty's VM implements no host operations: no filesystem, environment, network or process
9//! access exists in the bytecode, and time and recursion limits are enforced by the VM. The only
10//! way out is the tool functions handed in here, so the code reaches exactly what the agent's
11//! tools reach.
12//!
13//! # Isolation
14//!
15//! The interpreter runs in a separate worker process when one is available, so a crash inside it
16//! (a stack overflow, an allocator abort) ends only the worker, and the memory limit is a hard cap
17//! on the worker's allocations. The worker is the `monty` binary of `monty-runtime` at the exact
18//! version this crate pins ([`MONTY_WORKER_VERSION`]):
19//!
20//! ```text
21//! cargo install monty-runtime --version 1.5.0 --locked
22//! ```
23//!
24//! [`Isolation::Auto`] (the default) looks for the binary in this order: the `MONTY_BIN`
25//! environment variable when it names a file, then `monty` on `PATH`, then a `target/debug` or
26//! `target/release` build in the cargo workspace of the running executable.
27//! [`Isolation::Subprocess`] names the binary explicitly. Without one, or when a found binary
28//! other than `MONTY_BIN` cannot start, the interpreter runs in this process with a warning.
29//! In-process, each interpreter step runs on its own thread with a 256 MiB stack and arguments are
30//! converted at most 128 levels deep, so nested data cannot overflow the host's stack; the memory
31//! limit then only bounds single allocations (the VM checks each one against it, not the process
32//! total), so for a hard cap use a worker. The subprocess transport needs the `monty-pool` feature
33//! (on by default).
34//!
35//! Inner calls run through [`ToolAgent::call_tool_without_interrupts`], the agent's full
36//! per-tool pipeline (hooks, interventions, middleware): a denied call raises a catchable
37//! `RuntimeError` in the code, and a call that needs approval is refused the same way, since the
38//! code cannot wait for a human. The outer call still completes, and is never run again on
39//! resume.
40
41use 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
66/// The description shown to the model (`DEFAULT_PROGRAMMATIC_TOOL_CALLER_DESCRIPTION`).
67pub 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
85/// Inner tool calls in flight at once per run, so `asyncio.gather` over a long list does not fan
86/// out unbounded against the same agent.
87pub(crate) const MAX_CONCURRENT_TOOL_CALLS: usize = 10;
88
89/// The wall-clock ceiling for a run, tool calls included, when none is configured.
90pub const DEFAULT_PROGRAMMATIC_TOOL_CALLER_TIMEOUT: Duration = Duration::from_secs(900);
91
92/// The `monty-runtime` version whose `monty` binary serves as the worker: the protocol must match
93/// the `monty-pool` this crate links, so install exactly this version.
94pub const MONTY_WORKER_VERSION: &str = "1.5.0";
95
96/// The environment variable naming the worker binary for [`Isolation::Auto`], shared with Monty's
97/// other language bindings.
98pub 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
104/// Cap on the text returned to the model, in characters.
105const MAX_OUTPUT_CHARS: usize = 200_000;
106
107/// How deep a value may nest when it crosses between the code and a tool, so converting it
108/// never recurses deeper than this on the host's stack.
109const 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/// The interpreter limits (`LIMITS`). Guest duration counts interpreter time only (the clock
118/// pauses while a tool call is in flight). Suspensions are host round trips: a sequentially
119/// awaited tool call costs two, a gathered one about one.
120#[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/// Where the interpreter runs. See the [module docs](self#isolation).
145#[derive(Debug, Clone, Default, PartialEq, Eq)]
146#[non_exhaustive]
147pub enum Isolation {
148    /// The worker binary named by [`MONTY_WORKER_ENV`], else `monty` on `PATH`, else a build in
149    /// the running executable's cargo workspace, else this process, with a warning. A worker
150    /// from the environment variable that cannot start fails the run; one found elsewhere falls
151    /// back to this process.
152    #[default]
153    Auto,
154    /// This `monty` worker binary; a worker that cannot start fails the run. Needs the
155    /// `monty-pool` feature.
156    Subprocess(PathBuf),
157    /// This process, each interpreter step on its own large-stack thread.
158    InProcess,
159}
160
161/// The portable `builtinTools.programmatic_tool_caller` config (`ProgrammaticToolCallerConfig`).
162///
163/// ```
164/// use strands_harness::tools::programmatic_tool_caller::ProgrammaticToolCallerConfig;
165///
166/// let config: ProgrammaticToolCallerConfig = serde_json::from_str(r#"{"allowedTools": ["read"], "timeout": null}"#)?;
167/// assert_eq!(config.allowed_tools, Some(vec!["read".to_owned()]));
168/// assert_eq!(config.timeout, Some(None));
169/// # Ok::<(), serde_json::Error>(())
170/// ```
171#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, bon::Builder)]
172#[serde(rename_all = "camelCase", deny_unknown_fields)]
173pub struct ProgrammaticToolCallerConfig {
174    /// Names of the agent's other tools the code may call; `None` (or JSON `null`) for all of
175    /// them.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub allowed_tools: Option<Vec<String>>,
178    /// Wall-clock bound in seconds for one run, tool calls included: `None` (absent) for the
179    /// default of 900, `Some(None)` (JSON `null`) for no bound.
180    #[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/// Options for [`make_programmatic_tool_caller`] (`MakeProgrammaticToolCallerOptions`).
193#[derive(Debug, Clone, Default, bon::Builder)]
194#[builder(on(String, into))]
195pub struct MakeProgrammaticToolCallerOptions {
196    /// Registry names of the tools to expose to the code; every other registered tool when
197    /// absent. No programmatic tool caller is ever exposed, this one or another, even if named.
198    pub allowed_tools: Option<Vec<String>>,
199    /// The tool name; `programmatic_tool_caller` when absent.
200    pub name: Option<String>,
201    /// The description shown to the model; [`DEFAULT_PROGRAMMATIC_TOOL_CALLER_DESCRIPTION`]
202    /// when absent.
203    pub description: Option<String>,
204    /// Wall-clock ceiling for a run, tool calls included: `None` for
205    /// [`DEFAULT_PROGRAMMATIC_TOOL_CALLER_TIMEOUT`], `Some(None)` for no bound.
206    pub timeout: Option<Option<Duration>>,
207    /// Where the interpreter runs (Rust-only); [`Isolation::Auto`] by default.
208    #[builder(default)]
209    pub isolation: Isolation,
210}
211
212/// The `programmatic_tool_caller` tool: runs model-written Python with the agent's other tools
213/// exposed as async functions.
214///
215/// Cloning shares the instance; a clone is the same caller and is never exposed to code either.
216#[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
231/// Every live caller; none is exposed to another's code (two callers exposing each other would
232/// recurse). A tool is identified by the address of its name, which a caller's name keeps on its
233/// shared heap allocation, so no downcasting is needed.
234static 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/// Builds the tool from the portable config: the timeout is in seconds, and a negative or
253/// non-finite one ends every run at once.
254///
255/// ```
256/// use strands_harness::tools::programmatic_tool_caller::{ProgrammaticToolCallerConfig, programmatic_tool_caller};
257///
258/// let caller = programmatic_tool_caller(ProgrammaticToolCallerConfig::default());
259/// let agent = strands::Agent::builder().tools([caller]).printer(false).build()?;
260/// assert!(agent.tool_registry().get("programmatic_tool_caller").is_some());
261/// # Ok::<(), strands::Error>(())
262/// ```
263#[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/// Creates a programmatic tool caller.
276///
277/// ```
278/// use std::time::Duration;
279/// use strands::Tool;
280/// use strands_harness::tools::programmatic_tool_caller::{
281///     Isolation, MakeProgrammaticToolCallerOptions, make_programmatic_tool_caller,
282/// };
283///
284/// let caller = make_programmatic_tool_caller(
285///     MakeProgrammaticToolCallerOptions::builder()
286///         .name("run_code")
287///         .allowed_tools(vec!["read".to_owned()])
288///         .timeout(Some(Duration::from_secs(60)))
289///         .isolation(Isolation::InProcess)
290///         .build(),
291/// );
292/// assert_eq!(caller.name(), "run_code");
293/// ```
294#[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    /// A caller with other interpreter limits and isolation; `threaded: false` runs in-process
323    /// steps inline, so paused-clock tests see no thread time.
324    #[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
379/// How a run ended early.
380enum Stop {
381    Cancelled,
382    TimedOut,
383    Failed(String),
384}
385
386/// Where one run's interpreter runs, resolved from [`Isolation`] when the run starts.
387enum 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
402/// Where [`Isolation::Auto`] looks for a worker: the process `PATH` and the running executable.
403struct WorkerSearch<'a> {
404    path: Option<&'a std::ffi::OsStr>,
405    exe: Option<&'a Path>,
406}
407
408/// How many ancestor directories of the executable are searched for a cargo workspace.
409const WORKSPACE_SEARCH_DEPTH: usize = 6;
410
411fn worker_binary_name() -> String {
412    format!("monty{}", std::env::consts::EXE_SUFFIX)
413}
414
415/// The `monty` binary on `PATH`.
416fn 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
423/// A `target/debug` (preferred) or `target/release` `monty` build in the nearest cargo workspace
424/// above the executable that has one.
425fn 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    /// Runs the code; `Ok` is the printed output, `Err` the error message.
468    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    /// Runs the code in a worker when one is available, else in this process.
517    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    /// The host functions by Python name, each naming its registry tool: every exposed tool,
567    /// plus an alias for each tool whose name is not a valid identifier, with every
568    /// non-identifier character replaced by `_`. An alias that would shadow a real tool name or
569    /// another tool's alias is dropped rather than guessed.
570    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
617/// What an inner call answers the code with: the value, or the exception it raises.
618type CallResult = Result<MontyObject, MontyException>;
619
620type Pending = FuturesUnordered<BoxFuture<'static, (u32, CallResult)>>;
621
622/// What one run hands the code, whichever engine runs it: the tool functions, the concurrency
623/// slots, the output and the cancel signal.
624struct 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    /// One inner call through the agent's tool pipeline, holding a concurrency slot.
635    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            // A cancelled run makes no further real tool calls behind the model's back.
642            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    /// Resolves a name the code reads: a tool function, or undefined.
655    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
662/// The registry tool and input for a call, or the exception the code sees.
663fn 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
699/// What the code receives for an inner call: the unwrapped result, or a `RuntimeError`.
700fn 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
721/// What the code sees for an inner call that stopped for human input: the refusal
722/// `AfterToolCallEvent` left for an approval a hook or intervention asked for, else the refusal of
723/// an interrupt from middleware or the tool itself.
724fn 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
739/// The refusal of an interrupt that middleware or the inner tool raised.
740fn 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
747/// The refusal of an approval an inner call needs, which the inner call's `AfterToolCallEvent`
748/// sees as its error result.
749fn 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
777/// The value the code receives for a tool result: a lone JSON block, or a lone
778/// text block that is a JSON object or array, as data; otherwise the text blocks joined.
779fn 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
793/// `value` as a Python value, or `None` when it nests deeper than [`MAX_VALUE_DEPTH`].
794fn 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
820/// A Python value as JSON, or `None` when it nests deeper than [`MAX_VALUE_DEPTH`].
821fn 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/// Collects the code's `print()` output (`Output`), keeping one character past the cap so
860/// [`cap`] still sees that it overflowed.
861#[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    /// The error message preceded by whatever the code printed before failing. Both share the
893    /// cap: the error keeps at least half, the output the rest.
894    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
908/// The print callback for one interpreter step, writing into the run's shared [`Output`].
909struct 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
923/// `raw` trimmed when it fits in `limit` characters, else its first `limit` characters trimmed
924/// with a truncation marker.
925fn 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;