basis 0.2.0

The basis SDK: workspace discovery, run lifecycle, one event stream, and the two seams. No protocol, no transport, no TTY.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Asking before the agent does something consequential.
//!
//! Two pieces, and only two. [`ApprovalGate`] is the tool authorizer basis
//! installs on every runtime; it answers one question — *is this call worth
//! asking about* — and puts every call where the answer is yes to whoever is
//! answering. [`Approver`] is whoever that is, and it is the only thing that
//! decides.
//!
//! There was a third piece until ADR-0010: an `ApprovalPolicy` enum the core
//! interpreted, whose three values were three trait impls in disguise. Two of
//! them ship here — [`AllowAll`] and [`DenyAll`] — and the third, asking a
//! person, lives where the terminal is: `basis-acp` supplies an approver that
//! asks the client, and the binary one that asks at a TTY (ADR-0011). What the
//! enum could never express, the trait can: allow edits but deny the network,
//! ask over Slack with a timeout, escalate after the third refusal.
//!
//! Nothing installs an approver by default, and that is deliberate: with no
//! approver the run gets [`AllowAll`], which is what a headless run needs.
//! Anything stricter is one argument to
//! [`run_with_approver`](crate::run::run_with_approver).

use std::time::Duration;

use async_trait::async_trait;
use mentra::{
    error::RuntimeError,
    tool::{
        ToolAuthorizationDecision, ToolAuthorizationRequest, ToolAuthorizer, ToolSideEffectLevel,
    },
};
use serde_json::Value;

/// What the agent wants to do, as put to an [`Approver`].
#[derive(Debug, Clone, PartialEq)]
pub struct ApprovalRequest {
    pub request_id: String,
    pub tool_call_id: String,
    pub tool_name: String,
    /// Why approval is being asked for.
    pub description: String,
    /// The tool's input, parsed when it is JSON.
    pub input: Value,
}

/// What an [`Approver`] decided.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ApprovalDecision {
    Allow,
    /// The default: when in doubt, do not.
    #[default]
    Deny,
    /// Allow, and stop asking about this tool for the rest of the session.
    AllowForSession,
    /// Deny, and stop asking about this tool for the rest of the session.
    DenyForSession,
}

/// How an [`Approver`] answered: the decision, and — when it refused — why.
///
/// The reason is not decoration. A denial reaches the model as that tool
/// call's result, so the wording is the only thing telling it what to do
/// next: a model told merely that something was denied tries the write
/// again, and one told this run does not allow writes stops and reports.
/// An answer that leaves it unset still denies; the model just reads
/// mentra's standing "denied by session approver" instead.
///
/// Allowing needs no reason, because an allowed call explains itself by
/// happening.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ApprovalAnswer {
    pub decision: ApprovalDecision,
    pub reason: Option<String>,
}

impl ApprovalAnswer {
    /// An answer that says only what it decided.
    pub fn new(decision: ApprovalDecision) -> Self {
        Self {
            decision,
            reason: None,
        }
    }

    /// The same answer, carrying the words the model will read.
    pub fn because(self, reason: impl Into<String>) -> Self {
        Self {
            reason: Some(reason.into()),
            ..self
        }
    }
}

impl From<ApprovalDecision> for ApprovalAnswer {
    fn from(decision: ApprovalDecision) -> Self {
        Self::new(decision)
    }
}

/// Answers approval requests. The seam a host plugs its own judgment into.
///
/// Called from the event-forwarding task while the turn is blocked inside
/// mentra waiting, so an implementation must answer rather than defer to
/// something that only happens after the run.
///
/// Async because answering genuinely takes time and the caller is an async
/// task: an ACP approver awaits a round trip to the client, and a terminal one
/// waits on a person. A synchronous signature would force both to block a
/// runtime worker thread — which tokio rejects outright for the ACP case. The
/// attribute to spell an impl with is re-exported at the crate root —
/// [`async_trait`](crate::async_trait) — so it costs no manifest line of the
/// host's own.
///
/// # Fail closed
///
/// **An approver that cannot answer denies.** No terminal to ask at, an answer
/// that never came, a channel whose other end is gone: none of those is
/// consent, and the only calls that reach an approver are the ones that change
/// something outside this process.
///
/// The worked example is the binary's `TerminalApprover`. Asked when stdin is
/// not a terminal — an unattended `basis spawn --approve prompt`, a cron job — it
/// denies without printing a question nobody would read, so the run fails
/// visibly instead of quietly granting whatever came up. `basis-acp`'s client
/// approver applies the same rule to a failed round trip, a cancelled request,
/// an answer it cannot parse, and its own thirty-minute timeout.
///
/// Each of those denials should say which one it was, on the
/// [`reason`](ApprovalAnswer::reason) of its answer. Failing closed silently
/// leaves the model to guess, and it guesses that retrying will work.
///
/// [`ApprovalDecision`]'s own default is [`Deny`](ApprovalDecision::Deny) for
/// the same reason, and so is mentra's when an authorizer times out: silence is
/// never a yes.
#[async_trait]
pub trait Approver: Send + 'static {
    async fn approve(&mut self, request: &ApprovalRequest) -> ApprovalAnswer;
}

/// Forwards to the approver inside.
///
/// Lets a caller hold an approver it chose at runtime — one of several, or one
/// a feature flag picked — and still pass it to anything taking
/// `impl Approver`. The binary is exactly that caller: `--approve` names one of
/// three, and without this each arm would have to duplicate the whole run.
#[async_trait]
impl<A: Approver + ?Sized> Approver for Box<A> {
    async fn approve(&mut self, request: &ApprovalRequest) -> ApprovalAnswer {
        (**self).approve(request).await
    }
}

/// Approves everything. What a confined or headless run wants, and what a run
/// given no approver of its own gets.
#[derive(Debug, Default, Clone, Copy)]
pub struct AllowAll;

#[async_trait]
impl Approver for AllowAll {
    async fn approve(&mut self, _request: &ApprovalRequest) -> ApprovalAnswer {
        ApprovalDecision::Allow.into()
    }
}

/// Refuses everything, so the agent can inspect a workspace and report on it
/// and cannot touch it. Each refusal reaches the model as a tool error, which
/// is how it learns to stop trying.
#[derive(Debug, Default, Clone, Copy)]
pub struct DenyAll;

#[async_trait]
impl Approver for DenyAll {
    async fn approve(&mut self, request: &ApprovalRequest) -> ApprovalAnswer {
        ApprovalAnswer::new(ApprovalDecision::Deny).because(format!(
            "{} changes state outside this process, which this run does not allow",
            request.tool_name
        ))
    }
}

/// Whether a call changes anything outside this process.
///
/// Read-only calls are never worth asking about — prompting for them trains
/// people to approve without reading, which is worse than not asking.
pub fn is_consequential(level: ToolSideEffectLevel) -> bool {
    !matches!(level, ToolSideEffectLevel::None)
}

/// Puts every consequential call to the [`Approver`], and lets the rest
/// through.
///
/// This is the runtime half of approval, installed as mentra's
/// `ToolAuthorizer`. It carries no policy: since ADR-0010 there is nothing left
/// for one to say, because the approver decides. What it still owns is the
/// filter — [`is_consequential`] — and the choice to *surface* rather than
/// answer, which is what turns a call into a `PermissionRequested` event and
/// blocks the turn until someone resolves it.
///
/// Installed even by a run that approves everything, and that is the point. An
/// authorizer is fixed when the runtime is built and mentra never hands it
/// back; without one it allows every call unconditionally and no permission
/// request can ever be raised. Surfacing unconditionally is what lets the
/// answer be chosen per turn — or changed mid-session, which is how an ACP
/// client's mode picker works at all.
#[derive(Debug, Default, Clone, Copy)]
pub struct ApprovalGate {
    timeout: Option<Duration>,
}

impl ApprovalGate {
    pub fn new() -> Self {
        Self {
            // No timeout by default: a person reading a diff should not lose
            // the turn to a stopwatch. A host that needs one sets it.
            timeout: None,
        }
    }

    /// Gives up on an unanswered request after `timeout`, denying the call.
    ///
    /// mentra applies this to the whole wait, so it bounds an approver that
    /// never answers as well as one that answers slowly — the fail-closed rule
    /// of [`Approver`], enforced from outside for approvers that forget it.
    pub fn with_timeout(self, timeout: Duration) -> Self {
        Self {
            timeout: Some(timeout),
        }
    }
}

#[async_trait]
impl ToolAuthorizer for ApprovalGate {
    async fn authorize(
        &self,
        request: &ToolAuthorizationRequest,
    ) -> Result<ToolAuthorizationDecision, RuntimeError> {
        if !is_consequential(request.preview.side_effect_level) {
            return Ok(ToolAuthorizationDecision::allow());
        }

        // The reason becomes the description the approver shows, so it says
        // what is being asked rather than that something is.
        Ok(ToolAuthorizationDecision::prompt(format!(
            "{} wants to run and can change state outside this process",
            request.tool_name
        )))
    }

    fn timeout(&self) -> Option<Duration> {
        self.timeout
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mentra::tool::{
        ToolApprovalCategory, ToolAuthorizationOutcome, ToolAuthorizationPreview, ToolCapability,
        ToolDurability, ToolExecutionCategory,
    };
    use serde_json::json;
    use std::path::PathBuf;

    fn request(name: &str, level: ToolSideEffectLevel) -> ToolAuthorizationRequest {
        ToolAuthorizationRequest {
            agent_id: "a1".to_string(),
            agent_name: "test".to_string(),
            model: "m".to_string(),
            history_len: 1,
            tool_call_id: "tc-1".to_string(),
            tool_name: name.to_string(),
            preview: ToolAuthorizationPreview {
                working_directory: PathBuf::from("/repo"),
                capabilities: vec![ToolCapability::FilesystemWrite],
                side_effect_level: level,
                durability: ToolDurability::Ephemeral,
                execution_category: ToolExecutionCategory::default(),
                approval_category: ToolApprovalCategory::default(),
                raw_input: json!({}),
                structured_input: json!({}),
            },
        }
    }

    async fn outcome(level: ToolSideEffectLevel) -> ToolAuthorizationOutcome {
        ApprovalGate::new()
            .authorize(&request("shell", level))
            .await
            .expect("authorization does not error")
            .outcome
    }

    fn approval_request() -> ApprovalRequest {
        ApprovalRequest {
            request_id: "r".to_string(),
            tool_call_id: "t".to_string(),
            tool_name: "shell".to_string(),
            description: "d".to_string(),
            input: json!({}),
        }
    }

    #[test]
    fn only_side_effects_are_consequential() {
        assert!(!is_consequential(ToolSideEffectLevel::None));
        assert!(is_consequential(ToolSideEffectLevel::LocalState));
        assert!(is_consequential(ToolSideEffectLevel::Process));
        assert!(is_consequential(ToolSideEffectLevel::External));
    }

    #[tokio::test]
    async fn a_read_only_call_is_never_worth_asking_about() {
        assert_eq!(
            outcome(ToolSideEffectLevel::None).await,
            ToolAuthorizationOutcome::Allow,
            "prompting for reads trains people to approve without reading"
        );
    }

    #[tokio::test]
    async fn every_other_call_is_put_to_the_approver() {
        for level in [
            ToolSideEffectLevel::LocalState,
            ToolSideEffectLevel::Process,
            ToolSideEffectLevel::External,
        ] {
            assert_eq!(
                outcome(level).await,
                ToolAuthorizationOutcome::Prompt,
                "{level:?} changes something outside this process"
            );
        }
    }

    #[tokio::test]
    async fn the_request_says_which_tool_wants_to_run() {
        // This text is what an approver shows a person, so a request that
        // named nothing would be a prompt nobody can answer.
        let decision = ApprovalGate::new()
            .authorize(&request("files", ToolSideEffectLevel::LocalState))
            .await
            .expect("no error");

        let reason = decision.reason.expect("a prompt must say what it is about");
        assert!(reason.contains("files"), "{reason}");
    }

    #[test]
    fn a_gate_waits_as_long_as_it_takes_unless_told_otherwise() {
        assert_eq!(ApprovalGate::new().timeout(), None);
        assert_eq!(
            ApprovalGate::new()
                .with_timeout(Duration::from_secs(60))
                .timeout(),
            Some(Duration::from_secs(60))
        );
    }

    #[tokio::test]
    async fn the_trivial_approvers_answer_as_named() {
        let request = approval_request();

        assert_eq!(
            AllowAll.approve(&request).await.decision,
            ApprovalDecision::Allow
        );
        assert_eq!(
            DenyAll.approve(&request).await.decision,
            ApprovalDecision::Deny
        );
    }

    #[tokio::test]
    async fn a_blanket_refusal_tells_the_model_why_it_was_refused() {
        // Without this the model reads "denied" and tries the write again;
        // with it, it learns the run itself is the reason and stops.
        let reason = DenyAll
            .approve(&approval_request())
            .await
            .reason
            .expect("a refusal the model can act on must explain itself");

        assert_eq!(
            reason,
            "shell changes state outside this process, which this run does not allow"
        );
    }

    #[tokio::test]
    async fn a_boxed_approver_answers_exactly_as_the_one_inside() {
        // What the binary relies on to choose between three approvers without
        // writing the run out three times.
        let mut chosen: Box<dyn Approver> = Box::new(DenyAll);
        let answer = chosen.approve(&approval_request()).await;

        assert_eq!(answer.decision, ApprovalDecision::Deny);
        assert!(
            answer.reason.is_some(),
            "the reason must survive the indirection too"
        );
    }

    #[test]
    fn an_unanswered_request_is_a_refusal() {
        // The fail-closed rule, in the one place every approver inherits it:
        // whatever a decision defaults to is what silence means.
        assert_eq!(ApprovalDecision::default(), ApprovalDecision::Deny);
        assert_eq!(
            ApprovalAnswer::default(),
            ApprovalAnswer::new(ApprovalDecision::Deny)
        );
    }

    #[test]
    fn a_reason_rides_along_without_changing_the_decision() {
        let answer = ApprovalAnswer::from(ApprovalDecision::DenyForSession).because("no writes");

        assert_eq!(answer.decision, ApprovalDecision::DenyForSession);
        assert_eq!(answer.reason.as_deref(), Some("no writes"));
    }
}