basis 0.8.1

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
//! Conversation: more than one turn on one session.
//!
//! Until the session survived a turn, `execute` consumed it and every run was
//! a single prompt — mentra's `resume_session` was unreachable and there was no
//! way to say a second thing. These tests pin the property that unlocked:
//! the model sees the whole conversation, because the session was never thrown
//! away.
//!
//! The interesting assertion is not that a second call returns something. It is
//! that the *provider request* for turn two contains turn one — checked against
//! `MockRuntime::recorded_requests`, so a regression that quietly starts a fresh
//! conversation fails here rather than looking fine.

use basis::{AllowAll, CollectingSink, Event, RunOutcome, TurnOptions, run::prepare_with_session};
use mentra::{
    Role, RuntimePolicy,
    test::{MockRuntime, MockToolCall},
};

fn workspace() -> tempfile::TempDir {
    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::write(dir.path().join("AGENTS.md"), "house rules").expect("write AGENTS.md");
    dir
}

/// Pinned to the workspace, with the parent walk and global file off so an
/// `AGENTS.md` above the temp dir cannot leak in.
fn context() -> basis::ContextConfig {
    basis::ContextConfig {
        file_name: "AGENTS.md".to_string(),
        global_dir: None,
        walk_parents: false,
    }
}

/// A runtime that answers each turn with the next scripted reply.
fn mock(replies: &[&str]) -> MockRuntime {
    let mut builder = MockRuntime::builder()
        .model("mock-model", "openai")
        .with_policy(RuntimePolicy::permissive());
    for reply in replies {
        builder = builder.text(*reply);
    }
    builder.build().expect("mock runtime builds")
}

/// Every user message the provider was sent on the given request, in order.
async fn user_messages(mock: &MockRuntime, request: usize) -> Vec<String> {
    mock.recorded_requests()
        .await
        .get(request)
        .expect("the request was made")
        .messages
        .iter()
        .filter(|message| message.role == Role::User)
        .map(|message| message.text())
        .collect()
}

#[tokio::test]
async fn a_second_turn_sees_the_first() {
    let workspace = workspace();
    let mock = mock(&["Nice to meet you.", "You said hello."]);
    let session = mock
        .runtime()
        .create_session("test", mock.model())
        .expect("session");

    let mut prepared = prepare_with_session(
        session,
        workspace.path(),
        "hello",
        &context(),
        "openai",
        "mock-model",
    )
    .expect("prepared");

    let first = prepared
        .execute(CollectingSink::new())
        .await
        .expect("the first turn completes");
    assert_eq!(first.final_message.as_deref(), Some("Nice to meet you."));

    let second = prepared
        .send("what did I say?", CollectingSink::new(), AllowAll)
        .await
        .expect("the second turn completes");
    assert_eq!(second.final_message.as_deref(), Some("You said hello."));

    // The property that matters: turn two carried turn one to the model.
    // Asserted as a prefix rather than an exact list because mentra also
    // injects its own recalled-memory block — that is mentra's business, and
    // pinning it here would make this test fail on an unrelated change.
    let sent = user_messages(&mock, 1).await;
    assert!(
        sent.starts_with(&["hello".to_string(), "what did I say?".to_string()]),
        "the second turn must send the whole conversation, not just its own prompt: {sent:?}"
    );
}

#[tokio::test]
async fn each_turn_gets_its_own_bookends() {
    let workspace = workspace();
    let mock = mock(&["one", "two"]);
    let session = mock
        .runtime()
        .create_session("test", mock.model())
        .expect("session");

    let mut prepared = prepare_with_session(
        session,
        workspace.path(),
        "first",
        &context(),
        "openai",
        "mock-model",
    )
    .expect("prepared");

    let first = prepared
        .execute(CollectingSink::new())
        .await
        .expect("first turn");
    let second = prepared
        .send("second", CollectingSink::new(), AllowAll)
        .await
        .expect("second turn");

    for (label, report) in [("first", &first), ("second", &second)] {
        let events = report.sink.events();
        assert!(
            matches!(events.first(), Some(Event::RunStarted { .. })),
            "the {label} turn must open with a header"
        );
        assert!(
            matches!(
                events.last(),
                Some(Event::RunFinished {
                    outcome: RunOutcome::Ok,
                    ..
                })
            ),
            "the {label} turn must close with an outcome"
        );
    }

    // A turn is a complete stream, so a client reading the second one never
    // sees the first one's events replayed into it.
    assert!(
        second
            .sink
            .events()
            .iter()
            .all(|event| !matches!(event, Event::AssistantMessage { text } if text == "one")),
        "the second turn's stream must not repeat the first turn's message"
    );
}

#[tokio::test]
async fn the_session_survives_and_reports_its_history() {
    let workspace = workspace();
    let mock = mock(&["ack", "ack again"]);
    let session = mock
        .runtime()
        .create_session("test", mock.model())
        .expect("session");

    let mut prepared = prepare_with_session(
        session,
        workspace.path(),
        "first",
        &context(),
        "openai",
        "mock-model",
    )
    .expect("prepared");

    assert!(
        prepared.history().is_empty(),
        "nothing is committed before a turn runs"
    );
    let agent_id = prepared.agent_id().to_string();

    prepared
        .execute(CollectingSink::new())
        .await
        .expect("first turn");
    prepared
        .send("second", CollectingSink::new(), AllowAll)
        .await
        .expect("second turn");

    let history = prepared.history();
    let said: Vec<String> = history
        .iter()
        .filter(|message| message.role == Role::User)
        .map(|message| message.text())
        .collect();
    assert_eq!(said, vec!["first".to_string(), "second".to_string()]);

    assert_eq!(
        prepared.agent_id(),
        agent_id,
        "the agent id must be stable across turns — it is what resume takes"
    );
}

/// `answered_turns` is the fact a crash-recovering host takes a watermark of:
/// two turns each add one assistant message, never one of the user's own.
#[tokio::test]
async fn answered_turns_counts_the_assistant_messages_only() {
    let workspace = workspace();
    let mock = mock(&["one", "two"]);
    let session = mock
        .runtime()
        .create_session("test", mock.model())
        .expect("session");

    let mut prepared = prepare_with_session(
        session,
        workspace.path(),
        "first",
        &context(),
        "openai",
        "mock-model",
    )
    .expect("prepared");

    assert_eq!(
        prepared.answered_turns(),
        0,
        "nothing is committed before a turn runs"
    );

    prepared
        .execute(CollectingSink::new())
        .await
        .expect("first turn");
    assert_eq!(prepared.answered_turns(), 1);

    prepared
        .send("second", CollectingSink::new(), AllowAll)
        .await
        .expect("second turn");
    assert_eq!(
        prepared.answered_turns(),
        2,
        "one count per turn, not per message: each turn also committed a user message"
    );
}

#[tokio::test]
async fn an_empty_follow_up_prompt_is_refused() {
    let workspace = workspace();
    let mock = mock(&["ok"]);
    let session = mock
        .runtime()
        .create_session("test", mock.model())
        .expect("session");

    let mut prepared = prepare_with_session(
        session,
        workspace.path(),
        "first",
        &context(),
        "openai",
        "mock-model",
    )
    .expect("prepared");

    prepared
        .execute(CollectingSink::new())
        .await
        .expect("first turn");

    let error = prepared
        .send("  \n\t ", CollectingSink::new(), AllowAll)
        .await
        .expect_err("an empty follow-up is rejected");

    assert!(matches!(error, basis::RunError::EmptyPrompt));
}

#[tokio::test]
async fn a_failed_turn_does_not_end_the_conversation() {
    let workspace = workspace();
    // The first turn fails; the session must still take a second prompt.
    let mock = MockRuntime::builder()
        .model("mock-model", "openai")
        .with_policy(RuntimePolicy::permissive())
        .failure(mentra::ProviderError::UnsupportedCapability(
            "scripted failure".to_string(),
        ))
        .text("recovered")
        .build()
        .expect("mock runtime builds");
    let session = mock
        .runtime()
        .create_session("test", mock.model())
        .expect("session");

    let mut prepared = prepare_with_session(
        session,
        workspace.path(),
        "first",
        &context(),
        "openai",
        "mock-model",
    )
    .expect("prepared");

    let failed = prepared
        .execute(CollectingSink::new())
        .await
        .expect("the run reports rather than erroring");
    assert!(!failed.succeeded());

    let recovered = prepared
        .send("try again", CollectingSink::new(), AllowAll)
        .await
        .expect("the session still takes a turn after a failure");

    assert!(
        recovered.succeeded(),
        "a failed turn must not poison the session"
    );
    assert_eq!(recovered.final_message.as_deref(), Some("recovered"));
}

#[tokio::test]
async fn a_cancelled_turn_ends_rather_than_running() {
    let workspace = workspace();
    let mock = mock(&["never reached"]);
    let session = mock
        .runtime()
        .create_session("test", mock.model())
        .expect("session");

    let mut prepared = prepare_with_session(
        session,
        workspace.path(),
        "go",
        &context(),
        "openai",
        "mock-model",
    )
    .expect("prepared");

    // Tripped before the turn starts, so the outcome does not depend on
    // winning a race with the provider. This is the shape a protocol server's
    // stop button uses; only the timing differs.
    let (options, cancel) = TurnOptions::cancellable();
    cancel.cancel();

    let report = prepared
        .send_with_options("go", CollectingSink::new(), AllowAll, options)
        .await
        .expect("a cancelled turn reports rather than erroring");

    assert!(
        matches!(report.outcome, RunOutcome::Error { .. }),
        "a cancelled turn must not report success"
    );
    assert!(
        matches!(report.sink.events().last(), Some(Event::RunFinished { .. })),
        "a cancelled turn still closes its stream"
    );
}

#[tokio::test]
async fn tool_calls_from_an_earlier_turn_stay_in_the_conversation() {
    let workspace = workspace();
    let mock = MockRuntime::builder()
        .model("mock-model", "openai")
        .with_policy(RuntimePolicy::permissive())
        .tool_calls(vec![MockToolCall::new(
            "files",
            serde_json::json!({"operations": [{"op": "list", "path": "."}]}),
        )])
        .text("listed them")
        .text("as I said, I listed them")
        .build()
        .expect("mock runtime builds");
    let session = mock
        .runtime()
        .create_session_with_config(
            "test",
            mock.model(),
            mentra::agent::AgentConfig {
                workspace: mentra::agent::WorkspaceConfig {
                    base_dir: workspace.path().to_path_buf(),
                    ..Default::default()
                },
                ..Default::default()
            },
        )
        .expect("session");

    let mut prepared = prepare_with_session(
        session,
        workspace.path(),
        "list the files",
        &context(),
        "openai",
        "mock-model",
    )
    .expect("prepared");

    prepared
        .execute(CollectingSink::new())
        .await
        .expect("first turn");
    prepared
        .send("what did you do?", CollectingSink::new(), AllowAll)
        .await
        .expect("second turn");

    // The tool round is part of the conversation, so the last request carries
    // the assistant's tool use and its result, not just the prose.
    let requests = mock.recorded_requests().await;
    let last = requests.last().expect("a request was made");
    let has_tool_use = last.messages.iter().any(|message| {
        message
            .content
            .iter()
            .any(|block| matches!(block, mentra::ContentBlock::ToolUse { .. }))
    });
    let has_tool_result = last.messages.iter().any(|message| {
        message
            .content
            .iter()
            .any(|block| matches!(block, mentra::ContentBlock::ToolResult { .. }))
    });

    assert!(
        has_tool_use && has_tool_result,
        "a later turn must still see the earlier turn's tool round"
    );
}