Skip to main content

kernel_apis/
tool_calls.rs

1//! `tools.*`: extension tool calls from the REPL (`ultron/rlm/extension-tools.ts` `ExtensionToolCalls`). The kernel
2//! calls a tool with `await tools.call(name, params)` / `await tools.<name>(...)` / `await mcp.call(...)` (the `mcp`
3//! gateway is a tool like any other); the host runs it on its own thread through a [`ToolRunner`] with a cancel
4//! signal. Every call is a record (name, label, status, elapsed time, input and result previews), journaled as the
5//! module document `{version: 1, calls: [...]}`.
6//!
7//! A slow call detaches like a plain `bash`: after `yield_after` seconds the kernel gets a running snapshot, the call
8//! keeps running in the host, and its end is reported to the [`ToolCallEnd`] observer (the session publishes it as a
9//! `<runtime_event kind="tool_done">`). A cell that stops while waiting on a call it did not ask a handle for cancels
10//! the call (its end then counts as awaited); an Esc abort of the root turn cancels the calls started under it
11//! ([`ToolCalls::cancel_root`], `rootAborted`). A call does not outlive the worker: a journaled running call reads as
12//! `interrupted` after a restart.
13//!
14//! Calls on a lane honor the tool's `executionMode` as the harness does for a model's tool calls: a "sequential" tool
15//! waits for the lane's calls in flight and runs alone, and calls started after it wait for it (first come, first
16//! served; [`LaneGate`]). A running call's progress (`onUpdate`) becomes its record's preview.
17//!
18//! Not ported: the records of native tool calls (the model's only tool is `rlm`).
19
20use crate::store::read_versioned;
21use crate::util::{Clock, system_clock};
22use crate::{ApiModule, Request};
23use kernel::Signal;
24use kernel::store::DocumentStore;
25use serde_json::{Map, Value, json};
26use std::collections::HashMap;
27use std::sync::{Arc, Condvar, Mutex};
28use std::time::{Duration, Instant};
29
30pub const TOOL_RESULT_BYTES_ENV: &str = "ULTRON_TOOL_RESULT_BYTES";
31
32pub const TOOL_CALL_MAX_ACTIVE: usize = 32;
33pub const TOOL_CALL_MAX_RETAINED: usize = 64;
34pub const TOOL_CALL_MAX_WAIT_SECONDS: f64 = 3600.0;
35pub const DEFAULT_TOOL_RESULT_BYTES: usize = 256 * 1024;
36pub const MAX_TOOL_RESULT_BYTES: usize = 512 * 1024;
37const PREVIEW_CHARS: usize = 300;
38const DETAILS_MAX_BYTES: usize = 64 * 1024;
39const REPLY_TEXT_MAX_BYTES: usize = 768 * 1024;
40const JOURNAL_VERSION: i64 = 1;
41
42/// What the REPL learns about one extension tool (`ExtensionToolInfo`).
43#[derive(Clone, Debug, PartialEq)]
44pub struct ToolInfo {
45    pub name: String,
46    pub label: Option<String>,
47    pub description: String,
48    pub parameters: Value,
49    /// `"sequential"`: the tool runs alone among its lane's calls (Pi's `executionMode`).
50    pub execution_mode: Option<String>,
51}
52
53/// A running call's partial result (`onUpdate(partial)`: `{content, details?}`).
54pub type ToolUpdate<'a> = &'a (dyn Fn(&Value) + Send + Sync);
55
56/// The session's tools and how to run one (`ExtensionToolRunner`).
57pub trait ToolRunner: Send + Sync {
58    fn tools(&self) -> Vec<ToolInfo>;
59    /// Runs tool `name` to its end (blocking); `cancel` aborts it. Ok is the tool result `{content, details}`.
60    fn execute(&self, name: &str, call_id: &str, params: &Map<String, Value>, cancel: &Signal)
61    -> Result<Value, String>;
62    /// [`ToolRunner::execute`] with the tool's progress reported to `on_update` (`onUpdate`).
63    fn execute_with_updates(
64        &self,
65        name: &str,
66        call_id: &str,
67        params: &Map<String, Value>,
68        cancel: &Signal,
69        on_update: ToolUpdate<'_>,
70    ) -> Result<Value, String>;
71}
72
73/// The preview a call shows while it waits for its lane's gate.
74pub const QUEUED_PREVIEW: &str = "queued: waiting for a sequential tool call on this lane";
75
76/// A first-come-first-served readers-writer gate (`LaneGate`): parallel calls share it, an exclusive call holds it
77/// alone, and a waiting exclusive call keeps later calls from overtaking it. Tickets are granted in [`LaneGate::pump`];
78/// the caller holds the lock that guards the gate and waits on its condition variable.
79#[derive(Default, Debug)]
80pub struct LaneGate {
81    queue: std::collections::VecDeque<(u64, bool)>,
82    granted: std::collections::HashSet<u64>,
83    shared: usize,
84    exclusive: bool,
85}
86
87impl LaneGate {
88    /// Queues `ticket`; true when it is granted at once.
89    pub fn enqueue(&mut self, ticket: u64, exclusive: bool) -> bool {
90        self.queue.push_back((ticket, exclusive));
91        self.pump();
92        self.granted.contains(&ticket)
93    }
94
95    pub fn is_granted(&self, ticket: u64) -> bool {
96        self.granted.contains(&ticket)
97    }
98
99    /// A queued ticket gives up (its call was cancelled); later tickets may now run.
100    pub fn withdraw(&mut self, ticket: u64) {
101        self.queue.retain(|(t, _)| *t != ticket);
102        self.pump();
103    }
104
105    /// A granted ticket's call ended.
106    pub fn release(&mut self, ticket: u64, exclusive: bool) {
107        if !self.granted.remove(&ticket) {
108            return;
109        }
110        if exclusive {
111            self.exclusive = false;
112        } else {
113            self.shared = self.shared.saturating_sub(1);
114        }
115        self.pump();
116    }
117
118    fn pump(&mut self) {
119        while let Some(&(ticket, exclusive)) = self.queue.front() {
120            if self.exclusive || (exclusive && self.shared > 0) {
121                return;
122            }
123            self.queue.pop_front();
124            if exclusive {
125                self.exclusive = true;
126            } else {
127                self.shared += 1;
128            }
129            self.granted.insert(ticket);
130        }
131    }
132}
133
134/// A REPL call's end, as reported to the completion-event dispatcher (`ToolCallEnd`).
135#[derive(Clone, Debug, PartialEq)]
136pub struct ToolCallEnd {
137    /// The journaled record (`ToolCallRecord`).
138    pub call: Value,
139    /// A cell was waiting on this call when it ended (the model already has the result).
140    pub awaited: bool,
141    /// Cancelled because its root turn was aborted: no event.
142    pub root_aborted: bool,
143}
144
145/// The event-relevant view of a call's end: `None` when awaited, root-aborted, or not a REPL call (`toolEvent`).
146pub fn tool_event(end: &ToolCallEnd) -> Option<(String, String, String, String)> {
147    if end.awaited || end.root_aborted || end.call["source"] != "repl" {
148        return None;
149    }
150    let id = end.call["id"].as_str().unwrap_or_default().to_string();
151    Some((
152        id.clone(),
153        end.call["status"].as_str().unwrap_or_default().to_string(),
154        tool_call_summary(&end.call, 240),
155        format!("await tools.result(\"{id}\")"),
156    ))
157}
158
159pub type ToolCallObserver = Arc<dyn Fn(ToolCallEnd) + Send + Sync>;
160/// The usage root (root turn) a lane's call starts under.
161pub type RootOf = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
162
163#[derive(Clone, Debug, PartialEq)]
164struct Outcome {
165    text: String,
166    details: Value,
167    truncated: bool,
168}
169
170struct Live {
171    cancel: Signal,
172    waiters: usize,
173    reason: Option<&'static str>,
174}
175
176#[derive(Default)]
177struct State {
178    loaded: bool,
179    closed: bool,
180    /// Journaled records in start order (`ToolCallRecord` objects).
181    records: Vec<Value>,
182    live: HashMap<String, Live>,
183    outcomes: HashMap<String, Outcome>,
184    /// Per-lane gates that run "sequential" tools alone.
185    gates: HashMap<String, LaneGate>,
186    next_ticket: u64,
187}
188
189struct Inner {
190    runner: Option<Arc<dyn ToolRunner>>,
191    store: Arc<dyn DocumentStore>,
192    output_bytes: usize,
193    max_retained: usize,
194    now: Clock,
195    on_end: Mutex<Option<ToolCallObserver>>,
196    roots: Mutex<Option<RootOf>>,
197    state: Mutex<State>,
198    changed: Condvar,
199}
200
201/// The `tools.*` host module and the session's REPL tool calls.
202#[derive(Clone)]
203pub struct ToolCalls {
204    inner: Arc<Inner>,
205}
206
207/// `toolResultBudget`: ULTRON_TOOL_RESULT_BYTES within 1 KiB..512 KiB, default 256 KiB.
208pub fn tool_result_budget(value: Option<&str>) -> usize {
209    match value.map(str::trim).filter(|v| !v.is_empty()).map(str::parse::<i64>) {
210        Some(Ok(bytes)) if bytes > 0 => (bytes as usize).clamp(1024, MAX_TOOL_RESULT_BYTES),
211        _ => DEFAULT_TOOL_RESULT_BYTES,
212    }
213}
214
215impl ToolCalls {
216    /// `runner` is `None` in a session without extension tools: every call then fails with a clear message.
217    pub fn new(runner: Option<Arc<dyn ToolRunner>>, store: Arc<dyn DocumentStore>) -> Self {
218        Self {
219            inner: Arc::new(Inner {
220                runner,
221                store,
222                output_bytes: tool_result_budget(std::env::var(TOOL_RESULT_BYTES_ENV).ok().as_deref()),
223                max_retained: TOOL_CALL_MAX_RETAINED,
224                now: system_clock(),
225                on_end: Mutex::new(None),
226                roots: Mutex::new(None),
227                state: Mutex::new(State::default()),
228                changed: Condvar::new(),
229            }),
230        }
231    }
232
233    /// Reports each REPL call's end (`onEnd`).
234    pub fn on_end(&self, observer: ToolCallObserver) {
235        *jsrt::sync::lock(&self.inner.on_end) = Some(observer);
236    }
237
238    /// The root a lane's calls start under (`NativeHostApi.rootOf`).
239    pub fn set_roots(&self, roots: RootOf) {
240        *jsrt::sync::lock(&self.inner.roots) = Some(roots);
241    }
242
243    fn runner(&self) -> Result<Arc<dyn ToolRunner>, String> {
244        self.inner
245            .runner
246            .clone()
247            .ok_or_else(|| "Extension tools are not available in this session".to_string())
248    }
249
250    fn now(&self) -> i64 {
251        (self.inner.now)()
252    }
253
254    /// Loads the journal once: a call that was running when its worker stopped is `interrupted`.
255    fn load(&self) -> Result<(), String> {
256        let mut state = jsrt::sync::lock(&self.inner.state);
257        if state.loaded {
258            return Ok(());
259        }
260        let saved = read_versioned("ultron.module/tool-calls", self.inner.store.read()?, "version")?;
261        let calls = saved
262            .as_ref()
263            .and_then(|saved| saved.get("calls"))
264            .and_then(Value::as_array)
265            .cloned()
266            .unwrap_or_default();
267        let pending: Vec<String> = state.records.iter().map(|r| id_of(r).to_string()).collect();
268        let now = self.now();
269        let mut interrupted = false;
270        let mut journaled: Vec<Value> = calls
271            .into_iter()
272            .filter(|call| !pending.iter().any(|id| id == id_of(call)))
273            .map(|mut call| {
274                if call["status"] == "running" {
275                    interrupted = true;
276                    call["status"] = "interrupted".into();
277                    if call["endedAt"].is_null() {
278                        call["endedAt"] = now.into();
279                    }
280                    call["error"] = "worker restarted".into();
281                }
282                call
283            })
284            .collect();
285        journaled.append(&mut state.records);
286        state.records = journaled;
287        state.loaded = true;
288        if interrupted {
289            self.persist(&state);
290        }
291        Ok(())
292    }
293
294    fn persist(&self, state: &State) {
295        let document = json!({"version": JOURNAL_VERSION, "calls": state.records});
296        let _ = self.inner.store.write(&document);
297    }
298
299    fn tool(&self, name: Option<&Value>) -> Result<ToolInfo, String> {
300        let name = name
301            .and_then(Value::as_str)
302            .filter(|n| !n.is_empty())
303            .ok_or("tool name must be a non-empty string")?;
304        let tools = self.runner()?.tools();
305        let normalized = |value: &str| value.replace('-', "_");
306        tools
307            .iter()
308            .find(|t| t.name == name)
309            .or_else(|| tools.iter().find(|t| normalized(&t.name) == normalized(name)))
310            .cloned()
311            .ok_or_else(|| {
312                let names: Vec<&str> = tools.iter().take(20).map(|t| t.name.as_str()).collect();
313                if names.is_empty() {
314                    format!("Unknown extension tool \"{name}\" (no extension tools are registered)")
315                } else {
316                    format!("Unknown extension tool \"{name}\"; available: {}", names.join(", "))
317                }
318            })
319    }
320
321    /// Starts a REPL call of tool `name` on `lane` under `root`; returns its id.
322    pub fn start(
323        &self,
324        lane: &str,
325        root: Option<String>,
326        name: &str,
327        params: Map<String, Value>,
328    ) -> Result<String, String> {
329        let runner = self.runner()?;
330        let id = format!("call-{}", jsrt::random::random_hex(4));
331        let cancel = Signal::new();
332        let exclusive = runner
333            .tools()
334            .iter()
335            .find(|t| t.name == name)
336            .is_some_and(|t| t.execution_mode.as_deref() == Some("sequential"));
337        let ticket;
338        {
339            let mut state = jsrt::sync::lock(&self.inner.state);
340            if state.closed {
341                return Err("Extension tool calls are closed".into());
342            }
343            if state.live.len() >= TOOL_CALL_MAX_ACTIVE {
344                return Err(format!(
345                    "At most {TOOL_CALL_MAX_ACTIVE} extension tool calls can run at once"
346                ));
347            }
348            let mut record = json!({
349                "id": id,
350                "lane": lane,
351                "rootId": root,
352                "source": "repl",
353                "name": name,
354                "label": tool_call_label(name, &params),
355                "input": jsrt::json::preview(&Value::Object(params.clone()), PREVIEW_CHARS),
356                "status": "running",
357                "startedAt": self.now(),
358                "endedAt": null,
359            });
360            // The gate is taken in start order: a call queued behind a sequential one says so.
361            state.next_ticket += 1;
362            ticket = state.next_ticket;
363            if !state
364                .gates
365                .entry(lane.to_string())
366                .or_default()
367                .enqueue(ticket, exclusive)
368            {
369                record["preview"] = QUEUED_PREVIEW.into();
370            }
371            state.live.insert(
372                id.clone(),
373                Live {
374                    cancel: cancel.clone(),
375                    waiters: 0,
376                    reason: None,
377                },
378            );
379            state.records.push(record);
380            self.prune(&mut state);
381            self.persist(&state);
382        }
383        let (calls, call_id, name, lane) = (self.clone(), id.clone(), name.to_string(), lane.to_string());
384        std::thread::spawn(move || {
385            let result = match calls.acquire(&lane, &call_id, ticket, &cancel) {
386                Ok(()) => {
387                    let (updates, update_id) = (calls.clone(), call_id.clone());
388                    let on_update = move |partial: &Value| updates.progress(&update_id, partial);
389                    let result =
390                        runner.execute_with_updates(&name, &format!("repl-{call_id}"), &params, &cancel, &on_update);
391                    let mut state = jsrt::sync::lock(&calls.inner.state);
392                    if let Some(gate) = state.gates.get_mut(&lane) {
393                        gate.release(ticket, exclusive);
394                    }
395                    calls.inner.changed.notify_all();
396                    result
397                }
398                Err(error) => Err(error),
399            };
400            calls.finish(&call_id, result);
401        });
402        Ok(id)
403    }
404
405    /// Waits for the lane's gate; a call cancelled while queued never starts.
406    fn acquire(&self, lane: &str, id: &str, ticket: u64, cancel: &Signal) -> Result<(), String> {
407        let mut state = jsrt::sync::lock(&self.inner.state);
408        loop {
409            let granted = state.gates.get(lane).is_some_and(|g| g.is_granted(ticket));
410            if granted {
411                if let Some(record) = state.records.iter_mut().find(|r| id_of(r) == id)
412                    && record["preview"].as_str().is_some_and(|p| p.starts_with("queued:"))
413                {
414                    record.as_object_mut().map(|r| r.shift_remove("preview"));
415                }
416                return Ok(());
417            }
418            if cancel.is_aborted() {
419                if let Some(gate) = state.gates.get_mut(lane) {
420                    gate.withdraw(ticket);
421                }
422                self.inner.changed.notify_all();
423                return Err(cancel.reason().unwrap_or_else(|| "tool call cancelled".into()));
424            }
425            // Only [`ToolCalls::cancel`] aborts `cancel`, holding this lock, and it notifies `changed` before
426            // releasing it.
427            state = self
428                .inner
429                .changed
430                .wait(state)
431                .unwrap_or_else(std::sync::PoisonError::into_inner);
432        }
433    }
434
435    /// `onUpdate(partial)`: a running call's latest progress text is its preview.
436    fn progress(&self, id: &str, partial: &Value) {
437        let text = result_text(partial);
438        if text.is_empty() {
439            return;
440        }
441        let mut state = jsrt::sync::lock(&self.inner.state);
442        if !state.live.contains_key(id) {
443            return;
444        }
445        if let Some(record) = state.records.iter_mut().find(|r| id_of(r) == id) {
446            record["preview"] = jsrt::json::preview(&Value::from(text), PREVIEW_CHARS).into();
447        }
448    }
449
450    fn finish(&self, id: &str, result: Result<Value, String>) {
451        let end = {
452            let mut state = jsrt::sync::lock(&self.inner.state);
453            let Some(live) = state.live.remove(id) else {
454                return;
455            };
456            let now = self.now();
457            let outcome = match (&result, live.cancel.is_aborted()) {
458                (Ok(result), false) => Some(self.outcome(result)),
459                _ => None,
460            };
461            let Some(index) = state.records.iter().position(|r| id_of(r) == id) else {
462                return;
463            };
464            {
465                let record = state.records[index].as_object_mut().expect("records are objects");
466                record.insert("endedAt".into(), now.into());
467                if live.cancel.is_aborted() {
468                    record.insert("status".into(), "cancelled".into());
469                    record.shift_remove("preview");
470                } else if let Err(error) = &result {
471                    record.insert("status".into(), "failed".into());
472                    let shown = if error.chars().count() > 2000 {
473                        format!("{}…", error.chars().take(1999).collect::<String>())
474                    } else {
475                        error.clone()
476                    };
477                    record.insert("error".into(), shown.into());
478                    record.insert(
479                        "preview".into(),
480                        jsrt::json::preview(&Value::from(error.as_str()), PREVIEW_CHARS).into(),
481                    );
482                } else if let Some(outcome) = &outcome {
483                    record.insert("status".into(), "completed".into());
484                    record.insert(
485                        "preview".into(),
486                        jsrt::json::preview(&Value::from(outcome.text.as_str()), PREVIEW_CHARS).into(),
487                    );
488                }
489            }
490            if let Some(outcome) = outcome {
491                state.outcomes.insert(id.to_string(), outcome);
492            }
493            self.persist(&state);
494            let call = state.records[index].clone();
495            self.inner.changed.notify_all();
496            (live.reason != Some("closed")).then(|| ToolCallEnd {
497                call,
498                awaited: live.waiters > 0,
499                root_aborted: live.reason == Some("root_aborted"),
500            })
501        };
502        if let Some(end) = end {
503            let observer = jsrt::sync::lock(&self.inner.on_end).clone();
504            if let Some(observer) = observer {
505                // Observers never affect a call.
506                let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| observer(end)));
507            }
508        }
509    }
510
511    /// The result text bounded to the output budget (and the kernel frame), and the details bounded to 64 KiB.
512    fn outcome(&self, result: &Value) -> Outcome {
513        let raw = result_text(result);
514        let mut budget = self.inner.output_bytes;
515        let mut text = host::cell::truncate_tool_output(&raw, budget, None);
516        // JSON escaping can grow text (control characters six-fold): keep the reply within the kernel's frame.
517        while jsrt::json::stringify(&Value::from(text.as_str())).len() > REPLY_TEXT_MAX_BYTES && budget > 1024 {
518            budget /= 2;
519            text = host::cell::truncate_tool_output(&raw, budget, None);
520        }
521        let mut details = result.get("details").cloned().unwrap_or(Value::Null);
522        if !details.is_null() && jsrt::json::stringify(&details).len() > DETAILS_MAX_BYTES {
523            details = json!({"truncated": true, "preview": jsrt::json::preview(&details, 2000)});
524        }
525        Outcome {
526            truncated: text != raw,
527            text,
528            details,
529        }
530    }
531
532    /// Waits for call `id` at most `seconds` (`None`: until it ends), or until `signal` (the calling cell) aborts.
533    fn wait(&self, id: &str, seconds: Option<f64>, signal: &Signal) {
534        let deadline = seconds.map(|s| Instant::now() + Duration::from_secs_f64((s * 1000.0).max(20.0) / 1000.0));
535        let mut state = jsrt::sync::lock(&self.inner.state);
536        match state.live.get_mut(id) {
537            Some(live) => live.waiters += 1,
538            None => return,
539        }
540        loop {
541            if !state.live.contains_key(id) || signal.is_aborted() {
542                break;
543            }
544            let mut slice = Duration::from_millis(50);
545            if let Some(deadline) = deadline {
546                let now = Instant::now();
547                if now >= deadline {
548                    break;
549                }
550                slice = slice.min(deadline - now);
551            }
552            state = self
553                .inner
554                .changed
555                .wait_timeout(state, slice)
556                .unwrap_or_else(std::sync::PoisonError::into_inner)
557                .0;
558        }
559        if let Some(live) = state.live.get_mut(id) {
560            live.waiters -= 1;
561        }
562    }
563
564    /// Stops call `id` and waits for its end (`reason`: `cancelled`, `root_aborted` or `closed`).
565    pub fn cancel(&self, id: &str, reason: &'static str) {
566        let mut state = jsrt::sync::lock(&self.inner.state);
567        let Some(live) = state.live.get_mut(id) else {
568            return;
569        };
570        live.reason.get_or_insert(reason);
571        live.cancel.abort(if reason == "root_aborted" {
572            "turn aborted"
573        } else {
574            "tool call cancelled"
575        });
576        self.inner.changed.notify_all();
577        while state.live.contains_key(id) {
578            state = self
579                .inner
580                .changed
581                .wait(state)
582                .unwrap_or_else(std::sync::PoisonError::into_inner);
583        }
584    }
585
586    /// Esc aborted a root turn: stop every REPL call started under it.
587    pub fn cancel_root(&self, root: &str) {
588        let ids: Vec<String> = {
589            let state = jsrt::sync::lock(&self.inner.state);
590            state
591                .records
592                .iter()
593                .filter(|r| state.live.contains_key(id_of(r)) && r["rootId"].as_str() == Some(root))
594                .map(|r| id_of(r).to_string())
595                .collect()
596        };
597        for id in ids {
598            self.cancel(&id, "root_aborted");
599        }
600    }
601
602    /// Running REPL calls of `lane` whose root is not `excluded`.
603    pub fn running(&self, lane: &str, excluded: &dyn Fn(Option<&str>) -> bool) -> usize {
604        let state = jsrt::sync::lock(&self.inner.state);
605        state
606            .records
607            .iter()
608            .filter(|r| state.live.contains_key(id_of(r)) && r["lane"] == lane && !excluded(r["rootId"].as_str()))
609            .count()
610    }
611
612    /// Running and recent calls (`agents.status`), newest first.
613    pub fn list(&self) -> Vec<Value> {
614        jsrt::sync::lock(&self.inner.state)
615            .records
616            .iter()
617            .rev()
618            .cloned()
619            .collect()
620    }
621
622    /// Stops every running call without reporting their ends.
623    pub fn close(&self) {
624        let ids: Vec<String> = {
625            let mut state = jsrt::sync::lock(&self.inner.state);
626            state.closed = true;
627            state.live.keys().cloned().collect()
628        };
629        for id in ids {
630            self.cancel(&id, "closed");
631        }
632    }
633
634    /// The wire form of a call for the kernel's ToolCall / ToolResult (`ToolCallSnapshot`).
635    fn snapshot(&self, state: &State, record: &Value) -> Value {
636        let id = id_of(record);
637        let outcome = state.outcomes.get(id);
638        let status = record["status"].as_str().unwrap_or_default();
639        let ended = record["endedAt"].as_i64().unwrap_or_else(|| self.now());
640        let elapsed = (((ended - record["startedAt"].as_i64().unwrap_or(ended)) as f64) / 100.0).round() / 10.0;
641        let error = match record.get("error") {
642            Some(error) => error.clone(),
643            None if status == "completed" && outcome.is_none() => {
644                "the result is no longer held (the worker restarted or the call is too old)".into()
645            }
646            None => Value::Null,
647        };
648        json!({
649            "id": id,
650            "name": record["name"],
651            "label": record["label"],
652            "lane": record["lane"],
653            "status": status,
654            "running": status == "running",
655            "ok": status == "completed",
656            "text": outcome.map(|o| Value::from(o.text.as_str())).unwrap_or(Value::Null),
657            "details": outcome.map(|o| o.details.clone()).unwrap_or(Value::Null),
658            "truncated": outcome.is_some_and(|o| o.truncated),
659            "elapsed_seconds": elapsed,
660            "error": error,
661        })
662    }
663
664    fn snapshot_of(&self, id: &str) -> Result<Value, String> {
665        let state = jsrt::sync::lock(&self.inner.state);
666        let record = state
667            .records
668            .iter()
669            .find(|r| id_of(r) == id)
670            .ok_or_else(|| format!("Unknown tool call {id}"))?;
671        Ok(self.snapshot(&state, record))
672    }
673
674    /// The root lane sees every REPL call; a child lane sees its own.
675    fn visible(&self, id: Option<&Value>, lane: &str) -> Result<String, String> {
676        let id = id
677            .and_then(Value::as_str)
678            .filter(|id| !id.is_empty())
679            .ok_or("call id must be a nonempty string")?;
680        let state = jsrt::sync::lock(&self.inner.state);
681        match state.records.iter().find(|r| id_of(r) == id) {
682            Some(record) if kernel::sees(lane, record["lane"].as_str().unwrap_or_default()) => Ok(id.to_string()),
683            _ => Err(format!("Unknown tool call {id}")),
684        }
685    }
686
687    fn is_live(&self, id: &str) -> bool {
688        jsrt::sync::lock(&self.inner.state).live.contains_key(id)
689    }
690
691    /// Bounded retention: drop the oldest finished calls beyond the cap.
692    fn prune(&self, state: &mut State) {
693        let excess = state.records.len().saturating_sub(self.inner.max_retained);
694        if excess == 0 {
695            return;
696        }
697        let drop: Vec<String> = state
698            .records
699            .iter()
700            .filter(|r| r["status"] != "running")
701            .take(excess)
702            .map(|r| id_of(r).to_string())
703            .collect();
704        for id in &drop {
705            state.outcomes.remove(id);
706        }
707        state.records.retain(|r| !drop.iter().any(|id| id == id_of(r)));
708    }
709
710    fn handle_request(&self, request: &Request<'_>) -> Result<Value, String> {
711        self.load()?;
712        let payload = request.payload;
713        match request.kind {
714            "tools.list" => {
715                kernel::ops::fields("tools.list", payload)?;
716                Ok(Value::Array(
717                    self.runner()?
718                        .tools()
719                        .into_iter()
720                        .map(|tool| {
721                            let mut item = Map::new();
722                            item.insert("name".into(), tool.name.into());
723                            if let Some(label) = tool.label {
724                                item.insert("label".into(), label.into());
725                            }
726                            item.insert("description".into(), first_paragraph(&tool.description, 400).into());
727                            Value::Object(item)
728                        })
729                        .collect(),
730                ))
731            }
732            "tools.describe" => {
733                kernel::ops::fields("tools.describe", payload)?;
734                let tool = self.tool(payload.get("name"))?;
735                let mut item = Map::new();
736                item.insert("name".into(), tool.name.into());
737                if let Some(label) = tool.label {
738                    item.insert("label".into(), label.into());
739                }
740                item.insert("description".into(), tool.description.into());
741                item.insert("parameters".into(), tool.parameters);
742                Ok(Value::Object(item))
743            }
744            "tools.call" => {
745                // Wait up to `yield_after` seconds (absent: until the call ends). A call still running when a
746                // waiting cell is stopped is cancelled, unless the kernel asked for a handle (`detach`).
747                kernel::ops::fields("tools.call", payload)?;
748                let tool = self.tool(payload.get("name"))?;
749                let params = match payload.get("params") {
750                    None | Some(Value::Null) => Map::new(),
751                    Some(Value::Object(params)) => params.clone(),
752                    Some(_) => return Err("tool params must be a dict (a JSON object)".into()),
753                };
754                let yield_after = wait_seconds(payload.get("yield_after"), "yield_after")?;
755                let root = jsrt::sync::lock(&self.inner.roots)
756                    .clone()
757                    .and_then(|roots| roots(request.lane));
758                let id = self.start(request.lane, root, &tool.name, params)?;
759                self.wait(&id, yield_after, request.signal);
760                if self.is_live(&id) && request.signal.is_aborted() && payload.get("detach") != Some(&Value::Bool(true))
761                {
762                    {
763                        let mut state = jsrt::sync::lock(&self.inner.state);
764                        if let Some(live) = state.live.get_mut(&id) {
765                            live.waiters += 1;
766                        }
767                    }
768                    self.cancel(&id, "cancelled");
769                }
770                self.snapshot_of(&id)
771            }
772            "tools.result" => {
773                kernel::ops::fields("tools.result", payload)?;
774                let id = self.visible(payload.get("id"), request.lane)?;
775                if self.is_live(&id) {
776                    let wait = wait_seconds(payload.get("wait"), "wait")?;
777                    self.wait(&id, wait, request.signal);
778                }
779                self.snapshot_of(&id)
780            }
781            "tools.get" => {
782                kernel::ops::fields("tools.get", payload)?;
783                let id = self.visible(payload.get("id"), request.lane)?;
784                self.snapshot_of(&id)
785            }
786            "tools.cancel" => {
787                kernel::ops::fields("tools.cancel", payload)?;
788                let id = self.visible(payload.get("id"), request.lane)?;
789                self.cancel(&id, "cancelled");
790                self.snapshot_of(&id)
791            }
792            "tools.calls" => {
793                kernel::ops::fields("tools.calls", payload)?;
794                let state = jsrt::sync::lock(&self.inner.state);
795                Ok(Value::Array(
796                    state
797                        .records
798                        .iter()
799                        .rev()
800                        .filter(|r| kernel::sees(request.lane, r["lane"].as_str().unwrap_or_default()))
801                        .map(|r| {
802                            let mut snapshot = self.snapshot(&state, r);
803                            snapshot["text"] = Value::Null;
804                            snapshot["details"] = Value::Null;
805                            snapshot["source"] = r["source"].clone();
806                            snapshot
807                        })
808                        .collect(),
809                ))
810            }
811            other => Err(kernel::ops::not_wired(other)),
812        }
813    }
814}
815
816impl ApiModule for ToolCalls {
817    fn prefixes(&self) -> &[&str] {
818        &["tools."]
819    }
820
821    fn start(&self, _host: &dyn crate::TaskHost) -> Result<(), String> {
822        self.load()
823    }
824
825    fn handle(&self, request: &Request<'_>) -> Result<Value, String> {
826        self.handle_request(request)
827    }
828}
829
830fn id_of(record: &Value) -> &str {
831    record["id"].as_str().unwrap_or_default()
832}
833
834fn wait_seconds(value: Option<&Value>, name: &str) -> Result<Option<f64>, String> {
835    match value {
836        None | Some(Value::Null) => Ok(None),
837        Some(Value::Number(n)) if n.as_f64().is_some_and(|s| s.is_finite() && s >= 0.0) => {
838            Ok(n.as_f64().map(|s| s.min(TOOL_CALL_MAX_WAIT_SECONDS)))
839        }
840        Some(_) => Err(format!("{name} must be a non-negative number of seconds")),
841    }
842}
843
844fn first_paragraph(text: &str, limit: usize) -> String {
845    let trimmed = jsrt::string::trim(text);
846    let paragraph = fancy_regex::Regex::new(r"\n\s*\n")
847        .ok()
848        .and_then(|re| re.find(trimmed).ok().flatten())
849        .map_or(trimmed, |found| &trimmed[..found.start()]);
850    jsrt::json::preview(&Value::from(paragraph), limit)
851}
852
853/// The text of a tool result: text parts joined; other parts named (`resultText`).
854pub fn result_text(result: &Value) -> String {
855    let Some(content) = result.get("content").and_then(Value::as_array) else {
856        return String::new();
857    };
858    content
859        .iter()
860        .filter_map(|part| {
861            let part = part.as_object()?;
862            let kind = part.get("type").and_then(Value::as_str);
863            match (kind, part.get("text").and_then(Value::as_str)) {
864                (Some("text"), Some(text)) => Some(text.to_string()),
865                (Some("image"), _) => Some(match part.get("mimeType").and_then(Value::as_str) {
866                    Some(mime) => format!("[image {mime}]"),
867                    None => "[image]".into(),
868                }),
869                (Some(kind), _) => Some(format!("[{kind}]")),
870                (None, _) => None,
871            }
872        })
873        .filter(|text| !text.is_empty())
874        .collect::<Vec<_>>()
875        .join("\n")
876}
877
878/// A short label for the graph; the `mcp` gateway is labelled by its mode (`toolCallLabel`).
879pub fn tool_call_label(name: &str, params: &Map<String, Value>) -> String {
880    if name != "mcp" {
881        return name.to_string();
882    }
883    let text = |key: &str| params.get(key).and_then(Value::as_str).filter(|s| !s.is_empty());
884    if let Some(tool) = text("tool") {
885        return format!("mcp {tool}");
886    }
887    if let Some(action) = text("action") {
888        return match text("server") {
889            Some(server) => format!("mcp {action} {server}"),
890            None => format!("mcp {action}"),
891        };
892    }
893    if let Some(server) = text("connect") {
894        return format!("mcp connect {server}");
895    }
896    if let Some(name) = text("describe") {
897        return format!("mcp describe {name}");
898    }
899    if let Some(server) = text("instructions") {
900        return format!("mcp instructions {server}");
901    }
902    if let Some(search) = params.get("search") {
903        return format!("mcp search {}", jsrt::json::stringify(search));
904    }
905    if let Some(uri) = text("read") {
906        return format!("mcp read {uri}");
907    }
908    if params
909        .get("resources")
910        .is_some_and(|r| !matches!(r, Value::Null | Value::Bool(false)) && r != "")
911    {
912        return match text("resources").or(text("server")) {
913            Some(server) => format!("mcp resources {server}"),
914            None => "mcp resources".into(),
915        };
916    }
917    if let Some(server) = text("server") {
918        return format!("mcp list {server}");
919    }
920    "mcp status".into()
921}
922
923/// One-line completion summary for a runtime event (`toolCallSummary`).
924pub fn tool_call_summary(call: &Value, max_chars: usize) -> String {
925    let status = call["status"].as_str().unwrap_or_default();
926    let shown = match call.get("error").and_then(Value::as_str) {
927        _ if status == "completed" => "ok".to_string(),
928        Some(error) if !error.is_empty() => format!("{status}: {error}"),
929        _ => status.to_string(),
930    };
931    let body = match call.get("preview").and_then(Value::as_str) {
932        Some(preview) if status == "completed" && !preview.is_empty() => format!("; {preview}"),
933        _ => String::new(),
934    };
935    let text = format!("{}: {shown}{body}", call["label"].as_str().unwrap_or_default());
936    let text = text.split_whitespace().collect::<Vec<_>>().join(" ");
937    if text.chars().count() > max_chars {
938        format!("{}…", text.chars().take(max_chars - 1).collect::<String>())
939    } else {
940        text
941    }
942}