Skip to main content

leviath_runtime/pipeline/
inference.rs

1//! Inference dispatch: building each ready agent's request and handing it to the async lane.
2
3use super::*;
4
5/// The batch-tool-calls hint, prepended to a stage's system blocks when
6/// `InferenceConfig::batch_tool_hint` is set. Identical across every agent,
7/// stage, and run, so it is a stable cache prefix (`CacheHint::Always`). It tells
8/// the model it may emit several `tool_use` blocks per response and should batch
9/// *independent* operations - while explicitly forbidding batching of dependent
10/// ones.
11pub(crate) const BATCH_TOOL_HINT: &str = "You can call multiple tools in a single response. \
12When operations are independent (reading, editing, or writing different files, or \
13writing a file then running a command that doesn't need its output), batch them in \
14one response to cut round trips. Do NOT batch when a call depends on a previous \
15call's result, or when you must see a command's output before deciding the next step.";
16
17/// What the `shell` tool actually runs on Windows, and the PowerShell commands
18/// that stand in for the POSIX ones a model reaches for by reflex. Prepended to
19/// a shell-granting stage's system blocks when [`shell_guidance_for`] returns
20/// it; see [`InferenceConfig::shell_hint`](crate::components::InferenceConfig).
21pub(crate) const WINDOWS_SHELL_HINT: &str = "The shell tool runs on Windows through `cmd.exe /C`, \
22not a POSIX shell. GNU coreutils are not available: use `type` or PowerShell's `Get-Content` \
23instead of `cat`, `findstr` or `Select-String` instead of `grep`, `dir` or `Get-ChildItem` \
24instead of `ls`, and `Measure-Object -Line` instead of `wc -l`. Run a PowerShell command as \
25`powershell -Command \"...\"`. Paths use backslashes and drive letters, and `%VAR%` (cmd) or \
26`$env:VAR` (PowerShell) expands environment variables.";
27
28/// The shell guidance for `os`, or `None` when the platform's shell needs no
29/// explanation (a POSIX shell is what the model already assumes).
30///
31/// Pure over the OS string rather than `#[cfg]`-switched, following
32/// `leviath_sys::browser::open_command_for`, so every branch is reachable under
33/// test on a single platform. Callers pass [`std::env::consts::OS`].
34pub(crate) fn shell_guidance_for(os: &str) -> Option<&'static str> {
35    match os {
36        "windows" => Some(WINDOWS_SHELL_HINT),
37        _ => None,
38    }
39}
40
41/// The framework-authored system blocks a stage carries ahead of its own
42/// context, in the order they are prepended.
43///
44/// Both hints read the same on every agent, stage, and run of a given host, so
45/// they lead the `Always`-tier prefix (which `assemble` already sorts first) and
46/// leave prefix caching intact. `os` is the host OS string
47/// ([`std::env::consts::OS`] in production) and `tools` the stage's advertised
48/// tools: telling a stage that cannot run commands which shell it would have
49/// gotten is pure overhead, so the shell hint is gated on the tool being there.
50///
51/// Note this is a `build_request` concern, so the request paths that assemble
52/// their own [`InferenceRequest`] - `lev test`, title generation, compaction -
53/// carry no hints. That was already true of the batch hint.
54pub(crate) fn hint_blocks(
55    config: Option<&InferenceConfig>,
56    tools: &[Tool],
57    os: &str,
58) -> Vec<leviath_providers::SystemBlock> {
59    let always = |text: &str| leviath_providers::SystemBlock {
60        text: text.to_string(),
61        cache_hint: leviath_core::CacheHint::Always,
62    };
63    let mut blocks = Vec::new();
64    if config.map(|c| c.batch_tool_hint).unwrap_or(false) {
65        blocks.push(always(BATCH_TOOL_HINT));
66    }
67    if config.map(|c| c.shell_hint).unwrap_or(false)
68        && tools.iter().any(|t| t.name == "shell")
69        && let Some(text) = shell_guidance_for(os)
70    {
71        blocks.push(always(text));
72    }
73    blocks
74}
75
76/// Build the [`InferenceRequest`] for an agent from its context window + stage
77/// data. Pure; no `.await` - a custom region's render hook is a bounded,
78/// synchronous Rhai eval. (Ported from `AgentEngine::build_inference_request`,
79/// with provider resolution lifted into the caller so this stays query-friendly.)
80///
81/// `stage_name` / `stage_iterations` feed custom-region `render(ctx)` hooks;
82/// they change nothing when the window has no custom regions.
83pub(crate) fn build_request(
84    window: &ContextWindow,
85    config: Option<&InferenceConfig>,
86    stage: &StageInference,
87    provider: &Arc<dyn Provider>,
88    stage_name: &str,
89    stage_iterations: usize,
90) -> InferenceRequest {
91    let assembled = window.assemble_with_meta(&crate::custom_region::AssembleMeta {
92        stage_name: stage_name.to_string(),
93        stage_iterations,
94        model: stage.model.clone(),
95    });
96    let remaining = window.max_tokens.saturating_sub(window.current_tokens);
97    let caps = provider.capabilities(&stage.model);
98    let output_cap = config
99        .and_then(|c| c.max_output_tokens)
100        .unwrap_or(caps.max_output_tokens);
101    let max_tokens = remaining.min(output_cap);
102
103    let filtered_tools = match stage.tool_filter.as_deref() {
104        Some(filter) if !filter.is_empty() => stage
105            .tools
106            .iter()
107            .filter(|t| filter.iter().any(|f| f == &t.name))
108            .cloned()
109            .collect(),
110        _ => stage.tools.clone(),
111    };
112
113    let temperature = if caps.supports_temperature {
114        config.and_then(|c| c.temperature).unwrap_or(0.7)
115    } else {
116        0.0
117    };
118
119    // Pass through any extra model parameters (top_p, stop, seed, …) so the
120    // provider can apply them; `Null` when there are none.
121    let extra = match config.map(|c| &c.extra_params) {
122        Some(params) if !params.is_empty() => serde_json::Value::Object(params.clone()),
123        _ => serde_json::Value::Null,
124    };
125
126    let mut system = hint_blocks(config, &filtered_tools, std::env::consts::OS);
127    system.extend(assembled.system_blocks);
128
129    InferenceRequest {
130        system,
131        messages: assembled.messages,
132        model: stage.model.clone(),
133        max_tokens,
134        temperature,
135        tools: filtered_tools,
136        extra,
137        request_timeout_secs: config.and_then(|c| c.request_timeout_secs),
138    }
139}
140
141/// Build the [`RetryPolicy`] for a job from the operator's `[limits]` retry
142/// schedule, applying a stage's per-stage inference wall-clock cap when
143/// configured.
144///
145/// `tuning` carries the two configurable numbers (`[limits]
146/// inference_retry_attempts` and `inference_retry_base_ms`); everything else -
147/// the capacity schedule and the total-backoff ceiling - comes from the default
148/// policy. When the stage set `request_timeout_secs` (from
149/// `[stages.<name>.model]`) that overrides `job_timeout`; otherwise the default
150/// job timeout stands. Pure so both branches are unit-testable without driving
151/// the ECS dispatch.
152pub(crate) fn retry_policy_for(
153    config: Option<&InferenceConfig>,
154    tuning: InferenceRetryTuning,
155) -> crate::inference_bridge::RetryPolicy {
156    let mut policy = crate::inference_bridge::RetryPolicy {
157        max_attempts: tuning.max_attempts,
158        base_delay: std::time::Duration::from_millis(tuning.base_delay_ms),
159        ..crate::inference_bridge::RetryPolicy::default()
160    };
161    if let Some(secs) = config.and_then(|c| c.request_timeout_secs) {
162        policy.job_timeout = std::time::Duration::from_secs(secs);
163    }
164    policy
165}
166
167/// The cancellation handles for an agent's currently in-flight async work (its
168/// inference request, its tool batch). Attached when the work is dispatched,
169/// removed when it lands - so the presence of this component means "there is
170/// something running for this agent that a cancel needs to stop".
171///
172/// Without it, cancelling only stopped *new* work from being dispatched: a
173/// request already handed to the async lanes ran to completion, holding its
174/// inference-pool permit or tool-lane capacity the whole time.
175#[derive(Component, Default, Debug)]
176pub struct InFlightWork(pub Vec<crate::cancel::CancelToken>);
177
178/// Stop the in-flight work of every agent that has reached a terminal state, and
179/// drop the handles. Runs before the dispatch systems each tick, so a cancel
180/// takes effect on the very next tick rather than whenever the provider or tool
181/// happens to answer.
182pub fn abort_terminal_work(
183    agents: Query<(Entity, &AgentState, &InFlightWork)>,
184    mut commands: Commands,
185) {
186    crate::tick_scope::clear();
187    for (entity, state, in_flight) in agents.iter() {
188        if !is_terminal_status(&state.status) {
189            continue;
190        }
191        crate::tick_scope::enter(entity);
192        for token in &in_flight.0 {
193            token.cancel();
194        }
195        commands.entity(entity).remove::<InFlightWork>();
196    }
197}
198
199/// Record `token` as in-flight work for `entity`, keeping any already attached
200/// (an agent can have both a tool batch and an inference outstanding across a
201/// tick boundary).
202pub(crate) fn track_in_flight(
203    commands: &mut Commands,
204    entity: Entity,
205    existing: Option<&InFlightWork>,
206    token: crate::cancel::CancelToken,
207) {
208    let mut tokens = existing.map(|w| w.0.clone()).unwrap_or_default();
209    tokens.push(token);
210    commands.entity(entity).insert(InFlightWork(tokens));
211}
212
213/// What `dispatch_inference` selects.
214///
215/// `&'static` is bevy's `WorldQuery` convention, not a claim about
216/// lifetimes: the borrow is bound when the query is fetched.
217type InferenceQuery = (
218    Entity,
219    &'static AgentState,
220    &'static ContextWindow,
221    Option<&'static InferenceConfig>,
222    &'static StageInference,
223    Option<&'static InFlightWork>,
224    Option<&'static StageProgress>,
225    Option<&'static DispatchStall>,
226);
227
228/// Inference-dispatch system: for every `ReadyToInfer` agent, resolve its
229/// provider and, **if a per-model permit is free**, build the request, spawn the
230/// inference job, and move it to `AwaitingInference`. If its provider is missing
231/// or no slot is free, it stays `ReadyToInfer` and is retried on a later tick -
232/// no blocking, no wasted task.
233pub fn dispatch_inference(
234    agents: Query<InferenceQuery, With<ReadyToInfer>>,
235    stage: Res<InferenceStage>,
236    providers: Res<Providers>,
237    circuits: Option<Res<ProviderCircuits>>,
238    policy: Option<Res<CircuitPolicy>>,
239    retry: Option<Res<InferenceRetryTuning>>,
240    par_commands: ParallelCommands,
241) {
242    // Fan out across ready agents: request assembly (`build_request`) is the
243    // per-agent CPU cost and is independent, so it runs in parallel on the
244    // compute pool. Permit acquisition (an atomic semaphore) and the tokio spawn
245    // are thread-safe; the marker swap is batched via `ParallelCommands`.
246    //
247    // This is the one system whose per-agent body runs off the driver thread, so
248    // the thread-local `tick_scope` can't carry an entity back to the catcher.
249    // Each agent's share runs under `run_agent_parallel`, which catches there -
250    // where the entity is known - and marks that agent for `tick` to fail
251    // (issue #109). Clearing the thread-local keeps a panic in the fan-out
252    // machinery *itself* unattributed rather than blamed on whichever agent a
253    // previous system left recorded.
254    crate::tick_scope::clear();
255    let now = chrono::Utc::now().timestamp();
256    let circuit_policy = policy.map(|p| *p).unwrap_or_default();
257    // The daemon inserts this from `[limits]`; a world that never set it (every
258    // embedded host, and most tests) gets the built-in schedule.
259    let retry_tuning = retry.map(|r| *r).unwrap_or_default();
260    let circuits = circuits.as_deref();
261    agents.par_iter().for_each(
262        |(entity, state, window, config, si, in_flight, progress, stalled)| {
263            crate::tick_scope::run_agent_parallel(entity, &par_commands, &mut || {
264                if state.status != AgentStatus::Active {
265                    return; // paused / waiting / cancelled - don't start new work
266                }
267                // Every decline below records why and since when, so the
268                // watchdog can tell a run that is waiting from one that is
269                // waiting for something that will never happen (issue #190).
270                let stall = |reason| {
271                    let noted = note_stall(stalled, reason, now);
272                    par_commands.command_scope(|mut commands| {
273                        commands.entity(entity).insert(noted);
274                    });
275                };
276                // The rotation system already moved this agent onto the best
277                // provider still standing. Reaching a tripped one here means
278                // every candidate is out of service, so park rather than send
279                // a request that is going to fail the same way as the last
280                // three (issue #201). The stall watchdog ends the wait.
281                if circuits.is_some_and(|c| c.is_open(&si.provider_name, now, &circuit_policy)) {
282                    tracing::debug!(
283                        provider = %si.provider_name,
284                        "inference waiting: the provider's circuit is open"
285                    );
286                    stall(StallReason::ProviderCircuitOpen);
287                    return;
288                }
289                let Some(provider) = providers.0.get(&si.provider_name) else {
290                    // Leave ready and retry later - but say so. A silently
291                    // starved agent reads as a wedged run with no error.
292                    tracing::warn!(
293                        provider = %si.provider_name,
294                        "inference waiting: provider not registered"
295                    );
296                    stall(StallReason::ProviderMissing);
297                    return;
298                };
299                let Some(permit) = stage.pools.try_acquire(&si.model) else {
300                    // Every in-flight call on this model holds a permit; if
301                    // this repeats for minutes, one of them is stuck (see the
302                    // default request timeout in leviath-providers).
303                    tracing::debug!(
304                        model = %si.model,
305                        "inference waiting: per-model pool is full"
306                    );
307                    stall(StallReason::PoolFull);
308                    return;
309                };
310                let request = build_request(
311                    window,
312                    config,
313                    si,
314                    &provider,
315                    &state.current_stage,
316                    progress.map(|p| p.iterations).unwrap_or(0),
317                );
318                let job = InferenceJob {
319                    entity,
320                    provider,
321                    request,
322                    permit,
323                    exact_token_counting: stage.exact_token_counting,
324                };
325                let cancel = crate::cancel::CancelToken::new();
326                // Supervised: this agent is about to become `AwaitingInference`,
327                // which the driver reads as "busy". A job that died without
328                // reporting would leave it waiting on a completion that can no
329                // longer come, so the supervisor reports one in its place.
330                let lost_outcomes = stage.outcomes.clone();
331                let lost_wake = stage.wake.clone();
332                crate::lane_supervisor::spawn_supervised(
333                    &stage.runtime,
334                    "inference",
335                    run_inference_job(
336                        job,
337                        stage.outcomes.clone(),
338                        stage.wake.clone(),
339                        retry_policy_for(config, retry_tuning),
340                        cancel.clone(),
341                    ),
342                    move |message| {
343                        let _ = lost_outcomes.send(InferenceOutcome {
344                            entity,
345                            result: Err(leviath_providers::ProviderError::Other(message)),
346                            // The job never got to measure itself.
347                            latency: std::time::Duration::ZERO,
348                        });
349                        lost_wake.notify_one();
350                    },
351                );
352                par_commands.command_scope(|mut commands| {
353                    track_in_flight(&mut commands, entity, in_flight, cancel);
354                    commands
355                        .entity(entity)
356                        .remove::<ReadyToInfer>()
357                        // Dispatched: whatever it was waiting for, it isn't
358                        // waiting any more.
359                        .remove::<DispatchStall>()
360                        .insert(AwaitingInference);
361                });
362            });
363        },
364    );
365}