Skip to main content

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                    //
156                    // Every region the window carries, not only the ones this
157                    // stage assembles: a stage layout hides the regions it does
158                    // not declare rather than dropping them, and they are
159                    // recorded here all the same.
160                    for region in window.iter().flat_map(|w| w.regions.iter()) {
161                        let seen = rec.region_tokens.entry(region.name.clone()).or_insert(0);
162                        *seen = (*seen).max(region.current_tokens);
163                    }
164                    warn_if_context_is_running_away(rec, response.tokens_used.prompt_tokens);
165                }
166                // Buffer the readable output + a token line for the stage's logs.
167                if let Some(mut buffer) = buffer {
168                    if !response.content.trim().is_empty() {
169                        buffer.output.push((idx, response.content.clone()));
170                    }
171                    buffer.logs.push((
172                        idx,
173                        format!(
174                            "[Tokens: {} in, {} out]",
175                            response.tokens_used.prompt_tokens,
176                            response.tokens_used.completion_tokens
177                        ),
178                    ));
179                }
180                let result = to_inference_result(&response);
181                commands
182                    .entity(outcome.entity)
183                    .insert(result)
184                    .remove::<AwaitingInference>()
185                    .remove::<InFlightWork>()
186                    .insert(ProcessResponse);
187            }
188            Err(err) => {
189                // A provider that is out of credits or holding a rejected key
190                // is not this request's problem: every later request to it
191                // fails the same way. Move the stage to the next candidate and
192                // try again rather than killing the run (issue #201).
193                let next = err.unavailable_reason().and_then(|_| {
194                    let si = inference.as_deref_mut()?;
195                    (!si.fallbacks.is_empty()).then(|| si.fallbacks.remove(0))
196                });
197                if let Some(next) = next {
198                    // Loud on purpose. Silently swapping providers is how a
199                    // factory ends up running on a model nobody chose.
200                    tracing::warn!(
201                        from_provider = %called_provider,
202                        from_model = %called_model,
203                        to_provider = %next.provider,
204                        to_model = %next.model,
205                        error = %err,
206                        "provider unusable; failing over to the next configured model"
207                    );
208                    if let Some(mut buffer) = buffer {
209                        buffer.logs.push((
210                            idx,
211                            format!(
212                                "[failover] {called_provider}/{called_model} is unusable \
213                                 ({err}); retrying on {}/{}",
214                                next.provider, next.model
215                            ),
216                        ));
217                    }
218                    let si = inference
219                        .as_deref_mut()
220                        .expect("the failover branch only runs with a StageInference");
221                    si.provider_name = next.provider;
222                    si.model = next.model;
223                    // Back to ready, not errored: the next tick dispatches it
224                    // against the new provider and takes that model's permit.
225                    // The iteration is deliberately not bumped - the agent has
226                    // still not had a turn.
227                    commands
228                        .entity(outcome.entity)
229                        .remove::<AwaitingInference>()
230                        .remove::<InFlightWork>()
231                        .insert(ReadyToInfer);
232                    continue;
233                }
234                // Running out of credits with no candidate left is an account
235                // state, not a defect in the run: the operator tops up and
236                // resumes. Failing here would make the run permanently
237                // unresumable, so it pauses instead, still pointed at the same
238                // inference, and a `lev resume` re-dispatches it (issue #413).
239                if err.unavailable_reason()
240                    == Some(leviath_providers::UnavailableReason::CreditsExhausted)
241                {
242                    let message = format!(
243                        "out of credits ({err}); pausing this run - top up the \
244                         account, then `lev resume` it"
245                    );
246                    tracing::warn!(error = %err, "out of credits; pausing the run for a resume");
247                    if let Some(mut buffer) = buffer {
248                        buffer.logs.push((idx, format!("[paused] {message}")));
249                    }
250                    state.status = AgentStatus::Paused;
251                    commands
252                        .entity(outcome.entity)
253                        .remove::<AwaitingInference>()
254                        .remove::<InFlightWork>()
255                        .insert(ReadyToInfer);
256                    continue;
257                }
258                if let Some(mut buffer) = buffer {
259                    buffer.logs.push((idx, format!("[error] {err}")));
260                }
261                // Record the error and route it to the stage's transition logic
262                // (which follows an `error`-conditioned edge if the stage has one,
263                // e.g. → error_recovery, or terminates the run otherwise).
264                state.status = AgentStatus::Error {
265                    message: err.to_string(),
266                };
267                commands
268                    .entity(outcome.entity)
269                    .remove::<AwaitingInference>()
270                    .remove::<InFlightWork>()
271                    .insert(StageOutcome::Errored(err.to_string()))
272                    .insert(ResolveTransition);
273            }
274        }
275    }
276}
277
278/// The response had tool calls; the agent is ready for the tool-dispatch system
279/// to run them (the calls live on its `InferenceResult`).
280#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
281pub struct ReadyForTools;
282
283/// The response had no tool calls; the agent is ready for the empty-response
284/// handler to decide finish vs. a "use your tools" nudge.
285#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
286pub struct ReadyForTransition;
287
288/// The agent's current stage is complete; the transition system will resolve the
289/// next stage (or completion).
290#[derive(Component, Debug, Clone, Copy, PartialEq, Eq)]
291pub struct ResolveTransition;
292
293/// How much bigger than its first call a stage's prompt may get before the run
294/// says so.
295///
296/// The runtime notices a stalled run and a stuck one; it noticed nothing about
297/// the failure that actually costs money - a region filling up and being
298/// re-sent on every call. Measured, a profile stage capped at 10 iterations
299/// billed 1,135,289 tokens, roughly 113k per call, because an uncapped read had
300/// filled its region. Nothing warned, and the run looked healthy from the
301/// outside until the bill arrived.
302///
303/// Four rather than two: a stage that reads a file and then works with it has
304/// genuinely grown, and warning about that would be noise. Four is past the
305/// point where growth is explained by ordinary accumulation.
306const RUNAWAY_CONTEXT_FACTOR: usize = 4;
307
308/// Say so when a stage's per-call prompt has grown past
309/// [`RUNAWAY_CONTEXT_FACTOR`] times its first call.
310///
311/// Once per stage, on the crossing. Repeating it every call afterwards would
312/// bury the run's other output in exactly the situation where that output
313/// matters.
314pub(crate) fn warn_if_context_is_running_away(
315    rec: &mut leviath_core::run_meta::StageRecord,
316    prompt_tokens: usize,
317) {
318    let first = match rec.first_call_prompt_tokens {
319        Some(first) => first,
320        None => {
321            rec.first_call_prompt_tokens = Some(prompt_tokens);
322            return;
323        }
324    };
325    if rec.runaway_warned || first == 0 || prompt_tokens < first * RUNAWAY_CONTEXT_FACTOR {
326        return;
327    }
328    rec.runaway_warned = true;
329    tracing::warn!(
330        stage = %rec.name,
331        first_call_prompt_tokens = first,
332        this_call_prompt_tokens = prompt_tokens,
333        "this stage's context has grown past {RUNAWAY_CONTEXT_FACTOR}x its first call and is \
334         re-sent on every call; check whether a region is accumulating without a cap \
335         (`lev stages <run-id>` shows the per-region sizes)"
336    );
337}
338
339/// Per-stage progress counters, reset when an agent enters a stage.
340#[derive(Component, Debug, Clone, Default)]
341pub struct StageProgress {
342    /// Total tool calls the agent has made in this stage.
343    pub total_tool_calls: usize,
344    /// Consecutive text-only responses that were nudged toward tool use.
345    pub text_only_nudges: usize,
346    /// Inferences run in this stage (per-stage, unlike the run-cumulative
347    /// `AgentState.iteration`), for enforcing the stage's `max_iterations`.
348    pub iterations: usize,
349    /// Successful file-modifying tool calls (`write_file`/`edit_file`, plus any
350    /// tool named by an outgoing gate) made in this stage. Read by the
351    /// transition gate to enforce `require_modifications`.
352    pub modifying_tool_calls: usize,
353    /// Modifying tool calls the permission layer refused (`[denied] ...`). A
354    /// gate lets the transition through when this is non-zero: the agent is
355    /// trying to write and cannot, so re-running the stage only burns budget.
356    pub blocked_modification_calls: usize,
357    /// Content digests of the regions this stage's outgoing gates watch, as
358    /// they stood when the stage was entered.
359    ///
360    /// Only the watched regions: hashing every region on every entry would
361    /// cost the whole window for a feature most stages do not use. Empty for a
362    /// stage with no `require_region_updated` gate, which is the common case.
363    pub entry_region_digests: std::collections::HashMap<String, u64>,
364    /// How many times a transition gate has already sent this stage back for
365    /// another pass. Bounded by the gate's `max_attempts`.
366    pub gate_reentries: usize,
367    /// Unix seconds of the first tick this agent was ready to infer in the
368    /// stage - the clock a `stuck_after_minutes` threshold reads. Stamped
369    /// lazily by [`detect_stuck_stage`] so spawn, `enter_stage` and
370    /// [`force_transition`] all get a fresh clock from the `Default` reset
371    /// without threading a clock through their signatures.
372    pub stage_started_at: Option<i64>,
373    /// `write_file`/`edit_file` calls made in this stage, keyed by target path.
374    /// Feeds the `stuck_after_same_file_edits` threshold.
375    pub edits_by_path: std::collections::HashMap<String, usize>,
376    /// A `stuck` edge has already fired in this stage. One-shot per stage entry:
377    /// without it a stuck interrupt whose edge became unavailable would ping-pong
378    /// between [`detect_stuck_stage`] and [`resolve_transition`]'s resume arm.
379    pub stuck_fired: bool,
380}
381
382/// How a stage ended, when that governs the transition. Absent ⇒ the stage
383/// completed normally. Read by [`resolve_transition`] to follow an
384/// `error`/`max_iterations`/`stuck`-conditioned edge (e.g. → error_recovery)
385/// when the stage errored, hit its iteration cap, or stopped making progress.
386#[derive(Component, Debug, Clone, PartialEq, Eq)]
387pub enum StageOutcome {
388    /// The stage errored (carries the error message for the terminal case).
389    Errored(String),
390    /// The stage hit its `max_iterations` cap.
391    MaxIterations,
392    /// A `stuck` edge tripped mid-stage; carries the human-readable reason.
393    Stuck(String),
394}
395
396/// One [`StageRecord`](leviath_core::run_meta::StageRecord) per blueprint stage,
397/// seeded at spawn (names + `Pending`) and reconciled by [`dispatch_persistence`]
398/// (status + timestamps), with per-stage tokens accrued by [`collect_inference`].
399/// Serialized to `stages.json` so the dashboard / serve API can show every
400/// stage's real name and status - not just the active one (whose name is the only
401/// one carried in `meta.json`).
402#[derive(Component, Debug, Clone)]
403pub struct StageLedger(pub Vec<leviath_core::run_meta::StageRecord>);
404
405/// Buffered per-stage output/log lines awaiting the persistence lane. Emitters
406/// ([`collect_inference`], [`collect_tools`]) push; [`dispatch_persistence`]
407/// drains and clears, forwarding the lines to `stages/<idx>/output.log` (readable
408/// assistant output) and `stages/<idx>/logs.log` (tool + token + error events).
409#[derive(Component, Debug, Clone, Default)]
410pub struct StageIoBuffer {
411    /// Readable assistant output lines, each tagged with its stage index.
412    pub output: Vec<(usize, String)>,
413    /// Operational log lines (tool activity, token counts, errors), each tagged
414    /// with its stage index.
415    pub logs: Vec<(usize, String)>,
416}
417
418/// What `process_response` selects.
419///
420/// `&'static` is bevy's `WorldQuery` convention, not a claim about
421/// lifetimes: the borrow is bound when the query is fetched.
422type ProcessResponseQuery = (
423    Entity,
424    &'static crate::components::InferenceResult,
425    &'static mut StageProgress,
426    Option<&'static mut crate::persistence::TokenTotals>,
427);
428
429/// Process-response system: route each `ProcessResponse` agent by whether its
430/// last inference asked for tools. Tool calls present ⇒ `ReadyForTools` (and the
431/// stage's running tool-call count is bumped); none ⇒ `ReadyForTransition`. Pure
432/// routing - no I/O.
433pub fn process_response(
434    mut agents: Query<ProcessResponseQuery, With<ProcessResponse>>,
435    mut commands: Commands,
436) {
437    crate::tick_scope::clear();
438    for (entity, result, mut progress, totals) in agents.iter_mut() {
439        crate::tick_scope::enter(entity);
440        progress.iterations += 1; // per-stage inference count (for max_iterations)
441        let mut e = commands.entity(entity);
442        e.remove::<ProcessResponse>();
443        if result.tool_calls.is_empty() {
444            e.insert(ReadyForTransition);
445        } else {
446            progress.total_tool_calls += result.tool_calls.len();
447            // Per-path edit churn, for `stuck` edges armed on same-file edits.
448            // Counted from the *requested* calls: a model asking to edit the
449            // same wrong file five times is stuck whether or not each call ran.
450            for path in result.tool_calls.iter().filter_map(edited_path) {
451                *progress.edits_by_path.entry(path.to_string()).or_insert(0) += 1;
452            }
453            if let Some(mut totals) = totals {
454                totals.tool_calls += result.tool_calls.len();
455            }
456            e.insert(ReadyForTools);
457        }
458    }
459}
460
461/// The path a tool call targets, for per-stage edit-churn tracking. Only the two
462/// mutating file tools count: both carry the path in their `path` argument. A
463/// call without a string `path` (or any other tool) contributes nothing.
464pub(crate) fn edited_path(call: &crate::components::ToolCall) -> Option<&str> {
465    matches!(call.name.as_str(), "write_file" | "edit_file")
466        .then(|| call.arguments.get("path").and_then(|v| v.as_str()))
467        .flatten()
468}
469
470/// The global config's `[nudge]` defaults, captured per agent at spawn time so
471/// a hot-reloaded config applies from the next run rather than mutating live
472/// ones (same snapshot semantics as the batch-tool-hint global). Absent on
473/// worlds that spawn agents without going through the seeded spawn (tests,
474/// embedders); [`leviath_core::resolve_nudge`] then falls through to the
475/// built-in defaults.
476#[derive(Component, Debug, Clone, Default)]
477pub struct GlobalNudge(pub leviath_core::NudgeConfig);
478
479/// Whether this stage's deliverable *is* its text response.
480///
481/// A stage with interaction points presents what it writes for the user to
482/// approve, revise or edit - the text is the work product, not a model stalling
483/// before it starts. Nudging one is worse than wasteful: the nudge says "use
484/// your tools to complete the task", and a stage built to produce a document
485/// usually has no tool that could. A planning stage told to complete the task
486/// went looking for a way to write the file, found none, and asked the user to
487/// grant it a write tool or create the file by hand - instead of ending the
488/// stage and presenting the plan it had already finished writing.
489pub(crate) fn stage_output_is_reviewed(bp: &AgentBlueprint, cursor: &StageCursor) -> bool {
490    matches!(
491        bp.0.stages.get(cursor.index).map(|s| &s.mode),
492        Some(leviath_core::blueprint::StageMode::InteractivePoints { points }) if !points.is_empty()
493    )
494}
495
496/// What `handle_empty_response` selects.
497///
498/// `&'static` is bevy's `WorldQuery` convention, not a claim about
499/// lifetimes: the borrow is bound when the query is fetched.
500type EmptyResponseQuery = (
501    Entity,
502    &'static mut ContextWindow,
503    &'static crate::components::InferenceResult,
504    &'static mut StageProgress,
505    &'static AgentBlueprint,
506    &'static StageCursor,
507    Option<&'static GlobalNudge>,
508);
509
510/// Empty-response system: for each `ReadyForTransition` agent decide whether the
511/// stage is done. If the agent has already made tool calls, its nudge is
512/// disabled, or it has been nudged its budgeted number of times, the text
513/// response is accepted and the agent advances to `ResolveTransition`.
514/// Otherwise (text only, no work yet) the response + the stage's nudge are
515/// added to context and the agent loops back to `ReadyToInfer`. Ported from
516/// `AgentEngine::loop_handle_empty_tool_calls`.
517///
518/// The nudge is programmable per stage (`[stages.<name>.nudge]`), per agent
519/// (`[agent.nudge]`), and globally (config `[nudge]`), each field cascading
520/// independently through [`leviath_core::resolve_nudge`]. With nothing
521/// configured, a stage whose output is reviewed is never nudged - see
522/// `stage_output_is_reviewed` - but an explicit `enabled` at any level speaks
523/// for itself. The text supports `{stage}` and `{regions}` placeholders.
524pub fn handle_empty_response(
525    mut agents: Query<EmptyResponseQuery, With<ReadyForTransition>>,
526    mut commands: Commands,
527) {
528    crate::tick_scope::clear();
529    for (entity, mut window, infer, mut progress, bp, cursor, global) in agents.iter_mut() {
530        crate::tick_scope::enter(entity);
531        let stage = bp.0.stages.get(cursor.index);
532        let nudge = leviath_core::resolve_nudge(
533            global.map(|g| &g.0),
534            bp.0.nudge.as_ref(),
535            stage.and_then(|s| s.nudge.as_ref()),
536            stage_output_is_reviewed(bp, cursor),
537        );
538        if progress.total_tool_calls > 0 || !nudge.enabled || progress.text_only_nudges >= nudge.max
539        {
540            commands
541                .entity(entity)
542                .remove::<ReadyForTransition>()
543                .insert(ResolveTransition);
544        } else {
545            progress.text_only_nudges += 1;
546            let response_tokens = leviath_core::estimate_tokens(&infer.response);
547            let _ = window.add_typed_entry(
548                "conversation",
549                leviath_core::EntryKind::AssistantTurn { tool_calls: vec![] },
550                infer.response.clone(),
551                response_tokens,
552            );
553            let stage_name = stage.map(|s| s.name.as_str()).unwrap_or("");
554            let regions = stage
555                .and_then(|s| s.context_layout.as_ref())
556                .unwrap_or(&bp.0.context_layout)
557                .regions
558                .iter()
559                .filter(|r| r.required)
560                .map(|r| r.name.as_str())
561                .collect::<Vec<_>>()
562                .join(", ");
563            let text = leviath_core::text::interpolate(
564                &nudge.text,
565                &[("stage", stage_name), ("regions", &regions)],
566            );
567            inject_system_nudge(&mut window, &text);
568            commands
569                .entity(entity)
570                .remove::<ReadyForTransition>()
571                .insert(ReadyToInfer);
572        }
573    }
574}
575
576/// Append a `[System]` nudge to the conversation region: the one injection path
577/// shared by the empty-response nudge, the required-region nudges, and the
578/// transition-gate hold, so every nudge reaches the model with the same shape.
579/// (An unprefixed `Text` entry assembles as a user message, so the prefix is
580/// what distinguishes framework guidance from real user input.)
581pub(crate) fn inject_system_nudge(window: &mut ContextWindow, text: &str) {
582    let content = format!("[System] {text}");
583    let tokens = leviath_core::estimate_tokens(&content);
584    let _ = window.add_to_region("conversation", content, tokens);
585}