Skip to main content

agent_types/
guard.rs

1//! Guard-related pure types: GuardDecision, GuardCtx.
2
3use serde::{Deserialize, Serialize};
4
5use crate::execution::FinishReason;
6use crate::session::SessionId;
7
8/// Guard decision — returned by guard, executed by base loop.
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub enum GuardDecision {
11    /// Continue loop, optionally inject nudge message
12    Continue { nudge: Option<String> },
13    /// Normal completion (fire_turn_end + RunOutcome::Completed)
14    Complete,
15    /// Abnormal termination (fire_guard_fail + RunOutcome::Failed)
16    Fail { error: String },
17
18    // ─── Thinking control ─────────────────────────────────────
19    /// Temporarily disable thinking functionality
20    ///
21    /// Used for reasoning-only loop scenarios: model keeps thinking but produces no output.
22    /// After calling, runtime will:
23    /// 1. Set thinking_disabled_for_rest_of_run = true
24    /// 2. Inject nudge message
25    /// 3. Continue loop
26    DisableThinking { nudge: String },
27
28    /// Restore thinking functionality to previous state
29    ///
30    /// Used for thinking recovery scenarios: model starts working normally (has text or tool call).
31    /// After calling, runtime will:
32    /// 1. Restore thinking_disabled_for_rest_of_run to original state
33    /// 2. Reset related counters
34    RestoreThinking,
35
36    // ─── Turn-as-transaction (stream integrity) ───────────────
37    /// Discard this response whole and re-ask the LLM from the same state.
38    ///
39    /// For silent rounds whose tool-call batch is structurally corrupt (wire
40    /// truncation / misplaced args fragments). The kernel executes the
41    /// discard: NO history commit, NO tool execution — the response never
42    /// happened. The retry stays inside the current turn (`turn_count`
43    /// unchanged) and is bounded by the policy budget carried in
44    /// [`GuardCtx::silent_retries_in_round`] plus a kernel hard cap.
45    /// Never returned for rounds whose text already reached the user.
46    RetryTurn,
47}
48
49/// Structural integrity facts about one assembled tool-call batch.
50///
51/// Detection is shape-based (never provider metadata — stop reasons lie):
52/// a named call whose args are non-empty but not valid JSON is wire
53/// truncation; args fragments arriving on a name-less bucket are a misplaced
54/// tail (the provider leaked them past the owning block, e.g. into a
55/// thinking block's index).
56#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
57pub struct StreamIntegrity {
58    /// Named tool calls with non-empty, unparseable args.
59    #[serde(default)]
60    pub invalid_args: usize,
61    /// Bytes of args fragments that landed on name-less buckets.
62    #[serde(default)]
63    pub orphan_args_bytes: usize,
64}
65
66impl StreamIntegrity {
67    pub fn is_clean(&self) -> bool {
68        self.invalid_args == 0 && self.orphan_args_bytes == 0
69    }
70}
71
72/// Guard context information — built by runtime, passed to guard.
73#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct GuardCtx {
75    pub session_id: SessionId,
76    pub turn_count: u32,
77    pub user_input: String,
78    pub model_response: String,
79    pub finish_reason: FinishReason,
80    pub available_tools: Vec<String>,
81    // RunState information
82    pub reasoning_only_strikes: usize,
83    pub empty_response_strikes: usize,
84    #[serde(alias = "run_has_tool_calls")]
85    pub run_has_actions: bool,
86    /// The tools this run has called so far, in order, by name. A completion
87    /// judge handed only `user_input` and `model_response` cannot tell a report
88    /// from a shrug — both are a short text-only turn. This is the work it can
89    /// check the response against. Names only; nothing sensitive rides along.
90    #[serde(default)]
91    pub run_actions: Vec<String>,
92    /// The most recent assistant tool calls were ALL rejected before
93    /// execution (truncated/invalid arguments) and the model was told to
94    /// re-issue them (`RunState.truncation_strikes > 0`). While this is
95    /// true, a text-only response cannot be task completion — the work the
96    /// text describes was never executed (session 20260904_efad759c: a
97    /// fabricated success narrative passed the completion judge).
98    pub last_tool_calls_invalid: bool,
99    /// All user messages in the current session, ordered oldest-first.
100    /// Guards can use this to reconstruct full conversation context
101    /// (e.g. "continue" after a multi-turn discussion).
102    pub all_user_inputs: Vec<String>,
103    // Scene hints (runtime detected, guard can trust or ignore)
104    pub is_reasoning_only: bool,
105    pub is_empty_response: bool,
106    pub is_text_only: bool,
107    /// The run ended with a human step pending: the latest tool batch parked
108    /// on human input (a design-canvas screen awaiting a pick) and no tool ran
109    /// after it. Ending here is *waiting for the user*, not an incomplete task
110    /// — the next input is their answer. A "continue working" nudge in this
111    /// state steamrolls interactive flows (session 20261022_bb8c2dc3: the
112    /// completion judge pushed the model on and it decided the user's design
113    /// choices for them).
114    #[serde(default)]
115    pub awaiting_human: bool,
116    /// Structural facts about this turn's assembled tool-call batch (wire
117    /// corruption detection). Clean on healthy streams.
118    #[serde(default)]
119    pub integrity: StreamIntegrity,
120    /// The response carried visible text (already streamed to the user) —
121    /// a round with text can never be silently discarded.
122    #[serde(default)]
123    pub has_visible_text: bool,
124    /// The response carried thinking content (tolerated as "silent" by
125    /// default policy; tighten via config).
126    #[serde(default)]
127    pub has_thinking: bool,
128    /// Silent retries already spent on the current logical round (a retry
129    /// keeps the same round). Policy budget compares against this; the kernel
130    /// enforces its own hard cap on top.
131    #[serde(default)]
132    pub silent_retries_in_round: u32,
133    // Environment state
134    pub thinking_disabled: bool,
135    /// Original thinking configuration (for restoration)
136    ///
137    /// From RunState.original_thinking_enabled
138    pub original_thinking_enabled: bool,
139    /// Remaining turns before hitting max_turns limit
140    ///
141    /// Guards can use this to nudge the model to wrap up when running low on turns.
142    /// When remaining_turns == 0, the run will be terminated with MaxTurnsExceeded.
143    pub remaining_turns: u32,
144}