basis 0.10.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
//! Between-turn model and reasoning switching on one attached `PreparedRun`.
//!
//! This is deliberately a Basis-only public API oracle. It drives a real tool
//! round before switching phases so the synthesis request proves that the
//! session, agent, transcript, and complete request posture survived intact.

use std::sync::{
    Arc, Mutex,
    atomic::{AtomicUsize, Ordering},
};

use basis::{
    AllowAll, CollectingSink, ContentBlock, Effort, Event, ModelInfo, Provider,
    ProviderRequestOptions, ReasoningOptions, ReasoningSummary, RunError, RunProfile, RunSpec,
    Runtime, Workspace, async_trait,
    runtime::{
        ProviderCapabilities, ProviderDescriptor, ProviderError, ProviderEventStream, Request,
        Response, Role, provider_event_stream_from_response,
    },
    tools::{ParallelToolContext, RuntimeToolDescriptor, ToolDefinition, ToolExecutor, ToolResult},
};
use serde_json::json;

const PROVIDER: &str = "attached-switch-provider";
const MODEL_A: &str = "gather-model";
const MODEL_B: &str = "synthesis-model";
const TOOL: &str = "fake_retrieval";
const TOOL_CALL: &str = "gather-call";
const TOOL_RESULT: &str = "evidence from the fake retrieval tool";

#[derive(Clone, Default)]
struct Activity {
    listings: Arc<AtomicUsize>,
    requests: Arc<Mutex<Vec<Request<'static>>>>,
    tool_agents: Arc<Mutex<Vec<String>>>,
}

impl Activity {
    fn snapshot(&self) -> ActivitySnapshot {
        ActivitySnapshot {
            listings: self.listings.load(Ordering::SeqCst),
            requests: self.requests.lock().expect("request recorder").len(),
            tools: self.tool_agents.lock().expect("tool recorder").len(),
        }
    }

    fn requests(&self) -> Vec<Request<'static>> {
        self.requests.lock().expect("request recorder").clone()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ActivitySnapshot {
    listings: usize,
    requests: usize,
    tools: usize,
}

struct ScriptedProvider {
    activity: Activity,
}

#[async_trait]
impl Provider for ScriptedProvider {
    fn descriptor(&self) -> ProviderDescriptor {
        ProviderDescriptor::new(PROVIDER)
    }

    fn capabilities(&self) -> ProviderCapabilities {
        ProviderCapabilities {
            supports_model_listing: true,
            supports_streaming: true,
            supports_tool_calls: true,
            ..Default::default()
        }
    }

    async fn list_models(&self) -> Result<Vec<ModelInfo>, ProviderError> {
        self.activity.listings.fetch_add(1, Ordering::SeqCst);
        Ok(vec![model_a(), model_b()])
    }

    async fn stream(&self, request: Request<'_>) -> Result<ProviderEventStream, ProviderError> {
        let model = request.model.to_string();
        let call = {
            let mut requests = self.activity.requests.lock().expect("request recorder");
            requests.push(request.into_owned());
            requests.len()
        };
        let content = match call {
            1 => vec![ContentBlock::ToolUse {
                id: TOOL_CALL.to_string(),
                name: TOOL.to_string(),
                input: json!({"topic": "runtime adoption"}),
            }],
            2 => vec![ContentBlock::text("gather complete")],
            _ => vec![ContentBlock::text("synthesis complete")],
        };

        Ok(provider_event_stream_from_response(Response {
            id: format!("attached-switch-{call}"),
            model,
            role: Role::Assistant,
            content,
            stop_reason: None,
            usage: None,
        }))
    }
}

struct FakeRetrieval {
    activity: Activity,
}

impl ToolDefinition for FakeRetrieval {
    fn descriptor(&self) -> RuntimeToolDescriptor {
        RuntimeToolDescriptor::builder(TOOL)
            .description("returns fixed evidence for the attached-switch oracle")
            .input_schema(json!({
                "type": "object",
                "properties": {"topic": {"type": "string"}},
                "required": ["topic"]
            }))
            .build()
    }
}

#[async_trait]
impl ToolExecutor for FakeRetrieval {
    async fn execute(&self, ctx: ParallelToolContext, _input: serde_json::Value) -> ToolResult {
        self.activity
            .tool_agents
            .lock()
            .expect("tool recorder")
            .push(ctx.agent_id);
        Ok(TOOL_RESULT.to_string())
    }
}

fn model_a() -> ModelInfo {
    let mut model = ModelInfo::new(MODEL_A, PROVIDER).with_context_window(32_768);
    model.display_name = Some("Gather display metadata".to_string());
    model.description = Some("metadata handed to Mentra whole".to_string());
    model
}

fn model_b() -> ModelInfo {
    let mut model = ModelInfo::new(MODEL_B, PROVIDER).with_context_window(262_144);
    model.display_name = Some("Synthesis display metadata".to_string());
    model.description = Some("metadata handed to Mentra whole".to_string());
    model
}

fn low_reasoning() -> ReasoningOptions {
    ReasoningOptions {
        effort: Some(Effort::Low.into()),
        summary: None,
    }
}

fn high_reasoning() -> ReasoningOptions {
    ReasoningOptions {
        effort: Some(Effort::High.into()),
        summary: Some(ReasoningSummary::Detailed),
    }
}

fn gather_options() -> ProviderRequestOptions {
    let mut options = ProviderRequestOptions {
        reasoning: Some(low_reasoning()),
        ..Default::default()
    };
    options.responses.parallel_tool_calls = Some(false);
    options.responses.include = vec!["reasoning.encrypted_content".to_string()];
    options.responses.service_tier = Some("priority".to_string());
    options.responses.prompt_cache_key = Some("attached-switch-cache".to_string());
    options.anthropic.disable_parallel_tool_use = Some(true);
    options.gemini.thoughts = Some(true);
    options.session.sticky_turn_state = Some("attached-switch-turn".to_string());
    options.session.turn_metadata = Some("attached-switch-metadata".to_string());
    options.session.prefer_connection_reuse = Some(true);
    options
}

async fn workspace(path: &std::path::Path, activity: Activity) -> Workspace {
    Workspace::builder(path)
        .without_discovery()
        .fresh_only()
        .with_runtime_builder(
            Runtime::builder()
                .with_provider_instance(ScriptedProvider {
                    activity: activity.clone(),
                })
                .with_tool(FakeRetrieval { activity })
                .with_ephemeral_history(),
        )
        .with_resolved_model(model_a())
        .open()
        .await
        .expect("the private discovery-free workspace opens")
}

#[tokio::test]
async fn one_attached_run_switches_full_model_and_reasoning_without_losing_gather_context() {
    let activity = Activity::default();
    let dir = tempfile::tempdir().expect("workspace");
    let workspace = workspace(dir.path(), activity.clone()).await;
    let options = gather_options();
    let mut run = workspace
        .prepare(
            RunSpec::new("gather evidence")
                .with_profile(RunProfile::new().with_provider_request_options(options.clone())),
        )
        .expect("the attached run mints without provider activity");
    let session_id = run.session_id();
    let agent_id = run.agent_id().to_string();

    let gather = run
        .execute(CollectingSink::default())
        .await
        .expect("the gather tool exchange completes");
    assert_eq!(gather.model, MODEL_A);
    assert_eq!(gather.session_id, session_id);
    assert_eq!(run.context_window(), Some(32_768));
    assert_eq!(run.reasoning(), Some(&low_reasoning()));
    let gather_history = run.history().to_vec();
    assert!(gather_history.iter().any(|message| {
        message.content.iter().any(|block| {
            matches!(
                block,
                ContentBlock::ToolUse { id, name, .. } if id == TOOL_CALL && name == TOOL
            )
        })
    }));
    assert!(gather_history.iter().any(|message| {
        message.content.iter().any(|block| {
            matches!(
                block,
                ContentBlock::ToolResult {
                    tool_use_id,
                    content,
                    is_error: false,
                } if tool_use_id == TOOL_CALL && content == TOOL_RESULT
            )
        })
    }));
    assert_eq!(
        activity
            .tool_agents
            .lock()
            .expect("tool recorder")
            .as_slice(),
        [agent_id.as_str()]
    );
    let after_gather = activity.snapshot();
    assert_eq!(
        after_gather,
        ActivitySnapshot {
            listings: 0,
            requests: 2,
            tools: 1,
        }
    );

    run.set_resolved_model(model_b())
        .expect("the exact-provider model switch persists");
    run.set_reasoning(Some(high_reasoning()))
        .expect("the complete reasoning switch persists");

    assert_eq!(
        activity.snapshot(),
        after_gather,
        "switching itself must not list, request, or run a tool"
    );
    assert_eq!(run.session_id(), session_id);
    assert_eq!(run.agent_id(), agent_id);
    assert_eq!(run.session().metadata().model, MODEL_B);
    assert_eq!(run.context().provider, PROVIDER);
    assert_eq!(run.context().model, MODEL_B);
    assert_eq!(run.context_window(), Some(262_144));
    assert_eq!(run.reasoning(), Some(&high_reasoning()));
    assert!(matches!(
        run.header(),
        Event::RunStarted {
            ref model,
            ref provider,
            ..
        } if model == MODEL_B && provider == PROVIDER
    ));

    let synthesis = run
        .send(
            "synthesize from the gathered evidence",
            CollectingSink::default(),
            AllowAll,
        )
        .await
        .expect("synthesis completes on the same attached run");
    assert_eq!(synthesis.session_id, session_id);
    assert_eq!(synthesis.model, MODEL_B);
    assert_eq!(synthesis.provider, PROVIDER);
    assert_eq!(gather.model, MODEL_A, "the earlier report stays historical");
    assert_eq!(run.agent_id(), agent_id);

    let requests = activity.requests();
    assert_eq!(requests.len(), 3);
    assert_eq!(requests[0].model, MODEL_A);
    assert_eq!(requests[1].model, MODEL_A);
    assert_eq!(requests[0].provider_request_options, options);
    assert_eq!(requests[1].provider_request_options, options);
    let synthesis_request = &requests[2];
    assert_eq!(synthesis_request.model, MODEL_B);
    assert!(
        synthesis_request
            .messages
            .as_ref()
            .starts_with(&gather_history),
        "the model-B request must replay the exact committed gather transcript"
    );
    let mut expected_options = options;
    expected_options.reasoning = Some(high_reasoning());
    assert_eq!(synthesis_request.provider_request_options, expected_options);
}

#[tokio::test]
async fn legacy_switch_wrappers_are_lossy_only_for_model_metadata_and_reasoning_summary() {
    const WRAPPER_MODEL: &str = "wrapper-model";

    let activity = Activity::default();
    let dir = tempfile::tempdir().expect("workspace");
    let workspace = workspace(dir.path(), activity.clone()).await;
    let mut options = gather_options();
    options.reasoning = Some(ReasoningOptions {
        effort: Some(Effort::Low.into()),
        summary: Some(ReasoningSummary::Concise),
    });
    let mut run = workspace
        .prepare(
            RunSpec::new("wrapper gather")
                .with_profile(RunProfile::new().with_provider_request_options(options.clone())),
        )
        .expect("the wrapper run mints without provider activity");
    let before = activity.snapshot();

    run.set_model(WRAPPER_MODEL)
        .expect("the legacy model-id wrapper switches on the same provider");
    run.set_effort(Some(Effort::Medium))
        .expect("the legacy effort wrapper switches reasoning");

    assert_eq!(
        activity.snapshot(),
        before,
        "legacy wrappers must not list, request, or run a tool"
    );
    assert_eq!(
        before,
        ActivitySnapshot {
            listings: 0,
            requests: 0,
            tools: 0,
        }
    );
    assert_eq!(run.context_window(), None, "an id carries no model window");
    let expected_reasoning = ReasoningOptions {
        effort: Some(Effort::Medium.into()),
        summary: None,
    };
    assert_eq!(run.reasoning(), Some(&expected_reasoning));
    assert_eq!(run.effort(), Some(Effort::Medium));
    assert!(matches!(
        run.header(),
        Event::RunStarted {
            ref model,
            ref provider,
            ..
        } if model == WRAPPER_MODEL && provider == PROVIDER
    ));

    let report = run
        .execute(CollectingSink::default())
        .await
        .expect("the wrapper-model gather completes");
    assert_eq!(report.model, WRAPPER_MODEL);
    assert_eq!(report.provider, PROVIDER);
    let mut expected_options = options;
    expected_options.reasoning = Some(expected_reasoning);
    let requests = activity.requests();
    assert_eq!(requests.len(), 2);
    for request in requests {
        assert_eq!(request.model, WRAPPER_MODEL);
        assert_eq!(request.provider_request_options, expected_options);
    }
}

#[tokio::test]
async fn a_foreign_provider_switch_fails_before_touching_the_attached_run() {
    let activity = Activity::default();
    let dir = tempfile::tempdir().expect("workspace");
    let workspace = workspace(dir.path(), activity.clone()).await;
    let options = gather_options();
    let mut run = workspace
        .prepare(
            RunSpec::new("not sent")
                .with_profile(RunProfile::new().with_provider_request_options(options)),
        )
        .expect("the attached run mints without provider activity");
    let session_id = run.session_id();
    let agent_id = run.agent_id().to_string();
    let history = run.history().to_vec();
    let reasoning = run.reasoning().cloned();
    let before = activity.snapshot();

    let error = run
        .set_resolved_model(
            ModelInfo::new(MODEL_B, "attached-switch-provider-lookalike")
                .with_context_window(999_999),
        )
        .expect_err("provider identity is exact, not inferred from the model id");

    assert!(matches!(
        error,
        RunError::ResolvedModelProviderMismatch {
            ref model,
            ref model_provider,
            ref runtime_provider,
        } if model == MODEL_B
            && model_provider == "attached-switch-provider-lookalike"
            && runtime_provider == PROVIDER
    ));
    assert_eq!(activity.snapshot(), before);
    assert_eq!(
        before,
        ActivitySnapshot {
            listings: 0,
            requests: 0,
            tools: 0,
        }
    );
    assert_eq!(run.session_id(), session_id);
    assert_eq!(run.agent_id(), agent_id);
    assert_eq!(run.session().metadata().model, MODEL_A);
    assert_eq!(run.context().model, MODEL_A);
    assert_eq!(run.context().provider, PROVIDER);
    assert_eq!(run.context_window(), Some(32_768));
    assert_eq!(run.reasoning().cloned(), reasoning);
    assert_eq!(run.history(), history.as_slice());
    assert!(matches!(
        run.header(),
        Event::RunStarted {
            ref model,
            ref provider,
            ..
        } if model == MODEL_A && provider == PROVIDER
    ));
}