Skip to main content

eclipse_core/
approvals.rs

1//! Durable approvals: the pending tool calls of a run, and the answer when it arrives.
2//!
3//! The approval gate is normally a question asked of whoever is driving the loop, and its answer
4//! exists only in that process. That is fine until the process is not there — a CLI run in a
5//! script, a dashboard tab that was closed, a shell that lost its terminal — and then a call the
6//! model made is neither approved nor denied: it is simply unrecorded, and the transcript repairs
7//! it on the next run as "interrupted". The intent is lost.
8//!
9//! This module is the small amount of state that fixes it, and deliberately nothing more: one row
10//! per call the model made and the gate has not answered, keyed by the message that carried it
11//! (`seq`, `ord`), with the answer written into the same row when it arrives. There is no second
12//! state machine, no run registry and no job queue — a *run* is still just a transcript, and the
13//! rows are only the answers that were not in it yet.
14//!
15//! Three answers, not two:
16//!
17//! - [`Decision::Allow`] runs the call;
18//! - [`Decision::Deny`] answers it as declined, with the reason the model reads;
19//! - [`Decision::Defer`] means *nobody has answered and the loop must not guess*. The call is
20//!   recorded and the turn stops. Fail-closed: an unanswered gate is never an approval, and it is
21//!   no longer a silent denial either.
22//!
23//! `Defer` is what makes the state durable without a daemon: the process that asked can exit, and
24//! any later process can look at the same rows and answer them.
25
26use crate::session::SessionStore;
27use crate::Result;
28
29/// Who answered a waiting call, for the `by` column (`#340`).
30///
31/// `user` is every answer that came through a person — `eclipse approve`, a card, a dashboard
32/// button. `judge` is the aux route in `smart` mode. `policy` is reserved for a call a rule
33/// settled without either, so the column's vocabulary is fixed before anything writes a third word.
34pub const DECIDED_BY_USER: &str = "user";
35/// The aux route in `smart` mode (`#340`).
36pub const DECIDED_BY_JUDGE: &str = "judge";
37
38/// One call the model made, as the gate sees it: enough to ask, enough to re-run it later.
39#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
40pub struct Pending {
41    /// The model's id for this call, which is also how its result is matched back.
42    pub call_id: String,
43    pub tool: String,
44    /// The one-liner the gate shows a human (`Tool::describe_call`).
45    pub summary: String,
46    /// The arguments as the call will run: what the model wrote, unless an `on_dispatch` hook
47    /// repaired it before the gate saw it. This row — not the transcript — is what a resumed run
48    /// replays, so it is what the human is shown and what actually happens.
49    pub args: String,
50}
51
52impl Pending {
53    pub fn new(
54        call_id: impl Into<String>,
55        tool: impl Into<String>,
56        summary: String,
57        args: String,
58    ) -> Self {
59        Self {
60            call_id: call_id.into(),
61            tool: tool.into(),
62            summary,
63            args,
64        }
65    }
66}
67
68/// The gate's answer to one call.
69#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
70#[serde(rename_all = "snake_case")]
71pub enum Decision {
72    Allow,
73    /// Declined, with the reason the model reads as the tool result. A denial is information:
74    /// "the user declined" without a why teaches the model nothing.
75    Deny(String),
76    /// Not answered yet. The loop stops rather than deciding on the user's behalf.
77    Defer,
78}
79
80impl Decision {
81    /// How this answer is stored. `Defer` has no row value: a call with no decision *is* deferred,
82    /// and storing "deferred" would make "waiting" look like an answer that had arrived.
83    pub fn store(&self) -> Option<String> {
84        match self {
85            Decision::Allow => Some("allow".to_string()),
86            Decision::Deny(reason) => Some(format!("deny:{reason}")),
87            Decision::Defer => None,
88        }
89    }
90
91    /// The inverse of [`store`](Self::store), for a row that has a decision column set.
92    ///
93    /// Fails closed (`#427`). This used to read anything without a `deny:` prefix as Allow, so a
94    /// row this build did not write — an older scheme, a higher version's word, a hand-edited
95    /// `state.db` — became an approval for a call nobody approved. An unknown answer is a denial
96    /// that says what it did not understand; the only way to allow is to say `allow`.
97    pub fn parse(stored: &str) -> Self {
98        match stored.strip_prefix("deny:") {
99            Some(reason) => Decision::Deny(reason.to_string()),
100            None if stored == "allow" => Decision::Allow,
101            None => Decision::Deny(format!(
102                "the stored answer {stored:?} is not one this build understands, so the call was \
103                 not run"
104            )),
105        }
106    }
107}
108
109/// One line of the append-only log: a call, its answer, and who gave it (`#340`).
110///
111/// The waiting rows in `approvals` are deleted as soon as the answer reaches the transcript, so
112/// this is what a later reader has: "what did the model wave through last week" is a query over
113/// these, and it is answerable because nothing removes them.
114#[derive(Debug, Clone, PartialEq, serde::Serialize)]
115pub struct Ruling {
116    pub at_ms: i64,
117    pub call_id: String,
118    pub tool: String,
119    pub summary: String,
120    pub decision: Decision,
121    pub by: String,
122}
123
124/// One stored row: a call, and the answer if one arrived.
125#[derive(Debug, Clone, PartialEq, serde::Serialize)]
126pub struct PendingCall {
127    /// The `seq` of the assistant message that carried the call.
128    pub seq: i64,
129    /// Its position within that message, so two calls can never collide on one row.
130    pub ord: usize,
131    pub call: Pending,
132    pub decision: Option<Decision>,
133    pub decided_ms: Option<i64>,
134    /// Who answered: `user`, `judge` or `policy` (`#340`). `None` for a row that has no answer
135    /// yet, and for one written before the column existed — nobody recorded it, and saying so is
136    /// better than guessing a name.
137    pub by: Option<String>,
138}
139
140impl PendingCall {
141    pub fn is_waiting(&self) -> bool {
142        self.decision.is_none()
143    }
144}
145
146/// What a run left behind when it stopped on the gate.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct Waiting {
149    pub session: String,
150    /// How many calls are waiting for an answer.
151    pub calls: usize,
152}
153
154impl Waiting {
155    /// The line a human needs: what is waiting and the command that resolves it.
156    pub fn hint(&self) -> String {
157        format!(
158            "{} tool call(s) in {} waiting for an answer; run `eclipse approve {} --all` \
159             (or `--index N`, `--deny <reason>`) to resolve them",
160            self.calls, self.session, self.session
161        )
162    }
163}
164
165/// Record the calls of one assistant message as pending. An existing row is left alone: the same
166/// call re-recorded has the same answer or none, and overwriting it would lose a decision that
167/// arrived while the run was stopping.
168pub fn record(store: &SessionStore, session: &str, seq: i64, calls: &[Pending]) -> Result<()> {
169    store.record_pending(session, seq, calls)
170}
171
172/// The calls waiting for an answer, oldest first.
173pub fn waiting(store: &SessionStore, session: &str) -> Result<Vec<PendingCall>> {
174    Ok(store
175        .pending_calls(session)?
176        .into_iter()
177        .filter(PendingCall::is_waiting)
178        .collect())
179}
180
181/// Answer one waiting call by position, counting from 1 in the order `waiting` prints them.
182pub fn answer(
183    store: &SessionStore,
184    session: &str,
185    index: usize,
186    decision: &Decision,
187) -> Result<()> {
188    let waiting = waiting(store, session)?;
189    // `--index 0` used to be `saturating_sub(1)` == 0, so it silently answered the *first* call: an
190    // operator asking for nothing got the one thing they did not ask for (`#427`). The numbers a
191    // person sees in `eclipse approve` start at 1.
192    let Some(position) = index.checked_sub(1) else {
193        return Err(crate::Error::Session(
194            "call numbers start at 1: there is no call 0 to answer".into(),
195        ));
196    };
197    let Some(row) = waiting.get(position) else {
198        return Err(crate::Error::Session(format!(
199            "there is no waiting call {index} in {session}: {} waiting",
200            waiting.len()
201        )));
202    };
203    store.decide_pending(session, row.seq, row.ord, decision, DECIDED_BY_USER)
204}
205
206/// Answer every waiting call.
207pub fn answer_all(store: &SessionStore, session: &str, decision: &Decision) -> Result<usize> {
208    let waiting = waiting(store, session)?;
209    for row in &waiting {
210        store.decide_pending(session, row.seq, row.ord, decision, DECIDED_BY_USER)?;
211    }
212    Ok(waiting.len())
213}
214
215/// The decision recorded for one call, if any. Used by the resumed run, which must run exactly
216/// what was approved and nothing else.
217pub fn decision_for(
218    store: &SessionStore,
219    session: &str,
220    call_id: &str,
221) -> Result<Option<Decision>> {
222    Ok(store
223        .pending_calls(session)?
224        .into_iter()
225        .find(|row| row.call.call_id == call_id)
226        .and_then(|row| row.decision))
227}
228
229/// The store's answers, asked of the gate that replays a paused turn.
230///
231/// A resumed call is not asked of the user again: the answer is already in the row. But a call the
232/// resumed tool makes *itself* — a subagent's, or one a router re-dispatches — is a new decision
233/// with no row, and that one goes to the live gate as usual rather than being waved through by
234/// association. `Defer` for a row that has gone missing is the fail-closed answer: the transcript
235/// says this call was waiting, so nothing else may stand in for the answer.
236pub struct Recorded<'a> {
237    store: &'a SessionStore,
238    session: &'a str,
239    inner: &'a dyn crate::tools::Approver,
240}
241
242impl<'a> Recorded<'a> {
243    pub fn new(
244        store: &'a SessionStore,
245        session: &'a str,
246        inner: &'a dyn crate::tools::Approver,
247    ) -> Self {
248        Self {
249            store,
250            session,
251            inner,
252        }
253    }
254}
255
256#[async_trait::async_trait]
257impl crate::tools::Approver for Recorded<'_> {
258    async fn decide(&self, call: &Pending) -> Decision {
259        match decision_for(self.store, self.session, &call.call_id) {
260            Ok(Some(decision)) => decision,
261            Ok(None) => self.inner.decide(call).await,
262            Err(_) => Decision::Defer,
263        }
264    }
265}
266
267#[cfg(test)]
268mod tests;