basis 0.11.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! Normalization from mentra's [`SessionEvent`] to basis's [`Event`].
//!
//! The match is deliberately exhaustive with no wildcard arm. When mentra
//! grows an event, basis fails to compile rather than dropping it silently — a
//! new kind of thing happening during a run is exactly what a harness must not
//! hide from its clients.
//!
//! [`SessionEvent`]: mentra::SessionEvent

use mentra::{
    SessionEvent,
    agent::{
        ElidedToolResult as MentraElidedToolResult,
        RequestToolResultElisionPolicy as MentraRequestToolResultElisionPolicy,
        ToolResultContentKind as MentraToolResultContentKind,
        ToolResultElisionAction as MentraToolResultElisionAction,
    },
    session::{
        NoticeSeverity as MentraNoticeSeverity, PermissionOutcome as MentraPermissionOutcome,
        PermissionRuleScope, TaskKind as MentraTaskKind, TaskLifecycleStatus, ToolMutability,
    },
};
use serde_json::Value;

use super::{
    ElidedToolResult, Event, Mutability, NoticeSeverity, PermissionOutcome,
    RequestToolResultElisionPolicy, RuleScope, TaskKind, TaskStatus, ToolResultContentKind,
    ToolResultElisionAction,
};

/// Maps one session event, or `None` when basis's stream already carries the
/// same information.
pub(super) fn from_session_event(event: &SessionEvent) -> Option<Event> {
    let mapped = match event {
        // The stream header already names the session, and it is emitted
        // before the subscription starts, so this would be a duplicate.
        SessionEvent::SessionStarted { .. } => return None,

        SessionEvent::UserMessage { text, image_count } => Event::UserMessage {
            text: text.clone(),
            image_count: *image_count,
        },
        SessionEvent::AssistantTokenDelta { delta, .. } => Event::AssistantDelta {
            text: delta.clone(),
        },
        SessionEvent::AssistantReasoningDelta { delta, .. } => Event::AssistantReasoningDelta {
            text: delta.clone(),
        },
        SessionEvent::AssistantMessageCompleted { text } => {
            Event::AssistantMessage { text: text.clone() }
        }

        SessionEvent::ToolQueued {
            tool_call_id,
            tool_name,
            summary,
            mutability,
            input_json,
        } => Event::ToolQueued {
            tool_call_id: tool_call_id.clone(),
            tool_name: tool_name.clone(),
            summary: summary.clone(),
            mutability: mutability_of(*mutability),
            input: json_or_string(input_json),
        },
        SessionEvent::ToolStarted {
            tool_call_id,
            tool_name,
        } => Event::ToolStarted {
            tool_call_id: tool_call_id.clone(),
            tool_name: tool_name.clone(),
        },
        SessionEvent::ToolProgress {
            tool_call_id,
            tool_name,
            progress,
        } => Event::ToolProgress {
            tool_call_id: tool_call_id.clone(),
            tool_name: tool_name.clone(),
            progress: progress.clone(),
        },
        SessionEvent::ToolCompleted {
            tool_call_id,
            tool_name,
            summary,
            is_error,
        } => Event::ToolCompleted {
            tool_call_id: tool_call_id.clone(),
            tool_name: tool_name.clone(),
            summary: summary.clone(),
            is_error: *is_error,
        },

        SessionEvent::PermissionRequested {
            request_id,
            tool_call_id,
            tool_name,
            description,
            preview,
            // Deliberately not carried onto basis's Event: adding it is a
            // wire-format decision, deferred until a consumer needs it.
            classification: _,
        } => Event::PermissionRequested {
            request_id: request_id.clone(),
            tool_call_id: tool_call_id.clone(),
            tool_name: tool_name.clone(),
            description: description.clone(),
            preview: json_or_string(preview),
        },
        SessionEvent::PermissionResolved {
            request_id,
            tool_call_id,
            tool_name,
            outcome,
            rule_scope,
        } => Event::PermissionResolved {
            request_id: request_id.clone(),
            tool_call_id: tool_call_id.clone(),
            tool_name: tool_name.clone(),
            outcome: outcome_of(*outcome),
            rule_scope: rule_scope.map(scope_of),
        },

        SessionEvent::TaskUpdated {
            task_id,
            kind,
            status,
            title,
            detail,
        } => Event::TaskUpdated {
            task_id: task_id.clone(),
            kind: task_kind_of(*kind),
            status: task_status_of(*status),
            title: title.clone(),
            detail: detail.clone(),
        },

        SessionEvent::CompactionStarted { agent_id } => Event::CompactionStarted {
            agent_id: agent_id.clone(),
        },
        SessionEvent::CompactionCompleted {
            agent_id,
            replaced_items,
            preserved_items,
            resulting_transcript_len,
            extracted_facts_count,
            summary_preview,
        } => Event::CompactionCompleted {
            agent_id: agent_id.clone(),
            replaced_items: *replaced_items,
            preserved_items: *preserved_items,
            transcript_len: *resulting_transcript_len,
            extracted_facts: *extracted_facts_count,
            summary_preview: summary_preview.clone(),
        },
        SessionEvent::RequestToolResultsElided {
            agent_id,
            policy,
            canonical_tool_result_content_bytes,
            projected_tool_result_content_bytes,
            results,
        } => Event::RequestToolResultsElided {
            agent_id: agent_id.clone(),
            policy: elision_policy_of(policy),
            canonical_tool_result_content_bytes: *canonical_tool_result_content_bytes,
            projected_tool_result_content_bytes: *projected_tool_result_content_bytes,
            results: results.iter().map(elided_tool_result_of).collect(),
        },
        SessionEvent::MemoryUpdated {
            agent_id,
            stored_records,
        } => Event::MemoryUpdated {
            agent_id: agent_id.clone(),
            stored_records: *stored_records,
        },

        SessionEvent::UsageReport {
            agent_id,
            input_tokens,
            output_tokens,
            cache_read_tokens,
            cache_creation_tokens,
            reasoning_tokens,
            thoughts_tokens,
        } => Event::Usage {
            agent_id: agent_id.clone(),
            input_tokens: *input_tokens,
            output_tokens: *output_tokens,
            cache_read_tokens: *cache_read_tokens,
            cache_creation_tokens: *cache_creation_tokens,
            reasoning_tokens: *reasoning_tokens,
            thoughts_tokens: *thoughts_tokens,
        },
        SessionEvent::Notice { severity, message }
            if is_refused_memory_write(severity, message) =>
        {
            // The one notice basis drops by decision rather than maps, and
            // dropping it is the decision D2 already made: the file store
            // refuses a long-term-memory write (mentra
            // `runtime/file_store/delegated.rs`), and mentra reports the
            // refusal after every compaction ingests its summary. basis
            // switched mentra's memory engine off — nothing recalls from that
            // store and no tool reaches it — so under SQLite the same write
            // "succeeded" into a table nothing ever read, invisibly. A
            // warning that the unused write now fails is a fact about a
            // decision, not about the run, and its advice (enable a mentra
            // cargo feature) is addressed to a mentra embedder, which a basis
            // operator is not.
            return None;
        }
        SessionEvent::Notice { severity, message } => Event::Notice {
            severity: severity_of(*severity),
            message: message.clone(),
        },
        SessionEvent::RetryAttempt {
            agent_id,
            error_message,
            attempt,
            max_attempts,
            next_delay_ms,
        } => Event::Retry {
            agent_id: agent_id.clone(),
            error: error_message.clone(),
            attempt: *attempt,
            max_attempts: *max_attempts,
            next_delay_ms: *next_delay_ms,
        },
        SessionEvent::Branched {
            entry_id,
            abandoned_entries,
        } => Event::Branched {
            entry_id: entry_id.clone(),
            abandoned_entries: *abandoned_entries,
        },
        SessionEvent::Error {
            message,
            recoverable,
        } => Event::Error {
            message: message.clone(),
            recoverable: *recoverable,
        },
    };

    Some(mapped)
}

/// Mentra carries tool input and permission previews as JSON-encoded strings.
/// A client should not have to parse a string out of a JSON document to get at
/// JSON, so parse here; a value that is not JSON passes through as a string.
fn json_or_string(raw: &str) -> Value {
    serde_json::from_str(raw).unwrap_or_else(|_| Value::String(raw.to_string()))
}

fn mutability_of(value: ToolMutability) -> Mutability {
    match value {
        ToolMutability::ReadOnly => Mutability::ReadOnly,
        ToolMutability::Mutating => Mutability::Mutating,
        ToolMutability::Unknown => Mutability::Unknown,
    }
}

fn outcome_of(value: MentraPermissionOutcome) -> PermissionOutcome {
    match value {
        MentraPermissionOutcome::Allowed => PermissionOutcome::Allowed,
        MentraPermissionOutcome::Denied => PermissionOutcome::Denied,
    }
}

fn scope_of(value: PermissionRuleScope) -> RuleScope {
    match value {
        PermissionRuleScope::Session => RuleScope::Session,
        PermissionRuleScope::Project => RuleScope::Project,
        PermissionRuleScope::Global => RuleScope::Global,
    }
}

fn task_kind_of(value: MentraTaskKind) -> TaskKind {
    match value {
        MentraTaskKind::Subagent => TaskKind::Subagent,
        MentraTaskKind::BackgroundTask => TaskKind::BackgroundTask,
        MentraTaskKind::Teammate => TaskKind::Teammate,
    }
}

fn task_status_of(value: TaskLifecycleStatus) -> TaskStatus {
    match value {
        TaskLifecycleStatus::Spawned => TaskStatus::Spawned,
        TaskLifecycleStatus::Running => TaskStatus::Running,
        TaskLifecycleStatus::Finished => TaskStatus::Finished,
        TaskLifecycleStatus::Failed => TaskStatus::Failed,
    }
}

fn elision_policy_of(
    value: &MentraRequestToolResultElisionPolicy,
) -> RequestToolResultElisionPolicy {
    match value {
        MentraRequestToolResultElisionPolicy::KeepRecent {
            configured_keep_recent_tool_results,
        } => RequestToolResultElisionPolicy::KeepRecent {
            configured_keep_recent_tool_results: *configured_keep_recent_tool_results,
        },
        MentraRequestToolResultElisionPolicy::ByteBudget {
            configured_max_bytes,
            configured_prioritize_recent_results,
            configured_max_preview_bytes,
        } => RequestToolResultElisionPolicy::ByteBudget {
            configured_max_bytes: *configured_max_bytes,
            configured_prioritize_recent_results: *configured_prioritize_recent_results,
            configured_max_preview_bytes: *configured_max_preview_bytes,
        },
    }
}

fn elided_tool_result_of(value: &MentraElidedToolResult) -> ElidedToolResult {
    ElidedToolResult {
        tool_call_id: value.tool_call_id.clone(),
        tool_name: value.tool_name.clone(),
        is_error: value.is_error,
        canonical_content_kind: content_kind_of(value.canonical_content_kind),
        action: elision_action_of(value.action),
        canonical_content_bytes: value.canonical_content_bytes,
        projected_content_bytes: value.projected_content_bytes,
    }
}

fn content_kind_of(value: MentraToolResultContentKind) -> ToolResultContentKind {
    match value {
        MentraToolResultContentKind::Text => ToolResultContentKind::Text,
        MentraToolResultContentKind::Structured => ToolResultContentKind::Structured,
    }
}

fn elision_action_of(value: MentraToolResultElisionAction) -> ToolResultElisionAction {
    match value {
        MentraToolResultElisionAction::Preview => ToolResultElisionAction::Preview,
        MentraToolResultElisionAction::Marker => ToolResultElisionAction::Marker,
        MentraToolResultElisionAction::Omitted => ToolResultElisionAction::Omitted,
    }
}

/// Whether this notice is the file store refusing the memory write basis
/// already decided not to use — the one notice the mapping drops.
///
/// Deliberately narrow on both axes, because a mapping that swallows an event
/// is the one place a harness can hide something from its clients.
///
/// **Severity**: `Warning` only. mentra composes this notice in exactly one
/// place (`SessionHookBridge`, on a failed `MemoryIngestFinished`) and sends
/// it at `Warning`, so anything arriving at another severity did not come
/// from there and is not this. `Info` is the only other severity mentra has;
/// if a future one carries this text, it reaches the stream.
///
/// **Text**: the whole of what upstream composes around the store error —
/// `RuntimeError::Store`'s own `runtime store error: ` prefix followed by the
/// file store's sentence — rather than a loose phrase from the middle of it.
/// A message merely *mentioning* long-term memory, or reporting a different
/// failure that happens to quote this one, keeps its place on the stream.
/// Matched as text because mentra gives the notice no structure to match on
/// (upstream candidate); if the wording moves this fails open and the warning
/// reappears, which is visible rather than dangerous.
fn is_refused_memory_write(severity: &MentraNoticeSeverity, message: &str) -> bool {
    const REFUSAL: &str = "runtime store error: FileRuntimeStore does not persist long-term memory";

    matches!(severity, MentraNoticeSeverity::Warning) && message.contains(REFUSAL)
}

fn severity_of(value: MentraNoticeSeverity) -> NoticeSeverity {
    match value {
        MentraNoticeSeverity::Info => NoticeSeverity::Info,
        MentraNoticeSeverity::Warning => NoticeSeverity::Warning,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn session_started_is_already_covered_by_the_header() {
        let event = SessionEvent::SessionStarted {
            session_id: mentra::SessionId::new(),
        };

        assert_eq!(from_session_event(&event), None);
    }

    #[test]
    fn the_refused_memory_write_is_a_decision_not_a_run_fact() {
        // The file store refuses long-term-memory writes and mentra reports
        // it after every compaction's summary ingest. basis switched that
        // engine off (D2), so the warning describes a write nothing would
        // ever have read — dropped by decision, see the mapping arm.
        let refused = SessionEvent::Notice {
            severity: MentraNoticeSeverity::Warning,
            message: refused_memory_write(),
        };

        assert_eq!(from_session_event(&refused), None);
    }

    /// Exactly what mentra composes for this notice: `SessionHookBridge`
    /// wraps the agent id around the failed ingest's error, and that error is
    /// `RuntimeError::Store`'s Display around the file store's own sentence.
    fn refused_memory_write() -> String {
        "agent 'a-1': runtime store error: FileRuntimeStore does not persist long-term memory; \
         enable mentra's `store-sqlite` feature and use SqliteRuntimeStore or HybridRuntimeStore \
         for durable memory"
            .to_string()
    }

    #[test]
    fn only_a_warning_carrying_that_exact_refusal_is_dropped() {
        // A mapping that swallows an event is the one place a harness can
        // hide something from its clients, so the drop is narrow on both axes
        // and each is pinned here. `Info` stands in for "any severity but the
        // one upstream sends this at" — mentra's enum has no third.
        let elsewhere = SessionEvent::Notice {
            severity: MentraNoticeSeverity::Info,
            message: refused_memory_write(),
        };
        assert_eq!(
            from_session_event(&elsewhere),
            Some(Event::Notice {
                severity: NoticeSeverity::Info,
                message: refused_memory_write(),
            }),
            "the same text at a severity upstream never sends it at did not come from there"
        );

        // A different memory failure that merely mentions the same subject —
        // and any other notice at all — keeps its place on the stream.
        for message in [
            "agent 'a-1': runtime store error: could not save the memory cursor",
            "agent 'a-1': long-term memory is unavailable here",
            "something else worth hearing",
        ] {
            let ordinary = SessionEvent::Notice {
                severity: MentraNoticeSeverity::Warning,
                message: message.to_string(),
            };
            assert_eq!(
                from_session_event(&ordinary),
                Some(Event::Notice {
                    severity: NoticeSeverity::Warning,
                    message: message.to_string(),
                }),
                "{message}"
            );
        }
    }

    #[test]
    fn token_deltas_carry_only_the_delta() {
        // `full_text` is the accumulated message; re-sending it on every token
        // would make the stream quadratic in the response length.
        let event = SessionEvent::AssistantTokenDelta {
            delta: "lo".to_string(),
            full_text: "hello".to_string(),
        };

        assert_eq!(
            from_session_event(&event),
            Some(Event::AssistantDelta {
                text: "lo".to_string()
            })
        );
    }

    #[test]
    fn byte_budget_elision_maps_every_public_fact_without_a_body() {
        let event = SessionEvent::RequestToolResultsElided {
            agent_id: "agent-1".to_string(),
            policy: MentraRequestToolResultElisionPolicy::ByteBudget {
                configured_max_bytes: 4_096,
                configured_prioritize_recent_results: 2,
                configured_max_preview_bytes: 512,
            },
            canonical_tool_result_content_bytes: 9_000,
            projected_tool_result_content_bytes: 4_000,
            results: vec![MentraElidedToolResult {
                tool_call_id: "call-1".to_string(),
                tool_name: Some("grep".to_string()),
                is_error: false,
                canonical_content_kind: MentraToolResultContentKind::Text,
                action: MentraToolResultElisionAction::Preview,
                canonical_content_bytes: 8_000,
                projected_content_bytes: 3_000,
            }],
        };

        assert_eq!(
            from_session_event(&event),
            Some(Event::RequestToolResultsElided {
                agent_id: "agent-1".to_string(),
                policy: RequestToolResultElisionPolicy::ByteBudget {
                    configured_max_bytes: 4_096,
                    configured_prioritize_recent_results: 2,
                    configured_max_preview_bytes: 512,
                },
                canonical_tool_result_content_bytes: 9_000,
                projected_tool_result_content_bytes: 4_000,
                results: vec![ElidedToolResult {
                    tool_call_id: "call-1".to_string(),
                    tool_name: Some("grep".to_string()),
                    is_error: false,
                    canonical_content_kind: ToolResultContentKind::Text,
                    action: ToolResultElisionAction::Preview,
                    canonical_content_bytes: 8_000,
                    projected_content_bytes: 3_000,
                }],
            })
        );
    }

    #[test]
    fn recent_count_elision_keeps_omitted_structured_result_metadata() {
        let event = SessionEvent::RequestToolResultsElided {
            agent_id: "agent-2".to_string(),
            policy: MentraRequestToolResultElisionPolicy::KeepRecent {
                configured_keep_recent_tool_results: 3,
            },
            canonical_tool_result_content_bytes: 1_024,
            projected_tool_result_content_bytes: 24,
            results: vec![MentraElidedToolResult {
                tool_call_id: "call-2".to_string(),
                tool_name: None,
                is_error: true,
                canonical_content_kind: MentraToolResultContentKind::Structured,
                action: MentraToolResultElisionAction::Omitted,
                canonical_content_bytes: 1_024,
                projected_content_bytes: 0,
            }],
        };

        let Some(Event::RequestToolResultsElided {
            policy, results, ..
        }) = from_session_event(&event)
        else {
            panic!("expected request_tool_results_elided");
        };
        assert_eq!(
            policy,
            RequestToolResultElisionPolicy::KeepRecent {
                configured_keep_recent_tool_results: 3,
            }
        );
        assert_eq!(
            results[0].canonical_content_kind,
            ToolResultContentKind::Structured
        );
        assert_eq!(results[0].action, ToolResultElisionAction::Omitted);
        assert!(results[0].is_error);
    }

    #[test]
    fn tool_input_is_parsed_into_real_json() {
        let event = SessionEvent::ToolQueued {
            tool_call_id: "c1".to_string(),
            tool_name: "shell".to_string(),
            summary: "run ls".to_string(),
            mutability: ToolMutability::ReadOnly,
            input_json: r#"{"command":"ls"}"#.to_string(),
        };

        let Some(Event::ToolQueued { input, .. }) = from_session_event(&event) else {
            panic!("expected a tool_queued event");
        };
        assert_eq!(input["command"], "ls");
    }

    #[test]
    fn unparseable_tool_input_survives_as_a_string() {
        let event = SessionEvent::ToolQueued {
            tool_call_id: "c1".to_string(),
            tool_name: "shell".to_string(),
            summary: String::new(),
            mutability: ToolMutability::Unknown,
            input_json: "not json {".to_string(),
        };

        let Some(Event::ToolQueued { input, .. }) = from_session_event(&event) else {
            panic!("expected a tool_queued event");
        };
        assert_eq!(input, Value::String("not json {".to_string()));
    }

    #[test]
    fn permission_resolution_keeps_the_remembered_scope() {
        let event = SessionEvent::PermissionResolved {
            request_id: "r1".to_string(),
            tool_call_id: "c1".to_string(),
            tool_name: "shell".to_string(),
            outcome: MentraPermissionOutcome::Allowed,
            rule_scope: Some(PermissionRuleScope::Project),
        };

        let Some(Event::PermissionResolved {
            outcome,
            rule_scope,
            ..
        }) = from_session_event(&event)
        else {
            panic!("expected a permission_resolved event");
        };
        assert_eq!(outcome, PermissionOutcome::Allowed);
        assert_eq!(rule_scope, Some(RuleScope::Project));
    }

    #[test]
    fn errors_keep_their_recoverability() {
        let event = SessionEvent::Error {
            message: "rate limited".to_string(),
            recoverable: true,
        };

        assert_eq!(
            from_session_event(&event),
            Some(Event::Error {
                message: "rate limited".to_string(),
                recoverable: true,
            })
        );
    }
}