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, applying a stage's per-stage inference
142/// wall-clock cap when configured. Starts from the default policy and, when the
143/// stage set `request_timeout_secs` (from `[stages.<name>.model]`), overrides its
144/// `job_timeout`; otherwise the default job timeout stands. Pure so the override
145/// branch is unit-testable without driving the ECS dispatch.
146pub(crate) fn retry_policy_for(
147    config: Option<&InferenceConfig>,
148) -> crate::inference_bridge::RetryPolicy {
149    let mut policy = crate::inference_bridge::RetryPolicy::default();
150    if let Some(secs) = config.and_then(|c| c.request_timeout_secs) {
151        policy.job_timeout = std::time::Duration::from_secs(secs);
152    }
153    policy
154}
155
156/// The cancellation handles for an agent's currently in-flight async work (its
157/// inference request, its tool batch). Attached when the work is dispatched,
158/// removed when it lands - so the presence of this component means "there is
159/// something running for this agent that a cancel needs to stop".
160///
161/// Without it, cancelling only stopped *new* work from being dispatched: a
162/// request already handed to the async lanes ran to completion, holding its
163/// inference-pool permit or tool-lane capacity the whole time.
164#[derive(Component, Default, Debug)]
165pub struct InFlightWork(pub Vec<crate::cancel::CancelToken>);
166
167/// Stop the in-flight work of every agent that has reached a terminal state, and
168/// drop the handles. Runs before the dispatch systems each tick, so a cancel
169/// takes effect on the very next tick rather than whenever the provider or tool
170/// happens to answer.
171pub fn abort_terminal_work(
172    agents: Query<(Entity, &AgentState, &InFlightWork)>,
173    mut commands: Commands,
174) {
175    crate::tick_scope::clear();
176    for (entity, state, in_flight) in agents.iter() {
177        if !is_terminal_status(&state.status) {
178            continue;
179        }
180        crate::tick_scope::enter(entity);
181        for token in &in_flight.0 {
182            token.cancel();
183        }
184        commands.entity(entity).remove::<InFlightWork>();
185    }
186}
187
188/// Record `token` as in-flight work for `entity`, keeping any already attached
189/// (an agent can have both a tool batch and an inference outstanding across a
190/// tick boundary).
191pub(crate) fn track_in_flight(
192    commands: &mut Commands,
193    entity: Entity,
194    existing: Option<&InFlightWork>,
195    token: crate::cancel::CancelToken,
196) {
197    let mut tokens = existing.map(|w| w.0.clone()).unwrap_or_default();
198    tokens.push(token);
199    commands.entity(entity).insert(InFlightWork(tokens));
200}
201
202/// What `dispatch_inference` selects.
203///
204/// `&'static` is bevy's `WorldQuery` convention, not a claim about
205/// lifetimes: the borrow is bound when the query is fetched.
206type InferenceQuery = (
207    Entity,
208    &'static AgentState,
209    &'static ContextWindow,
210    Option<&'static InferenceConfig>,
211    &'static StageInference,
212    Option<&'static InFlightWork>,
213    Option<&'static StageProgress>,
214    Option<&'static DispatchStall>,
215);
216
217/// Inference-dispatch system: for every `ReadyToInfer` agent, resolve its
218/// provider and, **if a per-model permit is free**, build the request, spawn the
219/// inference job, and move it to `AwaitingInference`. If its provider is missing
220/// or no slot is free, it stays `ReadyToInfer` and is retried on a later tick -
221/// no blocking, no wasted task.
222pub fn dispatch_inference(
223    agents: Query<InferenceQuery, With<ReadyToInfer>>,
224    stage: Res<InferenceStage>,
225    providers: Res<Providers>,
226    circuits: Option<Res<ProviderCircuits>>,
227    policy: Option<Res<CircuitPolicy>>,
228    par_commands: ParallelCommands,
229) {
230    // Fan out across ready agents: request assembly (`build_request`) is the
231    // per-agent CPU cost and is independent, so it runs in parallel on the
232    // compute pool. Permit acquisition (an atomic semaphore) and the tokio spawn
233    // are thread-safe; the marker swap is batched via `ParallelCommands`.
234    //
235    // This is the one system whose per-agent body runs off the driver thread, so
236    // the thread-local `tick_scope` can't carry an entity back to the catcher.
237    // Each agent's share runs under `run_agent_parallel`, which catches there -
238    // where the entity is known - and marks that agent for `tick` to fail
239    // (issue #109). Clearing the thread-local keeps a panic in the fan-out
240    // machinery *itself* unattributed rather than blamed on whichever agent a
241    // previous system left recorded.
242    crate::tick_scope::clear();
243    let now = chrono::Utc::now().timestamp();
244    let circuit_policy = policy.map(|p| *p).unwrap_or_default();
245    let circuits = circuits.as_deref();
246    agents.par_iter().for_each(
247        |(entity, state, window, config, si, in_flight, progress, stalled)| {
248            crate::tick_scope::run_agent_parallel(entity, &par_commands, &mut || {
249                if state.status != AgentStatus::Active {
250                    return; // paused / waiting / cancelled - don't start new work
251                }
252                // Every decline below records why and since when, so the
253                // watchdog can tell a run that is waiting from one that is
254                // waiting for something that will never happen (issue #190).
255                let stall = |reason| {
256                    let noted = note_stall(stalled, reason, now);
257                    par_commands.command_scope(|mut commands| {
258                        commands.entity(entity).insert(noted);
259                    });
260                };
261                // The rotation system already moved this agent onto the best
262                // provider still standing. Reaching a tripped one here means
263                // every candidate is out of service, so park rather than send
264                // a request that is going to fail the same way as the last
265                // three (issue #201). The stall watchdog ends the wait.
266                if circuits.is_some_and(|c| c.is_open(&si.provider_name, now, &circuit_policy)) {
267                    tracing::debug!(
268                        provider = %si.provider_name,
269                        "inference waiting: the provider's circuit is open"
270                    );
271                    stall(StallReason::ProviderCircuitOpen);
272                    return;
273                }
274                let Some(provider) = providers.0.get(&si.provider_name) else {
275                    // Leave ready and retry later - but say so. A silently
276                    // starved agent reads as a wedged run with no error.
277                    tracing::warn!(
278                        provider = %si.provider_name,
279                        "inference waiting: provider not registered"
280                    );
281                    stall(StallReason::ProviderMissing);
282                    return;
283                };
284                let Some(permit) = stage.pools.try_acquire(&si.model) else {
285                    // Every in-flight call on this model holds a permit; if
286                    // this repeats for minutes, one of them is stuck (see the
287                    // default request timeout in leviath-providers).
288                    tracing::debug!(
289                        model = %si.model,
290                        "inference waiting: per-model pool is full"
291                    );
292                    stall(StallReason::PoolFull);
293                    return;
294                };
295                let request = build_request(
296                    window,
297                    config,
298                    si,
299                    &provider,
300                    &state.current_stage,
301                    progress.map(|p| p.iterations).unwrap_or(0),
302                );
303                let job = InferenceJob {
304                    entity,
305                    provider,
306                    request,
307                    permit,
308                    exact_token_counting: stage.exact_token_counting,
309                };
310                let cancel = crate::cancel::CancelToken::new();
311                // Supervised: this agent is about to become `AwaitingInference`,
312                // which the driver reads as "busy". A job that died without
313                // reporting would leave it waiting on a completion that can no
314                // longer come, so the supervisor reports one in its place.
315                let lost_outcomes = stage.outcomes.clone();
316                let lost_wake = stage.wake.clone();
317                crate::lane_supervisor::spawn_supervised(
318                    &stage.runtime,
319                    "inference",
320                    run_inference_job(
321                        job,
322                        stage.outcomes.clone(),
323                        stage.wake.clone(),
324                        retry_policy_for(config),
325                        cancel.clone(),
326                    ),
327                    move |message| {
328                        let _ = lost_outcomes.send(InferenceOutcome {
329                            entity,
330                            result: Err(leviath_providers::ProviderError::Other(message)),
331                            // The job never got to measure itself.
332                            latency: std::time::Duration::ZERO,
333                        });
334                        lost_wake.notify_one();
335                    },
336                );
337                par_commands.command_scope(|mut commands| {
338                    track_in_flight(&mut commands, entity, in_flight, cancel);
339                    commands
340                        .entity(entity)
341                        .remove::<ReadyToInfer>()
342                        // Dispatched: whatever it was waiting for, it isn't
343                        // waiting any more.
344                        .remove::<DispatchStall>()
345                        .insert(AwaitingInference);
346                });
347            });
348        },
349    );
350}