leviath_runtime/pipeline/response.rs
1//! Response collection and stage-progress accounting.
2
3use super::*;
4
5/// The response has been applied and is ready to be examined for tool calls (or
6/// completion) by the process-response system.
7#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
8pub struct ProcessResponse;
9
10/// The receiving end of the inference-outcomes channel, as a world resource for
11/// the collect system. (The sending end lives in [`InferenceStage`].)
12#[derive(Resource)]
13pub struct InferenceResults(pub UnboundedReceiver<InferenceOutcome>);
14
15/// Convert a provider response into the stored `InferenceResult` component.
16/// (Ported from `AgentEngine::apply_inference_response`.)
17pub(crate) fn to_inference_result(
18 response: &leviath_providers::InferenceResponse,
19) -> crate::components::InferenceResult {
20 crate::components::InferenceResult {
21 response: response.content.clone(),
22 tool_calls: response
23 .tool_calls
24 .iter()
25 .map(|tc| crate::components::ToolCall {
26 tool_id: tc.id.clone(),
27 name: tc.name.clone(),
28 arguments: tc.arguments.clone(),
29 thought_signature: tc.thought_signature.clone(),
30 })
31 .collect(),
32 tokens_used: response.tokens_used.total_tokens,
33 timestamp: chrono::Utc::now().timestamp(),
34 }
35}
36
37/// What `collect_inference` selects.
38///
39/// `&'static` is bevy's `WorldQuery` convention, not a claim about
40/// lifetimes: the borrow is bound when the query is fetched.
41type InferenceQuery = (
42 &'static mut AgentState,
43 Option<&'static mut crate::persistence::TokenTotals>,
44 Option<&'static StageCursor>,
45 Option<&'static ContextWindow>,
46 Option<&'static mut StageLedger>,
47 Option<&'static mut StageIoBuffer>,
48 Option<&'static mut StageInference>,
49 Option<&'static mut crate::telemetry::StageActivity>,
50);
51
52/// Inference-collect system: drain completed inferences and apply them. A
53/// success is stored on the agent (bumping its iteration) and the agent advances
54/// to `ProcessResponse`; an error marks the agent `Error`. An outcome for an
55/// agent that is no longer `AwaitingInference` (cancelled or despawned between
56/// dispatch and now) is dropped.
57pub fn collect_inference(
58 mut results: ResMut<InferenceResults>,
59 mut agents: Query<InferenceQuery, With<AwaitingInference>>,
60 mut circuits: Option<ResMut<ProviderCircuits>>,
61 policy: Option<Res<CircuitPolicy>>,
62 mut commands: Commands,
63) {
64 crate::tick_scope::clear();
65 let policy = policy.map(|p| *p).unwrap_or_default();
66 let now = chrono::Utc::now().timestamp();
67 while let Ok(outcome) = results.0.try_recv() {
68 let Ok((mut state, totals, cursor, window, mut ledger, buffer, mut inference, activity)) =
69 agents.get_mut(outcome.entity)
70 else {
71 continue; // stale: agent cancelled/despawned since dispatch
72 };
73 crate::tick_scope::enter(outcome.entity);
74 // The agent reached a terminal state while this inference was in flight
75 // (a cancel, or a panic that failed it). Drop the response: applying it
76 // would move the run on to `ProcessResponse` and it would keep going.
77 if is_terminal_status(&state.status) {
78 commands
79 .entity(outcome.entity)
80 .remove::<AwaitingInference>()
81 .remove::<InFlightWork>();
82 continue;
83 }
84 let idx = cursor.map_or(0, |c| c.index);
85 // Whoever we actually called. Read before the error arm below, which
86 // may swap the component over to the next provider.
87 let (called_provider, called_model) = inference
88 .as_deref()
89 .map(|i| (i.provider_name.clone(), i.model.clone()))
90 .unwrap_or_default();
91 // Record the call for the telemetry observer while the provider and
92 // timing are still at hand (the observer only sees components).
93 if let Some(mut activity) = activity {
94 let usage = outcome.result.as_ref().ok().map(|r| &r.tokens_used);
95 activity
96 .0
97 .push(crate::telemetry::ActivityRecord::Inference {
98 provider: called_provider.clone(),
99 model: called_model.clone(),
100 latency_ms: u64::try_from(outcome.latency.as_millis()).unwrap_or(u64::MAX),
101 prompt_tokens: usage.map_or(0, |u| u.prompt_tokens),
102 completion_tokens: usage.map_or(0, |u| u.completion_tokens),
103 cached_tokens: usage.map_or(0, |u| u.cached_tokens),
104 success: outcome.result.is_ok(),
105 });
106 }
107 // Breaker bookkeeping, before the arms below consume the outcome. Any
108 // answer at all proves the provider is serving; a provider-fatal one
109 // counts against it and may take it out of service for everyone.
110 if let Some(circuits) = circuits.as_deref_mut() {
111 match outcome
112 .result
113 .as_ref()
114 .err()
115 .and_then(|e| e.unavailable_reason())
116 {
117 Some(reason) => {
118 if circuits.record_failure(&called_provider, reason, now, &policy) {
119 // Loud and once, on the transition only. This is the
120 // alert issue #201 asked for: without it, ten dead
121 // runs in a row look like ten unrelated failures.
122 tracing::error!(
123 provider = %called_provider,
124 reason = reason.label(),
125 failures = policy.failures_before_open,
126 cooldown_secs = policy.cooldown_secs,
127 "provider circuit opened; no run will be dispatched to it \
128 until it recovers"
129 );
130 }
131 }
132 None if outcome.result.is_ok() => circuits.record_success(&called_provider),
133 // An ordinary error says nothing about the provider either
134 // way, so it neither counts against it nor clears its record.
135 None => {}
136 }
137 }
138 match outcome.result {
139 Ok(response) => {
140 state.iteration += 1;
141 if let Some(mut totals) = totals {
142 totals.add_usage(&response.tokens_used);
143 }
144 // Accrue this iteration's tokens against the current stage record.
145 if let Some(rec) = ledger.as_deref_mut().and_then(|l| l.0.get_mut(idx)) {
146 rec.prompt_tokens += response.tokens_used.prompt_tokens;
147 rec.completion_tokens += response.tokens_used.completion_tokens;
148 rec.cached_tokens += response.tokens_used.cached_tokens;
149 rec.cache_write_tokens += response.tokens_used.cache_write_tokens;
150 // The high-water mark rather than a sum: a region is
151 // re-sent whole on every call, so summing would report a
152 // number that is neither what it costs per call nor what it
153 // holds. The largest it reached is the one that says
154 // whether it is earning its place.
155 for region in window.iter().flat_map(|w| w.regions.iter()) {
156 let seen = rec.region_tokens.entry(region.name.clone()).or_insert(0);
157 *seen = (*seen).max(region.current_tokens);
158 }
159 warn_if_context_is_running_away(rec, response.tokens_used.prompt_tokens);
160 }
161 // Buffer the readable output + a token line for the stage's logs.
162 if let Some(mut buffer) = buffer {
163 if !response.content.trim().is_empty() {
164 buffer.output.push((idx, response.content.clone()));
165 }
166 buffer.logs.push((
167 idx,
168 format!(
169 "[Tokens: {} in, {} out]",
170 response.tokens_used.prompt_tokens,
171 response.tokens_used.completion_tokens
172 ),
173 ));
174 }
175 let result = to_inference_result(&response);
176 commands
177 .entity(outcome.entity)
178 .insert(result)
179 .remove::<AwaitingInference>()
180 .remove::<InFlightWork>()
181 .insert(ProcessResponse);
182 }
183 Err(err) => {
184 // A provider that is out of credits or holding a rejected key
185 // is not this request's problem: every later request to it
186 // fails the same way. Move the stage to the next candidate and
187 // try again rather than killing the run (issue #201).
188 let next = err.unavailable_reason().and_then(|_| {
189 let si = inference.as_deref_mut()?;
190 (!si.fallbacks.is_empty()).then(|| si.fallbacks.remove(0))
191 });
192 if let Some(next) = next {
193 // Loud on purpose. Silently swapping providers is how a
194 // factory ends up running on a model nobody chose.
195 tracing::warn!(
196 from_provider = %called_provider,
197 from_model = %called_model,
198 to_provider = %next.provider,
199 to_model = %next.model,
200 error = %err,
201 "provider unusable; failing over to the next configured model"
202 );
203 if let Some(mut buffer) = buffer {
204 buffer.logs.push((
205 idx,
206 format!(
207 "[failover] {called_provider}/{called_model} is unusable \
208 ({err}); retrying on {}/{}",
209 next.provider, next.model
210 ),
211 ));
212 }
213 let si = inference
214 .as_deref_mut()
215 .expect("the failover branch only runs with a StageInference");
216 si.provider_name = next.provider;
217 si.model = next.model;
218 // Back to ready, not errored: the next tick dispatches it
219 // against the new provider and takes that model's permit.
220 // The iteration is deliberately not bumped - the agent has
221 // still not had a turn.
222 commands
223 .entity(outcome.entity)
224 .remove::<AwaitingInference>()
225 .remove::<InFlightWork>()
226 .insert(ReadyToInfer);
227 continue;
228 }
229 if let Some(mut buffer) = buffer {
230 buffer.logs.push((idx, format!("[error] {err}")));
231 }
232 // Record the error and route it to the stage's transition logic
233 // (which follows an `error`-conditioned edge if the stage has one,
234 // e.g. → error_recovery, or terminates the run otherwise).
235 state.status = AgentStatus::Error {
236 message: err.to_string(),
237 };
238 commands
239 .entity(outcome.entity)
240 .remove::<AwaitingInference>()
241 .remove::<InFlightWork>()
242 .insert(StageOutcome::Errored(err.to_string()))
243 .insert(ResolveTransition);
244 }
245 }
246 }
247}
248
249/// The response had tool calls; the agent is ready for the tool-dispatch system
250/// to run them (the calls live on its `InferenceResult`).
251#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
252pub struct ReadyForTools;
253
254/// The response had no tool calls; the agent is ready for the empty-response
255/// handler to decide finish vs. a "use your tools" nudge.
256#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
257pub struct ReadyForTransition;
258
259/// The agent's current stage is complete; the transition system will resolve the
260/// next stage (or completion).
261#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
262pub struct ResolveTransition;
263
264/// How much bigger than its first call a stage's prompt may get before the run
265/// says so.
266///
267/// The runtime notices a stalled run and a stuck one; it noticed nothing about
268/// the failure that actually costs money - a region filling up and being
269/// re-sent on every call. Measured, a profile stage capped at 10 iterations
270/// billed 1,135,289 tokens, roughly 113k per call, because an uncapped read had
271/// filled its region. Nothing warned, and the run looked healthy from the
272/// outside until the bill arrived.
273///
274/// Four rather than two: a stage that reads a file and then works with it has
275/// genuinely grown, and warning about that would be noise. Four is past the
276/// point where growth is explained by ordinary accumulation.
277const RUNAWAY_CONTEXT_FACTOR: usize = 4;
278
279/// Say so when a stage's per-call prompt has grown past
280/// [`RUNAWAY_CONTEXT_FACTOR`] times its first call.
281///
282/// Once per stage, on the crossing. Repeating it every call afterwards would
283/// bury the run's other output in exactly the situation where that output
284/// matters.
285pub(crate) fn warn_if_context_is_running_away(
286 rec: &mut leviath_core::run_meta::StageRecord,
287 prompt_tokens: usize,
288) {
289 let first = match rec.first_call_prompt_tokens {
290 Some(first) => first,
291 None => {
292 rec.first_call_prompt_tokens = Some(prompt_tokens);
293 return;
294 }
295 };
296 if rec.runaway_warned || first == 0 || prompt_tokens < first * RUNAWAY_CONTEXT_FACTOR {
297 return;
298 }
299 rec.runaway_warned = true;
300 tracing::warn!(
301 stage = %rec.name,
302 first_call_prompt_tokens = first,
303 this_call_prompt_tokens = prompt_tokens,
304 "this stage's context has grown past {RUNAWAY_CONTEXT_FACTOR}x its first call and is \
305 re-sent on every call; check whether a region is accumulating without a cap \
306 (`lev stages <run-id>` shows the per-region sizes)"
307 );
308}
309
310/// Per-stage progress counters, reset when an agent enters a stage.
311#[derive(Component, Debug, Clone, Default)]
312pub struct StageProgress {
313 /// Total tool calls the agent has made in this stage.
314 pub total_tool_calls: usize,
315 /// Consecutive text-only responses that were nudged toward tool use.
316 pub text_only_nudges: usize,
317 /// Inferences run in this stage (per-stage, unlike the run-cumulative
318 /// `AgentState.iteration`), for enforcing the stage's `max_iterations`.
319 pub iterations: usize,
320 /// Successful file-modifying tool calls (`write_file`/`edit_file`, plus any
321 /// tool named by an outgoing gate) made in this stage. Read by the
322 /// transition gate to enforce `require_modifications`.
323 pub modifying_tool_calls: usize,
324 /// Modifying tool calls the permission layer refused (`[denied] ...`). A
325 /// gate lets the transition through when this is non-zero: the agent is
326 /// trying to write and cannot, so re-running the stage only burns budget.
327 pub blocked_modification_calls: usize,
328 /// Content digests of the regions this stage's outgoing gates watch, as
329 /// they stood when the stage was entered.
330 ///
331 /// Only the watched regions: hashing every region on every entry would
332 /// cost the whole window for a feature most stages do not use. Empty for a
333 /// stage with no `require_region_updated` gate, which is the common case.
334 pub entry_region_digests: std::collections::HashMap<String, u64>,
335 /// How many times a transition gate has already sent this stage back for
336 /// another pass. Bounded by the gate's `max_attempts`.
337 pub gate_reentries: usize,
338 /// Unix seconds of the first tick this agent was ready to infer in the
339 /// stage - the clock a `stuck_after_minutes` threshold reads. Stamped
340 /// lazily by [`detect_stuck_stage`] so spawn, `enter_stage` and
341 /// [`force_transition`] all get a fresh clock from the `Default` reset
342 /// without threading a clock through their signatures.
343 pub stage_started_at: Option<i64>,
344 /// `write_file`/`edit_file` calls made in this stage, keyed by target path.
345 /// Feeds the `stuck_after_same_file_edits` threshold.
346 pub edits_by_path: std::collections::HashMap<String, usize>,
347 /// A `stuck` edge has already fired in this stage. One-shot per stage entry:
348 /// without it a stuck interrupt whose edge became unavailable would ping-pong
349 /// between [`detect_stuck_stage`] and [`resolve_transition`]'s resume arm.
350 pub stuck_fired: bool,
351}
352
353/// How a stage ended, when that governs the transition. Absent ⇒ the stage
354/// completed normally. Read by [`resolve_transition`] to follow an
355/// `error`/`max_iterations`/`stuck`-conditioned edge (e.g. → error_recovery)
356/// when the stage errored, hit its iteration cap, or stopped making progress.
357#[derive(Component, Debug, Clone, PartialEq, Eq)]
358pub enum StageOutcome {
359 /// The stage errored (carries the error message for the terminal case).
360 Errored(String),
361 /// The stage hit its `max_iterations` cap.
362 MaxIterations,
363 /// A `stuck` edge tripped mid-stage; carries the human-readable reason.
364 Stuck(String),
365}
366
367/// One [`StageRecord`](leviath_core::run_meta::StageRecord) per blueprint stage,
368/// seeded at spawn (names + `Pending`) and reconciled by [`dispatch_persistence`]
369/// (status + timestamps), with per-stage tokens accrued by [`collect_inference`].
370/// Serialized to `stages.json` so the dashboard / serve API can show every
371/// stage's real name and status - not just the active one (whose name is the only
372/// one carried in `meta.json`).
373#[derive(Component, Debug, Clone)]
374pub struct StageLedger(pub Vec<leviath_core::run_meta::StageRecord>);
375
376/// Buffered per-stage output/log lines awaiting the persistence lane. Emitters
377/// ([`collect_inference`], [`collect_tools`]) push; [`dispatch_persistence`]
378/// drains and clears, forwarding the lines to `stages/<idx>/output.log` (readable
379/// assistant output) and `stages/<idx>/logs.log` (tool + token + error events).
380#[derive(Component, Debug, Clone, Default)]
381pub struct StageIoBuffer {
382 /// Readable assistant output lines, each tagged with its stage index.
383 pub output: Vec<(usize, String)>,
384 /// Operational log lines (tool activity, token counts, errors), each tagged
385 /// with its stage index.
386 pub logs: Vec<(usize, String)>,
387}
388
389/// What `process_response` selects.
390///
391/// `&'static` is bevy's `WorldQuery` convention, not a claim about
392/// lifetimes: the borrow is bound when the query is fetched.
393type ProcessResponseQuery = (
394 Entity,
395 &'static crate::components::InferenceResult,
396 &'static mut StageProgress,
397 Option<&'static mut crate::persistence::TokenTotals>,
398);
399
400/// Process-response system: route each `ProcessResponse` agent by whether its
401/// last inference asked for tools. Tool calls present ⇒ `ReadyForTools` (and the
402/// stage's running tool-call count is bumped); none ⇒ `ReadyForTransition`. Pure
403/// routing - no I/O.
404pub fn process_response(
405 mut agents: Query<ProcessResponseQuery, With<ProcessResponse>>,
406 mut commands: Commands,
407) {
408 crate::tick_scope::clear();
409 for (entity, result, mut progress, totals) in agents.iter_mut() {
410 crate::tick_scope::enter(entity);
411 progress.iterations += 1; // per-stage inference count (for max_iterations)
412 let mut e = commands.entity(entity);
413 e.remove::<ProcessResponse>();
414 if result.tool_calls.is_empty() {
415 e.insert(ReadyForTransition);
416 } else {
417 progress.total_tool_calls += result.tool_calls.len();
418 // Per-path edit churn, for `stuck` edges armed on same-file edits.
419 // Counted from the *requested* calls: a model asking to edit the
420 // same wrong file five times is stuck whether or not each call ran.
421 for path in result.tool_calls.iter().filter_map(edited_path) {
422 *progress.edits_by_path.entry(path.to_string()).or_insert(0) += 1;
423 }
424 if let Some(mut totals) = totals {
425 totals.tool_calls += result.tool_calls.len();
426 }
427 e.insert(ReadyForTools);
428 }
429 }
430}
431
432/// The path a tool call targets, for per-stage edit-churn tracking. Only the two
433/// mutating file tools count: both carry the path in their `path` argument. A
434/// call without a string `path` (or any other tool) contributes nothing.
435pub(crate) fn edited_path(call: &crate::components::ToolCall) -> Option<&str> {
436 matches!(call.name.as_str(), "write_file" | "edit_file")
437 .then(|| call.arguments.get("path").and_then(|v| v.as_str()))
438 .flatten()
439}
440
441/// The global config's `[nudge]` defaults, captured per agent at spawn time so
442/// a hot-reloaded config applies from the next run rather than mutating live
443/// ones (same snapshot semantics as the batch-tool-hint global). Absent on
444/// worlds that spawn agents without going through the seeded spawn (tests,
445/// embedders); [`leviath_core::resolve_nudge`] then falls through to the
446/// built-in defaults.
447#[derive(Component, Debug, Clone, Default)]
448pub struct GlobalNudge(pub leviath_core::NudgeConfig);
449
450/// Whether this stage's deliverable *is* its text response.
451///
452/// A stage with interaction points presents what it writes for the user to
453/// approve, revise or edit - the text is the work product, not a model stalling
454/// before it starts. Nudging one is worse than wasteful: the nudge says "use
455/// your tools to complete the task", and a stage built to produce a document
456/// usually has no tool that could. A planning stage told to complete the task
457/// went looking for a way to write the file, found none, and asked the user to
458/// grant it a write tool or create the file by hand - instead of ending the
459/// stage and presenting the plan it had already finished writing.
460pub(crate) fn stage_output_is_reviewed(bp: &AgentBlueprint, cursor: &StageCursor) -> bool {
461 matches!(
462 bp.0.stages.get(cursor.index).map(|s| &s.mode),
463 Some(leviath_core::blueprint::StageMode::InteractivePoints { points }) if !points.is_empty()
464 )
465}
466
467/// What `handle_empty_response` selects.
468///
469/// `&'static` is bevy's `WorldQuery` convention, not a claim about
470/// lifetimes: the borrow is bound when the query is fetched.
471type EmptyResponseQuery = (
472 Entity,
473 &'static mut ContextWindow,
474 &'static crate::components::InferenceResult,
475 &'static mut StageProgress,
476 &'static AgentBlueprint,
477 &'static StageCursor,
478 Option<&'static GlobalNudge>,
479);
480
481/// Empty-response system: for each `ReadyForTransition` agent decide whether the
482/// stage is done. If the agent has already made tool calls, its nudge is
483/// disabled, or it has been nudged its budgeted number of times, the text
484/// response is accepted and the agent advances to `ResolveTransition`.
485/// Otherwise (text only, no work yet) the response + the stage's nudge are
486/// added to context and the agent loops back to `ReadyToInfer`. Ported from
487/// `AgentEngine::loop_handle_empty_tool_calls`.
488///
489/// The nudge is programmable per stage (`[stages.<name>.nudge]`), per agent
490/// (`[agent.nudge]`), and globally (config `[nudge]`), each field cascading
491/// independently through [`leviath_core::resolve_nudge`]. With nothing
492/// configured, a stage whose output is reviewed is never nudged - see
493/// `stage_output_is_reviewed` - but an explicit `enabled` at any level speaks
494/// for itself. The text supports `{stage}` and `{regions}` placeholders.
495pub fn handle_empty_response(
496 mut agents: Query<EmptyResponseQuery, With<ReadyForTransition>>,
497 mut commands: Commands,
498) {
499 crate::tick_scope::clear();
500 for (entity, mut window, infer, mut progress, bp, cursor, global) in agents.iter_mut() {
501 crate::tick_scope::enter(entity);
502 let stage = bp.0.stages.get(cursor.index);
503 let nudge = leviath_core::resolve_nudge(
504 global.map(|g| &g.0),
505 bp.0.nudge.as_ref(),
506 stage.and_then(|s| s.nudge.as_ref()),
507 stage_output_is_reviewed(bp, cursor),
508 );
509 if progress.total_tool_calls > 0 || !nudge.enabled || progress.text_only_nudges >= nudge.max
510 {
511 commands
512 .entity(entity)
513 .remove::<ReadyForTransition>()
514 .insert(ResolveTransition);
515 } else {
516 progress.text_only_nudges += 1;
517 let response_tokens = leviath_core::estimate_tokens(&infer.response);
518 let _ = window.add_typed_entry(
519 "conversation",
520 leviath_core::EntryKind::AssistantTurn { tool_calls: vec![] },
521 infer.response.clone(),
522 response_tokens,
523 );
524 let stage_name = stage.map(|s| s.name.as_str()).unwrap_or("");
525 let regions = stage
526 .and_then(|s| s.context_layout.as_ref())
527 .unwrap_or(&bp.0.context_layout)
528 .regions
529 .iter()
530 .filter(|r| r.required)
531 .map(|r| r.name.as_str())
532 .collect::<Vec<_>>()
533 .join(", ");
534 let text = leviath_core::text::interpolate(
535 &nudge.text,
536 &[("stage", stage_name), ("regions", ®ions)],
537 );
538 inject_system_nudge(&mut window, &text);
539 commands
540 .entity(entity)
541 .remove::<ReadyForTransition>()
542 .insert(ReadyToInfer);
543 }
544 }
545}
546
547/// Append a `[System]` nudge to the conversation region: the one injection path
548/// shared by the empty-response nudge, the required-region nudges, and the
549/// transition-gate hold, so every nudge reaches the model with the same shape.
550/// (An unprefixed `Text` entry assembles as a user message, so the prefix is
551/// what distinguishes framework guidance from real user input.)
552pub(crate) fn inject_system_nudge(window: &mut ContextWindow, text: &str) {
553 let content = format!("[System] {text}");
554 let tokens = leviath_core::estimate_tokens(&content);
555 let _ = window.add_to_region("conversation", content, tokens);
556}