Skip to main content

leviath_runtime/pipeline/
tools.rs

1//! Tool dispatch: batching, policy triage, and handing calls to the tool lane.
2
3use super::*;
4
5/// The agent's tool batch has been handed to the tool lane; it is waiting for
6/// the results (which the tool-collect system will apply).
7#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
8pub struct AwaitingTools;
9
10/// Marker: this agent's advertised tools should be re-resolved before its next
11/// turn - mid-run dynamic tool discovery. Consumed by
12/// [`refresh_advertised_tools`], which asks the [`ToolService`] for the stage's
13/// fresh tool defs and writes them into the live [`StageInference`].
14#[derive(Component, Debug, Clone, Copy)]
15pub struct ToolsNeedRefresh;
16
17/// Marker: this agent opted into `dynamic_tools`. Only such agents
18/// are polled by [`poll_dynamic_tool_refresh`] for a pending tool re-scan, so the
19/// default (static) agent pays nothing.
20#[derive(Component, Debug, Clone, Copy)]
21pub struct DynamicTools;
22
23/// Reports one tool call's result the moment it resolves, from inside the
24/// executor - `(tool_call_id, result)`. Dispatch builds one per batch to journal
25/// each completion as a `ToolCallDone` record, so a crash mid-batch loses only
26/// the calls that genuinely never finished (issue #96). Implementors that don't
27/// journal get a no-op.
28pub type ToolProgress = Arc<dyn Fn(&str, &str) + Send + Sync>;
29
30/// A [`ToolProgress`] that reports nowhere - for worlds without a persistence
31/// lane and for `ToolService` impls under test.
32pub fn noop_progress() -> ToolProgress {
33    Arc::new(|_, _| {})
34}
35
36/// Provides a per-agent tool-execution closure. The concrete implementation
37/// (in the CLI) holds each agent's tool registry, workdir, and permission
38/// policy; the pipeline stays agnostic to *how* tools run. `exec_for` returns a
39/// boxed closure the tool worker runs off the tick.
40pub trait ToolService: Send + Sync {
41    /// Build the closure that runs `calls` for `entity`, resolving `(id, result)`
42    /// pairs. The executor calls `progress` with each call's result as it
43    /// resolves (per-call, not at batch end).
44    fn exec_for(
45        &self,
46        entity: Entity,
47        calls: Vec<leviath_providers::ToolCall>,
48        progress: ToolProgress,
49    ) -> BoxedToolExec;
50
51    /// Notify the service that `entity` entered the stage at `stage_index` named
52    /// `stage_name`, so it can re-sync that agent's per-stage tool permissions.
53    /// Default no-op for services without per-stage policy.
54    fn sync_stage(&self, _entity: Entity, _stage_index: usize, _stage_name: &str) {}
55
56    /// Re-resolve `entity`'s advertised tool defs for the stage at `stage_index` -
57    /// e.g. after new tools were discovered on disk. `None` means "no change"
58    /// (the default, for services without dynamic tools); `Some(tools)` replaces
59    /// the stage's advertised set.
60    fn refresh_tools(
61        &self,
62        _entity: Entity,
63        _stage_index: usize,
64    ) -> Option<Vec<leviath_providers::Tool>> {
65        None
66    }
67
68    /// Whether `entity` (a `dynamic_tools` agent) has pending tool changes that
69    /// warrant a re-scan + re-advertise. Polled by [`poll_dynamic_tool_refresh`];
70    /// implementors return (and clear) a per-agent dirty flag. Default `false`.
71    fn wants_refresh(&self, _entity: Entity) -> bool {
72        false
73    }
74}
75
76/// The tool service, as a world resource.
77#[derive(Resource, Clone)]
78pub struct ToolServiceRes(pub Arc<dyn ToolService>);
79
80/// The job sender feeding the tool lane, as a world resource, paired with the
81/// lane's occupancy counters so dispatch can record what it queued.
82#[derive(Resource, Clone)]
83pub struct ToolStage {
84    /// Where batches are handed to the lane.
85    pub jobs: UnboundedSender<ToolJob>,
86    /// Shared with the lane's workers; see [`crate::tool_bridge::ToolLaneStats`].
87    pub stats: Arc<crate::tool_bridge::ToolLaneStats>,
88}
89
90impl ToolStage {
91    /// A stage wired to a real lane's counters.
92    pub fn new(
93        jobs: UnboundedSender<ToolJob>,
94        stats: Arc<crate::tool_bridge::ToolLaneStats>,
95    ) -> Self {
96        Self { jobs, stats }
97    }
98
99    /// A stage with counters of its own, for callers that drive `dispatch_tools`
100    /// without a lane behind it (tests read the channel directly).
101    pub fn detached(jobs: UnboundedSender<ToolJob>) -> Self {
102        Self::new(jobs, Arc::new(crate::tool_bridge::ToolLaneStats::new(1)))
103    }
104}
105
106/// Context-tool results computed inline by [`dispatch_tools`] (the `context_*`
107/// tools mutate the ECS window, so they can't run on the async lane), held until
108/// [`collect_tools`] merges them with the lane results. Absent when a batch had
109/// no context tools.
110#[derive(Component, Debug, Clone, Default)]
111pub struct ContextToolResults(pub Vec<(String, String)>);
112
113/// Merge context + lane tool results into one `(id, result)` list in the
114/// original tool-call order (Anthropic requires a `tool_result` per `tool_use`,
115/// in order).
116/// Collapse a possibly-multiline string to a single trimmed line capped at
117/// `max` characters (with an ellipsis when truncated), for one-line log entries.
118pub(crate) fn one_line(s: &str, max: usize) -> String {
119    let flat = s.split_whitespace().collect::<Vec<_>>().join(" ");
120    if flat.chars().count() > max {
121        format!("{}…", flat.chars().take(max).collect::<String>())
122    } else {
123        flat
124    }
125}
126
127pub(crate) fn merge_in_call_order(
128    tool_calls: &[crate::components::ToolCall],
129    parts: &[(String, String)],
130) -> Vec<(String, String)> {
131    tool_calls
132        .iter()
133        .map(|tc| {
134            let result = parts
135                .iter()
136                .find(|(id, _)| id == &tc.tool_id)
137                .map(|(_, r)| r.clone())
138                .unwrap_or_default();
139            (tc.tool_id.clone(), result)
140        })
141        .collect()
142}
143
144/// Whether a tool result describes a call whose side effect never happened.
145///
146/// `[error]` (it ran and failed), `[denied]` (policy refused it),
147/// `[unavailable]` (the stage never offered it) and `[blocked]` (the taint
148/// gate stopped it) all mean the same thing to anything reasoning about what
149/// the agent *did*: file tracking must not record a write that was not
150/// written, and the modification counters behind a transition gate must not
151/// count it as work. Separate prefix lists are exactly how a new prefix gets
152/// missed - `[unavailable]` was, when dispatch began refusing unoffered tools
153/// and both call sites still listed only two, and `[blocked]` was again, so a
154/// taint-blocked write counted as a modification until issue #155's pass.
155pub(crate) fn call_had_no_effect(result: &str) -> bool {
156    result.starts_with("[error]")
157        || result.starts_with("[denied]")
158        || result.starts_with("[unavailable]")
159        || result.starts_with("[blocked]")
160}
161
162/// The effective tool names this stage advertised, canonicalised.
163///
164/// The same narrowing the request builder applies: `tools`, then `tool_filter`
165/// when it is set and non-empty. Deriving both from one function is what keeps
166/// "what the model was offered" and "what the model may call" the same set.
167pub(crate) fn offered_tool_names(stage: &StageInference) -> Vec<&str> {
168    stage
169        .tools
170        .iter()
171        .filter(|t| match stage.tool_filter.as_deref() {
172            Some(filter) if !filter.is_empty() => filter.iter().any(|f| f == &t.name),
173            _ => true,
174        })
175        .map(|t| leviath_tools::canonical_tool_name(&t.name))
176        .collect()
177}
178
179/// `Some(message)` when `name` is not among the stage's advertised tools.
180///
181/// The message is written for the model, not the user: it says plainly that the
182/// tool does not exist *here* and lists what does, so the next turn is a usable
183/// call rather than a retry of the same one. A stage advertising nothing says so
184/// instead of printing an empty list.
185pub(crate) fn unoffered_tool_refusal(stage: &StageInference, name: &str) -> Option<String> {
186    let canonical = leviath_tools::canonical_tool_name(name);
187    let offered = offered_tool_names(stage);
188    if offered.contains(&canonical) {
189        return None;
190    }
191    Some(match offered.is_empty() {
192        true => format!(
193            "[unavailable] '{name}' is not available in this stage, which has no \
194             tools at all. Answer directly instead of calling a tool."
195        ),
196        false => format!(
197            "[unavailable] '{name}' is not available in this stage. You may call: {}.",
198            offered.join(", ")
199        ),
200    })
201}
202
203/// How long a dispatched batch may wait for its journal record's ack before
204/// running anyway. The wait is what keeps the `ToolBatch` record on disk ahead
205/// of the batch's side effects; the bound is the liveness valve - a dead or
206/// backed-up persistence worker degrades to an unjournaled dispatch instead of
207/// wedging every tool batch behind it.
208pub(crate) const BATCH_JOURNAL_ACK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1);
209
210/// Wrap a tool-execution closure so it first waits (bounded) for the batch's
211/// journal-record ack. Both outcomes - acked, or timeout/dropped sender -
212/// proceed to run the batch.
213pub(crate) fn barrier_then(
214    exec: BoxedToolExec,
215    ack: tokio::sync::oneshot::Receiver<()>,
216    timeout: std::time::Duration,
217) -> BoxedToolExec {
218    Box::new(move || {
219        Box::pin(async move {
220            let _ = tokio::time::timeout(timeout, ack).await;
221            exec().await
222        })
223    })
224}
225
226/// `Some(refusal)` when `name`'s arguments do not satisfy the schema the
227/// stage advertised for it.
228///
229/// The def is found by canonicalising both the called name and each advertised
230/// name, the same resolution `offered_tool_names` applies, so a tool offered
231/// as `bash` validates a call to `shell` and vice versa. A name with no def
232/// here validates as fine - after the unoffered-tool check that cannot happen,
233/// and the schema's absence is not the model's mistake to be refused over.
234///
235/// A schema that does not compile (a typo'd Rhai `@param` type, an MCP
236/// fragment this crate cannot interpret) is logged and skipped rather than
237/// refused: validation must never turn a working tool into an unusable one.
238///
239/// Schemas are compiled per call, deliberately. They are small, calls arrive
240/// at model latency, and a compiled-validator cache would need invalidating on
241/// every dynamic-tools re-advertisement and scoping per agent - real
242/// complexity for unmeasurable savings.
243pub(crate) fn invalid_args_refusal(
244    stage: &StageInference,
245    name: &str,
246    args: &serde_json::Value,
247) -> Option<String> {
248    let canonical = leviath_tools::canonical_tool_name(name);
249    let tool = stage
250        .tools
251        .iter()
252        .find(|t| leviath_tools::canonical_tool_name(&t.name) == canonical)?;
253    match leviath_tools::validate_tool_args(name, &tool.parameters, args) {
254        leviath_tools::ArgValidation::Valid => None,
255        leviath_tools::ArgValidation::SchemaUnusable(e) => {
256            tracing::warn!(
257                tool = %name,
258                error = %e,
259                "tool schema did not compile; skipping argument validation"
260            );
261            None
262        }
263        leviath_tools::ArgValidation::Invalid(msg) => Some(msg),
264    }
265}
266
267/// Tool-dispatch system: for each `ReadyForTools` agent, apply its `context_*`
268/// tool calls inline (they mutate the ECS window) and hand the rest to the
269/// sequential tool lane, moving it to `AwaitingTools`. If a batch is *all*
270/// context tools there is nothing for the lane, so the results are applied
271/// immediately and the agent loops straight back to `ReadyToInfer`. The lane
272/// serializes execution, so there is no permit gate - every ready agent is
273/// enqueued in turn.
274///
275/// A persisted agent's batch is journaled at dispatch: a `ToolBatch` record
276/// (inline results pre-filled, lane calls pending) goes to the persistence lane
277/// with an ack the exec waits on, and a per-call [`ToolProgress`] journals each
278/// completion as a `ToolCallDone`. On a crash mid-batch, recovery replays the
279/// recorded results instead of re-running their side effects (issue #96).
280#[allow(clippy::type_complexity, clippy::too_many_arguments)]
281pub fn dispatch_tools(
282    mut agents: Query<
283        (
284            Entity,
285            &AgentState,
286            &StageInference,
287            &crate::components::InferenceResult,
288            &mut ContextWindow,
289            Option<&crate::components::ToolResultRoutingComponent>,
290            Option<&ToolSensitivities>,
291            Option<&mut crate::taint::TaintGate>,
292            Option<&crate::gate_prompt::GateResolved>,
293            Option<&crate::components::GateAutoApprove>,
294            Option<&InFlightWork>,
295            Option<&StageCursor>,
296            Option<&RunMetadata>,
297        ),
298        With<ReadyForTools>,
299    >,
300    service: Res<ToolServiceRes>,
301    stage: Res<ToolStage>,
302    policy: Option<Res<PolicyGate>>,
303    script_rules: Option<Res<GateScriptRules>>,
304    hub: Option<Res<InteractionHub>>,
305    gate_stage: Option<Res<crate::gate_prompt::GatePromptStage>>,
306    persist: Option<Res<PersistenceStage>>,
307    sink: Option<Res<crate::host::WorldEventSink>>,
308    mut commands: Commands,
309) {
310    crate::tick_scope::clear();
311    let default_policy = leviath_core::PolicyConfig::default();
312    let policy_ref = policy.as_ref().map(|p| &p.0).unwrap_or(&default_policy);
313    let script_checker = script_rules.as_ref().map(|r| r.0.as_ref());
314    // Interactive gate prompting is available only when both the hub and the
315    // gate-prompt lane are wired (the daemon); otherwise blocks are returned as
316    // `[blocked]` immediately, preserving the headless/non-interactive behavior.
317    let interactive = hub.as_ref().zip(gate_stage.as_ref());
318    for (
319        entity,
320        state,
321        stage_inf,
322        result,
323        mut window,
324        routing,
325        sensitivities,
326        mut gate,
327        resolved,
328        auto_gate,
329        in_flight,
330        cursor,
331        metadata,
332    ) in agents.iter_mut()
333    {
334        crate::tick_scope::enter(entity);
335        // `--yolo`: waive taint-gate enforcement so a headless run never blocks
336        // on a gate prompt no one can answer (taint tracking still records).
337        let auto_approve_gates = auto_gate.is_some();
338        if state.status != AgentStatus::Active {
339            continue; // paused / waiting / cancelled - don't start new work
340        }
341
342        // Apply context_* tools inline (they need world access); collect the rest
343        // for the async lane. A taint-gated agent's outbound call that would leak
344        // over-cleared data (and isn't allowlisted) is blocked - either returned
345        // as `[blocked]`, or (interactive) held for a user gate prompt.
346        let mut context_results = Vec::new();
347        let mut lane_calls = Vec::new();
348        // (tool_id, name, taint, clearance) for blocked calls awaiting a prompt.
349        let mut pending_prompts: Vec<(
350            String,
351            String,
352            leviath_core::TaintLevel,
353            leviath_core::TaintLevel,
354        )> = Vec::new();
355        for c in &result.tool_calls {
356            // Layer 1, enforced rather than merely advertised.
357            //
358            // A stage's `available_tools` was applied only when building the
359            // schema list sent to the model. Nothing checked it again here, so a
360            // model that *named* a tool it had never been offered got that call
361            // dispatched anyway - reaching the permission gate, and for a
362            // default-`Ask` tool surfacing to the user as an approval prompt for
363            // something the stage was never granted.
364            //
365            // That is not hypothetical. A `plan` stage granting only
366            // `read_file`/`list_dir`/`ask_user_*`/`edit_document` emitted
367            // `write_file` with a complete source file in it, and the user was
368            // asked to approve writing code from the planning stage. Declining
369            // it was the only thing that stopped it.
370            //
371            // Checked against `StageInference`, which *is* the set advertised
372            // for this stage - resolved at spawn, swapped on every transition,
373            // and rewritten by the dynamic-tools refresh - so enforcement cannot
374            // drift from advertising the way a second copy of the rule would.
375            if let Some(refusal) = unoffered_tool_refusal(stage_inf, &c.name) {
376                context_results.push((c.tool_id.clone(), refusal));
377                continue;
378            }
379            // Layer 2: the call must satisfy the schema the model was shown.
380            // A mismatched call is refused back to the model with the
381            // validator's message, so the next turn can self-correct, rather
382            // than executed on garbage or surfaced to the user as a permission
383            // prompt for arguments that were never valid. Deterministic, so a
384            // gate-prompt re-run of the same batch refuses identically.
385            if let Some(refusal) = invalid_args_refusal(stage_inf, &c.name, &c.arguments) {
386                context_results.push((c.tool_id.clone(), refusal));
387                continue;
388            }
389            if crate::context_tools::is_context_tool(&c.name) {
390                let text =
391                    crate::context_tools::handle_context_tool(&c.name, &c.arguments, &mut window);
392                context_results.push((c.tool_id.clone(), text));
393                continue;
394            }
395            // A call the user already resolved in a prior prompt round.
396            if let Some(resolved) = resolved {
397                if let Some(msg) = resolved.denied.get(&c.tool_id) {
398                    context_results.push((c.tool_id.clone(), msg.clone()));
399                    continue;
400                }
401                if resolved.approved.contains(&c.tool_id) {
402                    lane_calls.push(leviath_providers::ToolCall {
403                        id: c.tool_id.clone(),
404                        name: c.name.clone(),
405                        arguments: c.arguments.clone(),
406                        thought_signature: c.thought_signature.clone(),
407                    });
408                    continue;
409                }
410            }
411            if let Some(gate) = gate.as_deref_mut() {
412                let decision = gate.check_with_policy(
413                    &state.agent_id,
414                    &c.name,
415                    &window,
416                    None,
417                    policy_ref,
418                    script_checker,
419                );
420                if !decision.is_allowed() {
421                    if auto_approve_gates {
422                        // `--yolo`: waive enforcement but record the override in
423                        // the audit trail (rather than skipping the gate), so the
424                        // over-cleared call is still accounted for. Fall through
425                        // to dispatch the call.
426                        let (taint, clearance) = decision
427                            .blocked_levels()
428                            .expect("a non-Allowed GateDecision is always Blocked");
429                        gate.record_allow(
430                            &state.agent_id,
431                            &c.name,
432                            taint,
433                            clearance,
434                            leviath_core::taint::GateDecisionSource::YoloAutoApprove,
435                        );
436                    } else {
437                        match (interactive, decision.blocked_levels()) {
438                            (Some(_), Some((taint, clearance))) => {
439                                pending_prompts.push((
440                                    c.tool_id.clone(),
441                                    c.name.clone(),
442                                    taint,
443                                    clearance,
444                                ));
445                            }
446                            _ => {
447                                context_results
448                                    .push((c.tool_id.clone(), taint_block_message(&decision)));
449                            }
450                        }
451                        continue;
452                    }
453                }
454            }
455            lane_calls.push(leviath_providers::ToolCall {
456                id: c.tool_id.clone(),
457                name: c.name.clone(),
458                arguments: c.arguments.clone(),
459                thought_signature: c.thought_signature.clone(),
460            });
461        }
462
463        // Hold the batch and ask the user about each blocked call.
464        if let (false, Some((hub, gate_stage))) = (pending_prompts.is_empty(), interactive) {
465            let n = pending_prompts.len();
466            for (tool_id, name, taint, clearance) in pending_prompts {
467                gate_stage
468                    .runtime
469                    .spawn(crate::gate_prompt::run_gate_prompt(
470                        entity,
471                        (*hub).clone(),
472                        state.agent_id.clone(),
473                        tool_id,
474                        name,
475                        taint,
476                        clearance,
477                        gate_stage.outcomes.clone(),
478                        gate_stage.wake.clone(),
479                    ));
480            }
481            commands
482                .entity(entity)
483                .remove::<ReadyForTools>()
484                .insert(crate::gate_prompt::AwaitingGatePrompt(n))
485                .insert(crate::gate_prompt::GateResolved::default());
486            continue; // re-run after the prompts resolve
487        }
488
489        // Dispatching the batch consumes any resolution state from a prior round.
490        commands
491            .entity(entity)
492            .remove::<crate::gate_prompt::GateResolved>();
493
494        if lane_calls.is_empty() {
495            // Nothing async to run - apply the context results now and loop back.
496            let merged = merge_in_call_order(&result.tool_calls, &context_results);
497            apply_tool_results(
498                &mut window,
499                &result.response,
500                &result.tool_calls,
501                &merged,
502                routing.map(|c| &c.routing),
503                sensitivities.map(|s| &s.0),
504            );
505            commands
506                .entity(entity)
507                .remove::<ReadyForTools>()
508                .insert(ReadyToInfer);
509            continue;
510        }
511
512        // Journal the batch before it can run: a `ToolBatch` record with the
513        // dispatcher's inline results pre-filled and every lane call pending,
514        // plus a per-call progress hook that records each completion. Worlds
515        // without a persistence lane or run metadata (tests, unpersisted
516        // agents) dispatch unjournaled with a no-op progress.
517        let (progress, ack) = match (persist.as_ref(), metadata) {
518            (Some(persist), Some(md)) => {
519                let record = leviath_core::run_archive::RunRecord::ToolBatch {
520                    calls: result
521                        .tool_calls
522                        .iter()
523                        .map(|c| leviath_core::run_archive::ToolCallRecord {
524                            id: c.tool_id.clone(),
525                            name: c.name.clone(),
526                            arguments: c.arguments.to_string(),
527                            result: context_results
528                                .iter()
529                                .find(|(id, _)| id == &c.tool_id)
530                                .map(|(_, r)| r.clone()),
531                            thought_signature: c.thought_signature.clone(),
532                        })
533                        .collect(),
534                    at: chrono::Utc::now().timestamp(),
535                    stage_index: cursor.map_or(0, |c| c.index),
536                    iteration: state.iteration,
537                    response: result.response.clone(),
538                };
539                let (ack_tx, ack_rx) = tokio::sync::oneshot::channel();
540                let _ = persist.0.send(PersistMsg::Append {
541                    run_id: md.run_id.clone(),
542                    record: Box::new(record),
543                    ack: Some(ack_tx),
544                });
545                let sender = persist.0.clone();
546                let run_id = md.run_id.clone();
547                let iteration = state.iteration;
548                let progress: ToolProgress = Arc::new(move |call_id: &str, result: &str| {
549                    let _ = sender.send(PersistMsg::Append {
550                        run_id: run_id.clone(),
551                        record: Box::new(leviath_core::run_archive::RunRecord::ToolCallDone {
552                            iteration,
553                            call_id: call_id.to_string(),
554                            result: result.to_string(),
555                            at: chrono::Utc::now().timestamp(),
556                        }),
557                        ack: None,
558                    });
559                });
560                (progress, Some(ack_rx))
561            }
562            _ => (noop_progress(), None),
563        };
564        // Announce each lane-bound call before it starts executing. Inline
565        // results (context tools, refusals, blocks) never reach the lane and
566        // are deliberately not announced.
567        if let (Some(sink), Some(md)) = (sink.as_ref(), metadata) {
568            for call in &lane_calls {
569                let _ = sink.0.send(crate::host::WorldEvent::ToolCallStarted {
570                    run_id: md.run_id.clone(),
571                    agent_id: state.agent_id.clone(),
572                    call_id: call.id.clone(),
573                    tool: call.name.clone(),
574                });
575            }
576        }
577        let exec = service.0.exec_for(entity, lane_calls, progress);
578        let exec = match ack {
579            Some(ack) => barrier_then(exec, ack, BATCH_JOURNAL_ACK_TIMEOUT),
580            None => exec,
581        };
582        let cancel = crate::cancel::CancelToken::new();
583        // The lane is alive for the world's lifetime; a failed send would
584        // only happen during shutdown, where dropping the job is fine.
585        stage.stats.enqueued();
586        let _ = stage.jobs.send(ToolJob {
587            entity,
588            exec,
589            cancel: cancel.clone(),
590        });
591        track_in_flight(&mut commands, entity, in_flight, cancel);
592        commands
593            .entity(entity)
594            .remove::<ReadyForTools>()
595            .insert(AwaitingTools)
596            .insert(ContextToolResults(context_results));
597    }
598}