Skip to main content

mur_common/hitl/
mod.rs

1//! Risk-tiered HITL vocabulary shared across the executor, runtime, and surfaces.
2
3use serde::{Deserialize, Serialize};
4
5pub mod approval_token;
6pub mod bash_class;
7pub mod builtin_tier;
8pub mod dest;
9pub mod floor_waiver;
10mod heredoc_data;
11pub mod intent;
12pub mod label;
13mod opaque_shell;
14pub mod pin;
15pub mod signed_time;
16pub mod startup_waiver;
17pub mod tool_tier;
18
19pub use signed_time::{HITL_CLOCK_SKEW_SECS, TimeFault, check_answer_time, check_fresh};
20
21/// Approvals and denials settle a gate for this long. Content staleness is
22/// already handled by the hash pin (any input change = a different hash); the
23/// TTL bounds TIME staleness, so a weeks-old approval cannot release a gate
24/// nobody remembers granting. Measured on the signed `issued_at` only — see
25/// [`signed_time`]. Shared by gate A (`mur-core::hitl::gate`) and
26/// gate B (`mur-agent-runtime::hitl::store`) — one number, or the two gates
27/// remember for different lengths and the Hub cannot explain why.
28pub const APPROVAL_TTL_SECS: i64 = 7 * 24 * 60 * 60;
29
30/// `message/send` param: `false` makes this turn's tool approvals one-shot —
31/// gate B neither answers them from the agent's remembered decisions nor
32/// records the human's answer there. Absent means `true` (chat behaviour).
33/// A `mur fleet review` turn sends `false`: its gate always asks (#1783).
34pub const REMEMBER_DECISIONS_PARAM: &str = "remember_decisions";
35
36/// How risky an action is. `Ord` is severity order: `Read` < … < `Privileged`.
37/// Tier is resolved most-restrictive-wins and is NEVER LLM-asserted.
38#[derive(
39    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
40)]
41#[serde(rename_all = "kebab-case")]
42pub enum RiskTier {
43    Read,
44    Write,
45    NetworkEgress,
46    Spend,
47    Destructive,
48    Privileged,
49}
50
51/// What the gate does for a tier.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "lowercase")]
54pub enum HitlMode {
55    /// Run unattended (read tier): a post-hoc audit event is fine.
56    Auto,
57    /// Pre-execution human approval required.
58    Ask,
59    /// Refuse pre-emptively.
60    Deny,
61}
62
63/// Default gate mode for a tier. Read runs unattended; everything mutating asks.
64/// A channel policy floor (future) may tighten Ask→Deny but never loosen.
65pub fn default_mode(tier: RiskTier) -> HitlMode {
66    match tier {
67        RiskTier::Read => HitlMode::Auto,
68        _ => HitlMode::Ask,
69    }
70}
71
72/// What an Ask-tier gate does when nobody has answered yet.
73///
74/// This is a policy floor, chosen by the run's owner — it may only tighten the
75/// outcome, never approve anything. `Deny` short-circuits before any lookup so
76/// a fleet declared free of risk-tiered work stays that way even if some older
77/// approval for the same action is still on the channel.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "lowercase")]
80pub enum Unanswered {
81    /// Park the request durably and report the step blocked. Nobody waits; an
82    /// approval arriving later releases the gate on a subsequent run. The
83    /// default when no human is watching.
84    Defer,
85    /// Block the caller, polling until the gate timeout. The default when a
86    /// terminal is attached, and the right choice for an unattended run that
87    /// somebody IS watching on another surface.
88    Wait,
89    /// Refuse every Ask-tier action outright, without writing a request. For a
90    /// run that must never reach for a human — the failure is immediate and
91    /// legible instead of a request nobody will answer.
92    Deny,
93}
94
95impl Default for Unanswered {
96    /// The strict end of the three: a policy built without stating a mode must
97    /// never be the one that waits or lets something through.
98    fn default() -> Self {
99        Unanswered::Defer
100    }
101}
102
103/// May a run's owner take standing responsibility for this tier in config —
104/// i.e. pre-approve it once instead of being asked every time?
105///
106/// Capped at `Write` deliberately. A standing grant is real authority handed
107/// to an unattended process, so widening it is a decision to make in code with
108/// its reasoning written down, never something a user acquires by typing one
109/// more word into a YAML file. `Spend`, `Destructive` and `Privileged` are
110/// exactly the actions whose cost a human cannot undo by noticing later, and
111/// `NetworkEgress` is how data leaves — none of them belongs behind a config
112/// line today.
113pub fn tier_may_be_granted(tier: RiskTier) -> bool {
114    matches!(tier, RiskTier::Read | RiskTier::Write)
115}
116
117/// May a one-boot startup override (`--no-hitl`) answer an ask for this tier?
118///
119/// Exhaustive on purpose: a new tier fails to compile here until someone
120/// decides. Not a range test — `RiskTier` orders `Spend` below `Destructive`,
121/// and `Spend`'s cost lands off the host and adds up per call, which nobody
122/// undoes by noticing later. `None` (unclassified) is refused too: the runtime
123/// reaches the gate with `None` for an undeclared MCP tool, so waiving it would
124/// waive whatever that tool really does. [`tier_may_be_granted`] is a separate,
125/// narrower question (a standing grant) and is not widened by this.
126pub fn tier_may_be_waived(tier: Option<RiskTier>) -> bool {
127    match tier {
128        Some(
129            RiskTier::Read | RiskTier::Write | RiskTier::NetworkEgress | RiskTier::Destructive,
130        ) => true,
131        Some(RiskTier::Spend | RiskTier::Privileged) => false,
132        None => false,
133    }
134}
135
136/// How far the agent carries a turn on its own before handing back.
137///
138/// ORTHOGONAL to `HitlMode`/`RiskTier`. Those answer "may this ACTION run?"
139/// and are enforced per tool call; this answers "is the TURN over?" and is
140/// enforced once, at the loop's termination branch. Neither may overrule the
141/// other: `Continue` never releases a risk gate, and an approved gate never
142/// extends a turn. Issue #001 is what happens when only the prompt layer
143/// carries this — the model reads "已授權工作持續推進" as a suggestion because
144/// nothing in the runtime ever re-entered the loop.
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
146#[serde(rename_all = "kebab-case")]
147pub enum Autonomy {
148    /// Mode 1, 持續推進 — a turn that ends with work still open is nudged back
149    /// into the loop instead of returning. Never implicit, not even for
150    /// unattended runs: handing an agent the right to keep going is written
151    /// down in a profile, because nobody is in the room to take it back.
152    Continue,
153    /// Mode 2, 需要再審核 — the agent finishes its own work but must present it
154    /// for review before anything further; the turn ends where it would anyway.
155    Review,
156    /// Mode 3, 用戶審核 — hand back at every natural stop. The strictest of the
157    /// three and the default when nothing is stated.
158    Ask,
159}
160
161impl Default for Autonomy {
162    /// The strict end, matching `Unanswered::default()`: a policy assembled
163    /// without stating a mode must never be the one that keeps going by
164    /// itself.
165    fn default() -> Self {
166        Autonomy::Ask
167    }
168}
169
170/// How many times one turn may be nudged onward. Bounded, and small: the
171/// iteration ceiling and the stuck clock are the real budgets, and a
172/// continuation that could fire endlessly would quietly convert both into a
173/// suggestion. One nudge is enough to fix #001 (the model stopped once, mid
174/// task) without inventing a second, parallel loop.
175pub const MAX_CONTINUATIONS: u32 = 1;
176
177/// Why a turn was NOT continued. Every variant is a thing the settlement card
178/// can print, because "it just stopped" is the bug being fixed.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum ContinueVeto {
181    /// Policy says hand back — `Review` or `Ask`.
182    Policy,
183    /// A1: the turn did not end cleanly (ceiling, loop, deadline, stuck,
184    /// truncation). Those stops already have their own graceful exit and a
185    /// nudge would fight it.
186    UnCleanStop,
187    /// A2: a risk gate blocked, denied or deferred something this turn. The
188    /// human IS the next step; nudging would spin against a closed gate.
189    GateBlocked,
190    /// The nudge budget for this turn is spent.
191    BudgetSpent,
192}
193
194/// The whole continuation decision, as one pure function so the policy is
195/// testable without a model, a gate, or a clock.
196///
197/// `clean_stop` is "the model ended the turn of its own accord". `gate_blocked`
198/// is "at least one action this turn was refused, denied or parked". Both are
199/// facts the loop already holds at the termination branch.
200pub fn should_continue(
201    autonomy: Autonomy,
202    clean_stop: bool,
203    gate_blocked: bool,
204    continuations_used: u32,
205) -> Result<(), ContinueVeto> {
206    if autonomy != Autonomy::Continue {
207        return Err(ContinueVeto::Policy);
208    }
209    if !clean_stop {
210        return Err(ContinueVeto::UnCleanStop);
211    }
212    if gate_blocked {
213        return Err(ContinueVeto::GateBlocked);
214    }
215    if continuations_used >= MAX_CONTINUATIONS {
216        return Err(ContinueVeto::BudgetSpent);
217    }
218    Ok(())
219}
220
221/// `EventKind::HitlRequest` payload: the durable, pinned approval request.
222#[derive(Debug, Clone, Serialize, Deserialize)]
223pub struct HitlRequest {
224    pub hitl_id: String,
225    /// SHA-256 of the canonical action (see `mur-core` `hitl::pin`).
226    pub action_hash: String,
227    pub tier: RiskTier,
228    pub tool_name: String,
229    pub tool_input: serde_json::Value,
230    pub step_or_call_id: String,
231    pub agent_id: String,
232    pub timeout_ms: u64,
233    pub summary: String,
234    /// When the router asked. Inside the payload, so inside the signature —
235    /// unlike the store-assigned `ChannelEvent::ts`, which any process that
236    /// can write the log can rewrite (#1764). `None` is a request written
237    /// before this field existed; it answers nothing (fail closed).
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub issued_at: Option<chrono::DateTime<chrono::Utc>>,
240}
241
242/// `EventKind::HitlResponse` payload: the human's decision, echoing the pin.
243#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct HitlResponse {
245    pub hitl_id: String,
246    pub action_hash: String,
247    pub allow: bool,
248    #[serde(default)]
249    pub reason: String,
250    /// "cli" | "hub" | "ios" | "auto".
251    pub surface: String,
252    /// When the answer was given; signed for the same reason as
253    /// [`HitlRequest::issued_at`]. `None` (an older writer) settles nothing.
254    #[serde(default, skip_serializing_if = "Option::is_none")]
255    pub issued_at: Option<chrono::DateTime<chrono::Utc>>,
256    /// What was decided, for `mur agent hitl list` (#1806): tool name plus a
257    /// redacted, truncated summary built by [`label::decision_label`]. It is
258    /// written into a signed append-only log, so it must never carry raw
259    /// input. `None` = an older writer, or a surface that has no tool call.
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub label: Option<String>,
262}
263
264/// `message/send`-style A2A methods for gate B's remembered decisions (#1806).
265pub const HITL_LIST_METHOD: &str = "hitl/list";
266pub const HITL_FORGET_METHOD: &str = "hitl/forget";
267
268/// #2085: lists the approvals a running agent is waiting on right now, so a
269/// human can answer one from another terminal (`mur agent hitl pending`).
270pub const HITL_PENDING_METHOD: &str = "hitl/pending";
271
272/// #2085: `message/send` param. With `can_approve: false`, an `Ask` call
273/// nobody has decided is parked for at most this many seconds (clamped to the
274/// turn's deadline) instead of refused at once; `mur agent hitl approve`
275/// answers it. Absent = refuse at once, the #2087 behaviour.
276pub const WAIT_APPROVAL_PARAM: &str = "wait_approval_secs";
277
278/// How long `mur agent send --wait-approval` (no value) parks a call. The
279/// turn's deadline still wins when it comes first.
280pub const DEFAULT_WAIT_APPROVAL_SECS: u64 = 30 * 60;
281
282/// Key inside an `EventKind::Note` payload that marks a gate-B revocation.
283/// A `Note` rather than a new `EventKind` so a reader built before #1806
284/// still parses the channel (an unknown kind would fail the whole line).
285pub const REVOCATION_PAYLOAD_KEY: &str = "hitl_revocation";
286
287/// Which remembered decisions a revocation covers.
288#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
289#[serde(rename_all = "snake_case", tag = "scope", content = "action_hash")]
290pub enum RevocationScope {
291    One(String),
292    All,
293}
294
295/// A signed "forget": every decision covered by `scope` whose signed
296/// `issued_at` is not after this one's `issued_at` stops settling the gate.
297/// Nothing is deleted — the log stays append-only (#1770).
298#[derive(Debug, Clone, Serialize, Deserialize)]
299pub struct HitlRevocation {
300    #[serde(flatten)]
301    pub scope: RevocationScope,
302    pub issued_at: chrono::DateTime<chrono::Utc>,
303}
304
305impl HitlRevocation {
306    pub fn to_payload(&self) -> serde_json::Value {
307        serde_json::json!({ REVOCATION_PAYLOAD_KEY: self })
308    }
309
310    /// `None` = not a revocation note (or a malformed one, which revokes
311    /// nothing — the safe reading is "still remembered", and the gate asked
312    /// when that decision was recorded).
313    pub fn from_payload(payload: &serde_json::Value) -> Option<Self> {
314        serde_json::from_value(payload.get(REVOCATION_PAYLOAD_KEY)?.clone()).ok()
315    }
316
317    pub fn covers(&self, action_hash: &str) -> bool {
318        match &self.scope {
319            RevocationScope::All => true,
320            RevocationScope::One(h) => h == action_hash,
321        }
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    #[test]
330    fn tier_orders_by_severity_and_maps_mode() {
331        assert!(RiskTier::Read < RiskTier::Destructive);
332        assert!(RiskTier::Write < RiskTier::Privileged);
333        assert_eq!(default_mode(RiskTier::Read), HitlMode::Auto);
334        assert_eq!(default_mode(RiskTier::Destructive), HitlMode::Ask);
335    }
336
337    #[test]
338    fn hitl_payloads_round_trip() {
339        let req = HitlRequest {
340            hitl_id: "h1".into(),
341            action_hash: "abc".into(),
342            tier: RiskTier::Destructive,
343            tool_name: "bash".into(),
344            tool_input: serde_json::json!({ "cmd": "rm -rf x" }),
345            step_or_call_id: "s0".into(),
346            agent_id: "mur".into(),
347            timeout_ms: 300_000,
348            summary: "delete x".into(),
349            issued_at: Some(chrono::Utc::now()),
350        };
351        let s = serde_json::to_string(&req).unwrap();
352        let back: HitlRequest = serde_json::from_str(&s).unwrap();
353        assert_eq!(back.tier, RiskTier::Destructive);
354        assert_eq!(back.action_hash, "abc");
355    }
356
357    /// The grantable ceiling. Widening this list is a security decision that
358    /// belongs in a commit message, not a YAML typo — the test exists so the
359    /// reviewer has to read the reasoning right here.
360    #[test]
361    fn tier_grant_ceiling_is_write() {
362        assert!(tier_may_be_granted(RiskTier::Read));
363        assert!(tier_may_be_granted(RiskTier::Write));
364        assert!(!tier_may_be_granted(RiskTier::NetworkEgress));
365        assert!(!tier_may_be_granted(RiskTier::Spend));
366        assert!(!tier_may_be_granted(RiskTier::Destructive));
367        assert!(!tier_may_be_granted(RiskTier::Privileged));
368    }
369
370    /// #001 §6 A0: the safe default. An `Autonomy` nobody stated must be the
371    /// one that hands back, never the one that drives itself.
372    #[test]
373    fn autonomy_defaults_to_the_strictest_mode() {
374        assert_eq!(Autonomy::default(), Autonomy::Ask);
375    }
376
377    /// The happy path this whole feature exists for: unattended work, a clean
378    /// stop, no blocked gate, budget unspent → carry on.
379    #[test]
380    fn continue_mode_resumes_a_clean_unblocked_turn() {
381        assert_eq!(should_continue(Autonomy::Continue, true, false, 0), Ok(()));
382    }
383
384    /// The other two modes are handbacks by construction. This is the test
385    /// that keeps "持續推進" from silently becoming the behaviour of all three.
386    #[test]
387    fn review_and_ask_never_continue() {
388        for mode in [Autonomy::Review, Autonomy::Ask] {
389            assert_eq!(
390                should_continue(mode, true, false, 0),
391                Err(ContinueVeto::Policy),
392                "{mode:?} must hand back"
393            );
394        }
395    }
396
397    /// #001 §6 A1: a turn stopped by a budget (ceiling / loop / deadline /
398    /// stuck) already has a graceful exit. Nudging it would fight that exit.
399    #[test]
400    fn an_unclean_stop_is_never_continued() {
401        assert_eq!(
402            should_continue(Autonomy::Continue, false, false, 0),
403            Err(ContinueVeto::UnCleanStop)
404        );
405    }
406
407    /// #001 §6 A2 — THE SAFETY BOUNDARY. Continuation and the risk gate are
408    /// orthogonal: when a gate blocked, denied or deferred something, the
409    /// human is the next step and no autonomy setting may route around them.
410    /// If this test ever goes green with `Ok(())`, `Autonomy::Continue` has
411    /// become a privilege escalation.
412    #[test]
413    fn continuation_never_routes_around_a_blocked_gate() {
414        assert_eq!(
415            should_continue(Autonomy::Continue, true, true, 0),
416            Err(ContinueVeto::GateBlocked)
417        );
418    }
419
420    /// Bounded, and the bound is enforced here rather than by hoping the loop
421    /// converges.
422    #[test]
423    fn continuation_budget_is_spent_after_max() {
424        assert_eq!(
425            should_continue(Autonomy::Continue, true, false, MAX_CONTINUATIONS),
426            Err(ContinueVeto::BudgetSpent)
427        );
428        assert_eq!(
429            should_continue(Autonomy::Continue, true, false, MAX_CONTINUATIONS + 9),
430            Err(ContinueVeto::BudgetSpent)
431        );
432    }
433
434    /// Policy is checked before anything else, so a `Ask` run reports "policy"
435    /// rather than leaking why it would ALSO have been stopped.
436    #[test]
437    fn policy_veto_precedes_every_other_veto() {
438        assert_eq!(
439            should_continue(Autonomy::Ask, false, true, 99),
440            Err(ContinueVeto::Policy)
441        );
442    }
443
444    #[test]
445    fn autonomy_round_trips_as_kebab_case() {
446        let y = serde_yaml::to_string(&Autonomy::Continue).unwrap();
447        assert!(y.contains("continue"), "got {y}");
448        let back: Autonomy = serde_yaml::from_str("review").unwrap();
449        assert_eq!(back, Autonomy::Review);
450    }
451
452    #[test]
453    fn revocation_payload_round_trips_and_ignores_other_notes() {
454        let at = chrono::Utc::now();
455        for scope in [RevocationScope::All, RevocationScope::One("abc".into())] {
456            let r = HitlRevocation {
457                scope: scope.clone(),
458                issued_at: at,
459            };
460            let back = HitlRevocation::from_payload(&r.to_payload()).expect("round trip");
461            assert_eq!(back.scope, scope);
462            assert_eq!(back.issued_at, at);
463        }
464        let one = HitlRevocation {
465            scope: RevocationScope::One("abc".into()),
466            issued_at: at,
467        };
468        assert!(one.covers("abc") && !one.covers("abd"));
469        assert!(HitlRevocation::from_payload(&serde_json::json!({"review": {}})).is_none());
470        assert!(HitlRevocation::from_payload(&serde_json::json!({"hitl_revocation": 1})).is_none());
471    }
472
473    #[test]
474    fn a_response_without_label_still_parses() {
475        let v = serde_json::json!({"hitl_id": "h", "action_hash": "a", "allow": true, "surface": "hub"});
476        let r: HitlResponse = serde_json::from_value(v).unwrap();
477        assert!(r.label.is_none());
478        assert!(!serde_json::to_string(&r).unwrap().contains("label"));
479    }
480}