eclipse-core 0.13.3

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! Durable approvals: the pending tool calls of a run, and the answer when it arrives.
//!
//! The approval gate is normally a question asked of whoever is driving the loop, and its answer
//! exists only in that process. That is fine until the process is not there — a CLI run in a
//! script, a dashboard tab that was closed, a shell that lost its terminal — and then a call the
//! model made is neither approved nor denied: it is simply unrecorded, and the transcript repairs
//! it on the next run as "interrupted". The intent is lost.
//!
//! This module is the small amount of state that fixes it, and deliberately nothing more: one row
//! per call the model made and the gate has not answered, keyed by the message that carried it
//! (`seq`, `ord`), with the answer written into the same row when it arrives. There is no second
//! state machine, no run registry and no job queue — a *run* is still just a transcript, and the
//! rows are only the answers that were not in it yet.
//!
//! Three answers, not two:
//!
//! - [`Decision::Allow`] runs the call;
//! - [`Decision::Deny`] answers it as declined, with the reason the model reads;
//! - [`Decision::Defer`] means *nobody has answered and the loop must not guess*. The call is
//!   recorded and the turn stops. Fail-closed: an unanswered gate is never an approval, and it is
//!   no longer a silent denial either.
//!
//! `Defer` is what makes the state durable without a daemon: the process that asked can exit, and
//! any later process can look at the same rows and answer them.

use crate::session::SessionStore;
use crate::Result;

/// Who answered a waiting call, for the `by` column (`#340`).
///
/// `user` is every answer that came through a person — `eclipse approve`, a card, a dashboard
/// button. `judge` is the aux route in `smart` mode. `policy` is reserved for a call a rule
/// settled without either, so the column's vocabulary is fixed before anything writes a third word.
pub const DECIDED_BY_USER: &str = "user";
/// The aux route in `smart` mode (`#340`).
pub const DECIDED_BY_JUDGE: &str = "judge";

/// One call the model made, as the gate sees it: enough to ask, enough to re-run it later.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct Pending {
    /// The model's id for this call, which is also how its result is matched back.
    pub call_id: String,
    pub tool: String,
    /// The one-liner the gate shows a human (`Tool::describe_call`).
    pub summary: String,
    /// The arguments as the call will run: what the model wrote, unless an `on_dispatch` hook
    /// repaired it before the gate saw it. This row — not the transcript — is what a resumed run
    /// replays, so it is what the human is shown and what actually happens.
    pub args: String,
}

impl Pending {
    pub fn new(
        call_id: impl Into<String>,
        tool: impl Into<String>,
        summary: String,
        args: String,
    ) -> Self {
        Self {
            call_id: call_id.into(),
            tool: tool.into(),
            summary,
            args,
        }
    }
}

/// The gate's answer to one call.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Decision {
    Allow,
    /// Declined, with the reason the model reads as the tool result. A denial is information:
    /// "the user declined" without a why teaches the model nothing.
    Deny(String),
    /// Not answered yet. The loop stops rather than deciding on the user's behalf.
    Defer,
}

impl Decision {
    /// How this answer is stored. `Defer` has no row value: a call with no decision *is* deferred,
    /// and storing "deferred" would make "waiting" look like an answer that had arrived.
    pub fn store(&self) -> Option<String> {
        match self {
            Decision::Allow => Some("allow".to_string()),
            Decision::Deny(reason) => Some(format!("deny:{reason}")),
            Decision::Defer => None,
        }
    }

    /// The inverse of [`store`](Self::store), for a row that has a decision column set.
    ///
    /// Fails closed (`#427`). This used to read anything without a `deny:` prefix as Allow, so a
    /// row this build did not write — an older scheme, a higher version's word, a hand-edited
    /// `state.db` — became an approval for a call nobody approved. An unknown answer is a denial
    /// that says what it did not understand; the only way to allow is to say `allow`.
    pub fn parse(stored: &str) -> Self {
        match stored.strip_prefix("deny:") {
            Some(reason) => Decision::Deny(reason.to_string()),
            None if stored == "allow" => Decision::Allow,
            None => Decision::Deny(format!(
                "the stored answer {stored:?} is not one this build understands, so the call was \
                 not run"
            )),
        }
    }
}

/// One line of the append-only log: a call, its answer, and who gave it (`#340`).
///
/// The waiting rows in `approvals` are deleted as soon as the answer reaches the transcript, so
/// this is what a later reader has: "what did the model wave through last week" is a query over
/// these, and it is answerable because nothing removes them.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct Ruling {
    pub at_ms: i64,
    pub call_id: String,
    pub tool: String,
    pub summary: String,
    pub decision: Decision,
    pub by: String,
}

/// One stored row: a call, and the answer if one arrived.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct PendingCall {
    /// The `seq` of the assistant message that carried the call.
    pub seq: i64,
    /// Its position within that message, so two calls can never collide on one row.
    pub ord: usize,
    pub call: Pending,
    pub decision: Option<Decision>,
    pub decided_ms: Option<i64>,
    /// Who answered: `user`, `judge` or `policy` (`#340`). `None` for a row that has no answer
    /// yet, and for one written before the column existed — nobody recorded it, and saying so is
    /// better than guessing a name.
    pub by: Option<String>,
}

impl PendingCall {
    pub fn is_waiting(&self) -> bool {
        self.decision.is_none()
    }
}

/// What a run left behind when it stopped on the gate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Waiting {
    pub session: String,
    /// How many calls are waiting for an answer.
    pub calls: usize,
}

impl Waiting {
    /// The line a human needs: what is waiting and the command that resolves it.
    pub fn hint(&self) -> String {
        format!(
            "{} tool call(s) in {} waiting for an answer; run `eclipse approve {} --all` \
             (or `--index N`, `--deny <reason>`) to resolve them",
            self.calls, self.session, self.session
        )
    }
}

/// Record the calls of one assistant message as pending. An existing row is left alone: the same
/// call re-recorded has the same answer or none, and overwriting it would lose a decision that
/// arrived while the run was stopping.
pub fn record(store: &SessionStore, session: &str, seq: i64, calls: &[Pending]) -> Result<()> {
    store.record_pending(session, seq, calls)
}

/// Record `calls` as pending, starting at `ord` — the position `calls[0]` holds in the assistant
/// message that carried it.
///
/// A caller that records a turn's deferred calls one at a time must pass each call's own position.
/// `ord` is half the row's key, so writing them all at 0 makes the second one collide with the
/// first and `ON CONFLICT DO NOTHING` drops it (#547).
pub fn record_at(
    store: &SessionStore,
    session: &str,
    seq: i64,
    ord: usize,
    calls: &[Pending],
) -> Result<()> {
    store.record_pending_at(session, seq, ord, calls)
}

/// The calls waiting for an answer, oldest first.
pub fn waiting(store: &SessionStore, session: &str) -> Result<Vec<PendingCall>> {
    Ok(store
        .pending_calls(session)?
        .into_iter()
        .filter(PendingCall::is_waiting)
        .collect())
}

/// Answer one waiting call by position, counting from 1 in the order `waiting` prints them.
pub fn answer(
    store: &SessionStore,
    session: &str,
    index: usize,
    decision: &Decision,
) -> Result<()> {
    let waiting = waiting(store, session)?;
    // `--index 0` used to be `saturating_sub(1)` == 0, so it silently answered the *first* call: an
    // operator asking for nothing got the one thing they did not ask for (`#427`). The numbers a
    // person sees in `eclipse approve` start at 1.
    let Some(position) = index.checked_sub(1) else {
        return Err(crate::Error::Session(
            "call numbers start at 1: there is no call 0 to answer".into(),
        ));
    };
    let Some(row) = waiting.get(position) else {
        return Err(crate::Error::Session(format!(
            "there is no waiting call {index} in {session}: {} waiting",
            waiting.len()
        )));
    };
    store.decide_pending(session, row.seq, row.ord, decision, DECIDED_BY_USER)
}

/// Answer every waiting call.
pub fn answer_all(store: &SessionStore, session: &str, decision: &Decision) -> Result<usize> {
    let waiting = waiting(store, session)?;
    for row in &waiting {
        store.decide_pending(session, row.seq, row.ord, decision, DECIDED_BY_USER)?;
    }
    Ok(waiting.len())
}

/// The decision recorded for one call, if any. Used by the resumed run, which must run exactly
/// what was approved and nothing else.
pub fn decision_for(
    store: &SessionStore,
    session: &str,
    call_id: &str,
) -> Result<Option<Decision>> {
    Ok(store
        .pending_calls(session)?
        .into_iter()
        .find(|row| row.call.call_id == call_id)
        .and_then(|row| row.decision))
}

/// The store's answers, asked of the gate that replays a paused turn.
///
/// A resumed call is not asked of the user again: the answer is already in the row. But a call the
/// resumed tool makes *itself* — a subagent's, or one a router re-dispatches — is a new decision
/// with no row, and that one goes to the live gate as usual rather than being waved through by
/// association. `Defer` for a row that has gone missing is the fail-closed answer: the transcript
/// says this call was waiting, so nothing else may stand in for the answer.
pub struct Recorded<'a> {
    store: &'a SessionStore,
    session: &'a str,
    inner: &'a dyn crate::tools::Approver,
}

impl<'a> Recorded<'a> {
    pub fn new(
        store: &'a SessionStore,
        session: &'a str,
        inner: &'a dyn crate::tools::Approver,
    ) -> Self {
        Self {
            store,
            session,
            inner,
        }
    }
}

#[async_trait::async_trait]
impl crate::tools::Approver for Recorded<'_> {
    async fn decide(&self, call: &Pending) -> Decision {
        match decision_for(self.store, self.session, &call.call_id) {
            Ok(Some(decision)) => decision,
            Ok(None) => self.inner.decide(call).await,
            Err(_) => Decision::Defer,
        }
    }
}

#[cfg(test)]
mod tests;