basis 0.22.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
//! What `.basis/config.json` may say, who may say it, and which file wins.

use super::*;

/// An environment fixed by the test rather than by the shell that started it,
/// for [`crate::provider`]'s reason: the variables this module expands are
/// exactly the ones a person working on basis is likely to have exported.
fn exporting(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
    let vars: Vec<(String, String)> = vars
        .iter()
        .map(|(var, value)| ((*var).to_string(), (*value).to_string()))
        .collect();

    move |name: &str| {
        vars.iter()
            .find(|(var, _)| var == name)
            .map(|(_, value)| value.clone())
    }
}

fn nothing_exported() -> impl Fn(&str) -> Option<String> {
    exporting(&[])
}

fn write(path: &std::path::Path, body: &str) {
    std::fs::create_dir_all(path.parent().expect("a parent")).expect("create dir");
    std::fs::write(path, body).expect("write file");
}

/// The workspace file, in a fresh temp directory.
fn workspace_file(root: &std::path::Path, body: &str) {
    write(&root.join(DEFAULT_WORKSPACE_CONFIG_FILE), body);
}

fn global_file(dir: &std::path::Path, body: &str) {
    write(&dir.join(DEFAULT_GLOBAL_CONFIG_FILE), body);
}

fn discover(
    root: &std::path::Path,
    global: Option<&std::path::Path>,
) -> Result<Config, ConfigError> {
    Config::discover_with(root, global, &nothing_exported())
}

#[test]
fn nothing_on_disk_says_nothing() {
    let tmp = tempfile::tempdir().expect("tempdir");

    let config = discover(tmp.path(), None).expect("a missing file is not an error");

    assert!(config.is_empty());
    assert!(config.files.is_empty());
}

#[test]
fn a_workspace_file_pins_the_model_and_names_itself() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(
        tmp.path(),
        r#"{"schema": 1, "model": "claude-sonnet-4-5-20250929"}"#,
    );

    let config = discover(tmp.path(), None).expect("a well-formed file");

    let model = config.model.as_ref().expect("the file set a model");
    assert_eq!(model.value, "claude-sonnet-4-5-20250929");
    assert_eq!(model.scope, ContextScope::Workspace);
    assert_eq!(model.path, tmp.path().join(DEFAULT_WORKSPACE_CONFIG_FILE));
    assert_eq!(
        config.model_selector(),
        Some(ModelSelector::Id("claude-sonnet-4-5-20250929".to_string()))
    );
    assert_eq!(config.files.len(), 1, "the file that decided is reported");
    assert_eq!(config.files[0].scope, "workspace");
}

#[test]
fn every_key_is_optional() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), r#"{"schema": 1}"#);

    let config = discover(tmp.path(), None).expect("an empty file is a choice");

    assert!(
        config.is_empty(),
        "a file that says nothing settles nothing"
    );
    assert_eq!(config.files.len(), 1, "it was still read");
}

#[test]
fn the_workspace_file_outranks_the_global_one_key_by_key() {
    // The point of layering per key rather than per file: a repository that
    // pins a model has not thereby unsaid its owner's preferred effort.
    let tmp = tempfile::tempdir().expect("tempdir");
    let global = tmp.path().join("global");
    workspace_file(tmp.path(), r#"{"schema": 1, "model": "workspace-model"}"#);
    global_file(
        &global,
        r#"{"schema": 1, "model": "global-model", "effort": "high", "provider": "openai"}"#,
    );

    let config = discover(tmp.path(), Some(&global)).expect("both files parse");

    let model = config.model.expect("a model");
    assert_eq!(model.value, "workspace-model");
    assert_eq!(model.scope, ContextScope::Workspace);

    let effort = config.effort.expect("the global effort survives");
    assert_eq!(effort.value, Effort::High);
    assert_eq!(effort.scope, ContextScope::Global);
    assert_eq!(effort.path, global.join(DEFAULT_GLOBAL_CONFIG_FILE));

    let provider = config.provider.expect("the global provider survives");
    assert_eq!(provider.value, BuiltinProvider::OpenAI);
    assert_eq!(provider.scope, ContextScope::Global);

    assert_eq!(config.files.len(), 2, "both files are reported");
    assert_eq!(
        config
            .files
            .iter()
            .map(|file| file.scope.as_str())
            .collect::<Vec<_>>(),
        vec!["workspace", "global"],
        "most specific first"
    );
}

#[test]
fn a_base_url_in_the_workspace_file_is_refused_and_the_file_is_named() {
    // The whole asymmetry of this format: a committed file may not point the
    // model's traffic — and the key riding on it — at a host nobody chose.
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(
        tmp.path(),
        r#"{"schema": 1, "base_url": "https://gateway.example.com/v1"}"#,
    );

    let error = discover(tmp.path(), None).expect_err("refused, not ignored");

    assert!(
        matches!(error, ConfigError::WorkspaceBaseUrl { .. }),
        "{error}"
    );
    let rendered = error.to_string();
    assert!(
        rendered.contains(DEFAULT_WORKSPACE_CONFIG_FILE),
        "{rendered}"
    );
    assert!(rendered.contains("base_url"), "{rendered}");
}

#[test]
fn a_base_url_in_the_global_file_is_honored() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let global = tmp.path().join("global");
    global_file(
        &global,
        r#"{"schema": 1, "base_url": "https://gateway.example.com/v1"}"#,
    );

    let config = discover(tmp.path(), Some(&global)).expect("the user's own file may say it");

    let base_url = config.base_url.expect("a base URL");
    assert_eq!(
        base_url.value, "https://gateway.example.com/",
        "normalized where a typo can still name this file"
    );
    assert_eq!(base_url.scope, ContextScope::Global);
}

#[test]
fn a_workspace_file_may_still_choose_a_provider() {
    // Safe where `base_url` is not: it selects a preset endpoint and an
    // environment variable, and both of those are the user's own.
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), r#"{"schema": 1, "provider": "anthropic"}"#);

    let config = discover(tmp.path(), None).expect("a well-formed file");

    assert_eq!(
        config.provider.expect("a provider").value,
        BuiltinProvider::Anthropic
    );
}

#[test]
fn there_is_no_api_key_and_saying_one_is_an_error() {
    // A credential is the environment's. `deny_unknown_fields` is what makes
    // the absence enforceable rather than documented.
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), r#"{"schema": 1, "api_key": "sk-live-nope"}"#);

    let error = discover(tmp.path(), None).expect_err("there is no such key");

    assert!(matches!(error, ConfigError::Parse { .. }), "{error}");
    assert!(
        !error.to_string().contains("sk-live-nope"),
        "no error repeats a value it read: {error}"
    );
}

#[test]
fn a_misspelled_key_is_an_error_not_a_silent_default() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), r#"{"schema": 1, "modle": "gpt-5"}"#);

    let error = discover(tmp.path(), None).expect_err("a typo is caught");

    assert!(matches!(error, ConfigError::Parse { .. }), "{error}");
}

#[test]
fn a_malformed_file_is_an_error_naming_it() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), "{not json");

    let error = discover(tmp.path(), None).expect_err("malformed is an error");

    match error {
        ConfigError::Parse { ref path, .. } => {
            assert_eq!(path, &tmp.path().join(DEFAULT_WORKSPACE_CONFIG_FILE));
        }
        other => panic!("expected a parse error, got {other}"),
    }
}

#[test]
fn a_file_that_states_no_schema_is_an_error() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), r#"{"model": "gpt-5"}"#);

    let error = discover(tmp.path(), None).expect_err("basis will not guess a schema");

    assert!(matches!(error, ConfigError::NoSchema { .. }), "{error}");
}

#[test]
fn a_schema_from_the_future_is_an_error() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), r#"{"schema": 99, "model": "gpt-5"}"#);

    let error = discover(tmp.path(), None).expect_err("an unknown schema is refused");

    assert!(
        matches!(error, ConfigError::UnsupportedSchema { schema: 99, .. }),
        "{error}"
    );
}

#[test]
fn environment_placeholders_are_expanded() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(
        tmp.path(),
        r#"{"schema": 1, "model": "${TEAM_MODEL}", "provider": "${TEAM_PROVIDER}"}"#,
    );

    let config = Config::discover_with(
        tmp.path(),
        None,
        &exporting(&[("TEAM_MODEL", "gpt-5"), ("TEAM_PROVIDER", "openai")]),
    )
    .expect("both are set");

    assert_eq!(config.model.expect("a model").value, "gpt-5");
    assert_eq!(
        config.provider.expect("a provider").value,
        BuiltinProvider::OpenAI
    );
}

#[test]
fn an_unset_placeholder_names_the_key_and_the_variable() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), r#"{"schema": 1, "model": "${TEAM_MODEL}"}"#);

    let error = discover(tmp.path(), None).expect_err("an unset variable is an error");

    let rendered = error.to_string();
    assert!(rendered.contains("model"), "{rendered}");
    assert!(rendered.contains("TEAM_MODEL"), "{rendered}");
}

#[test]
fn a_placeholder_may_carry_a_default() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(
        tmp.path(),
        r#"{"schema": 1, "model": "${TEAM_MODEL:-gpt-5}"}"#,
    );

    let config = discover(tmp.path(), None).expect("the fallback answers");

    assert_eq!(config.model.expect("a model").value, "gpt-5");
}

#[test]
fn the_five_effort_spellings_are_the_flags_own() {
    for (text, expected) in [
        ("low", Effort::Low),
        ("medium", Effort::Medium),
        ("high", Effort::High),
        ("xhigh", Effort::XHigh),
        ("max", Effort::Max),
    ] {
        let tmp = tempfile::tempdir().expect("tempdir");
        workspace_file(
            tmp.path(),
            &format!(r#"{{"schema": 1, "effort": "{text}"}}"#),
        );

        let config = discover(tmp.path(), None).expect("a known spelling");

        assert_eq!(config.effort.expect("an effort").value, expected);
    }
}

#[test]
fn an_unknown_effort_is_an_error() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), r#"{"schema": 1, "effort": "hardest"}"#);

    let error = discover(tmp.path(), None).expect_err("only five words are efforts");

    assert!(matches!(error, ConfigError::Parse { .. }), "{error}");
}

#[test]
fn an_unknown_provider_names_the_key_and_the_alternatives() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), r#"{"schema": 1, "provider": "hal9000"}"#);

    let error = discover(tmp.path(), None).expect_err("rejected");

    let rendered = error.to_string();
    assert!(rendered.contains("provider"), "{rendered}");
    assert!(rendered.contains("anthropic"), "{rendered}");
}

#[test]
fn an_empty_model_is_an_error_rather_than_a_request_for_nothing() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), r#"{"schema": 1, "model": "   "}"#);

    let error = discover(tmp.path(), None).expect_err("rejected");

    assert!(
        matches!(error, ConfigError::Invalid { key: "model", .. }),
        "{error}"
    );
}

#[test]
fn a_directory_where_the_file_should_be_is_ignored() {
    let tmp = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir_all(tmp.path().join(DEFAULT_WORKSPACE_CONFIG_FILE))
        .expect("create a directory with the file's name");

    let config = discover(tmp.path(), None).expect("discovery succeeds");

    assert!(config.is_empty());
}

#[test]
fn the_same_file_reached_twice_is_read_once() {
    // A global directory that *is* the workspace's `.basis` would otherwise
    // layer one file against itself and report two.
    let tmp = tempfile::tempdir().expect("tempdir");
    let global = tmp.path().join(".basis");
    workspace_file(tmp.path(), r#"{"schema": 1, "model": "gpt-5"}"#);

    let config = discover(tmp.path(), Some(&global)).expect("discovery succeeds");

    assert_eq!(config.files.len(), 1);
    assert_eq!(config.files[0].scope, "workspace");
}

#[test]
fn an_empty_config_is_the_off_switch() {
    let config = Config::default();

    assert!(config.is_empty());
    assert_eq!(config.model_selector(), None);
}

#[test]
fn a_ring_in_the_global_file_names_its_members_in_order_and_where_their_keys_live() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let global = tmp.path().join("global");
    global_file(
        &global,
        r#"{"schema": 1, "gateways": [
            {"base_url": "${GATEWAY_HOST}/v1", "api_key_file": "/run/secrets/local"},
            {"base_url": "http://relay/v1", "api_key_env": "RELAY_KEY",
             "strip_model_prefix": "openai/"}
        ]}"#,
    );

    let config = Config::discover_with(
        tmp.path(),
        Some(&global),
        &exporting(&[("GATEWAY_HOST", "http://local:2455")]),
    )
    .expect("the user's own file may say it");

    assert!(!config.is_empty());
    let ring = config.gateways.expect("a ring");
    assert_eq!(ring.scope, ContextScope::Global);
    assert_eq!(
        ring.value,
        GatewayRingConfig {
            members: vec![
                crate::runtime::GatewayMember::new("http://local:2455/v1")
                    .with_api_key_file("/run/secrets/local"),
                crate::runtime::GatewayMember::new("http://relay/v1")
                    .with_api_key_env("RELAY_KEY")
                    .with_model_prefix_stripped("openai/"),
            ],
            policy: None,
        }
    );
}

#[test]
fn a_ring_object_carries_its_policy() {
    use crate::runtime::GatewayRingPolicy;
    use std::time::Duration;

    let policy = |body: &str| {
        let tmp = tempfile::tempdir().expect("tempdir");
        let global = tmp.path().join("global");
        global_file(&global, body);
        discover(tmp.path(), Some(&global))
            .expect("parses")
            .gateways
            .expect("a ring")
            .value
            .policy
    };
    let members = r#""members": [{"base_url": "http://a/v1"}]"#;

    assert_eq!(
        policy(&format!(
            r#"{{"schema": 1, "gateways": {{{members}, "failure_threshold": 2, "cooldown_secs": 30}}}}"#
        )),
        Some(GatewayRingPolicy {
            failure_threshold: 2,
            cooldown: Some(Duration::from_secs(30)),
        })
    );
    assert_eq!(
        policy(&format!(
            r#"{{"schema": 1, "gateways": {{{members}, "sticky": true}}}}"#
        )),
        Some(GatewayRingPolicy::sticky())
    );
    assert_eq!(
        policy(&format!(r#"{{"schema": 1, "gateways": {{{members}}}}}"#)),
        None,
        "an object that says nothing about policy leaves the host's standing"
    );
}

#[test]
fn a_ring_in_the_workspace_file_is_refused_like_a_base_url() {
    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(
        tmp.path(),
        r#"{"schema": 1, "gateways": [{"base_url": "http://a/v1"}]}"#,
    );

    let error = discover(tmp.path(), None).expect_err("refused, not ignored");

    assert!(
        matches!(error, ConfigError::WorkspaceGateways { .. }),
        "{error}"
    );
}

#[test]
fn a_ring_that_cannot_be_meant_is_refused_by_key() {
    for (gateways, says) in [
        (r#"[]"#, "lists no gateways"),
        (
            r#"[{"base_url": "http://a/v1", "api_key_env": "A", "api_key_file": "/a"}]"#,
            "gateway #0 names both",
        ),
        (r#"[{"base_url": "not a url"}]"#, "gateway #0"),
        (
            r#"{"members": [{"base_url": "http://a/v1"}], "sticky": true, "cooldown_secs": 5}"#,
            "both `sticky` and `cooldown_secs`",
        ),
        (
            r#"{"members": [{"base_url": "http://a/v1"}], "failure_threshold": 0}"#,
            "`failure_threshold` to 0",
        ),
    ] {
        let tmp = tempfile::tempdir().expect("tempdir");
        let global = tmp.path().join("global");
        global_file(
            &global,
            &format!(r#"{{"schema": 1, "gateways": {gateways}}}"#),
        );

        let error = discover(tmp.path(), Some(&global)).expect_err(gateways);

        let rendered = error.to_string();
        assert!(
            matches!(
                error,
                ConfigError::Invalid {
                    key: "gateways",
                    ..
                }
            ),
            "{rendered}"
        );
        assert!(rendered.contains(says), "{rendered}");
    }
}

#[test]
fn a_ring_beside_a_base_url_is_refused() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let global = tmp.path().join("global");
    global_file(
        &global,
        r#"{"schema": 1, "base_url": "http://a/v1", "gateways": [{"base_url": "http://b/v1"}]}"#,
    );

    let error = discover(tmp.path(), Some(&global)).expect_err("refused");

    assert!(error.to_string().contains("beside `base_url`"), "{error}");
}

#[test]
fn the_variable_reads_the_files_schema_and_names_no_value_when_it_cannot() {
    let ring =
        parse_gateways_var(r#"[{"base_url": "http://a/v1", "api_key_env": "A"}]"#).expect("parses");
    assert_eq!(ring.members.len(), 1);

    let reason = parse_gateways_var(r#"[{"base_url": "http://a/v1", "api_kee": "sk-secret"}]"#)
        .expect_err("an unknown key");
    assert!(!reason.contains("sk-secret"), "{reason}");
    assert!(parse_gateways_var("not json").is_err());
}

#[test]
fn a_named_file_is_read_as_the_hosts_own_and_nothing_else_is_probed() {
    let tmp = tempfile::tempdir().expect("tempdir");
    // A workspace file beside it that must not be read.
    workspace_file(tmp.path(), r#"{"schema": 1, "model": "from-the-repo"}"#);
    let named = tmp.path().join("host.json");
    write(
        &named,
        r#"{"schema": 1, "base_url": "http://gateway/v1", "model": "from-the-host"}"#,
    );

    let config = Config::read_file_with(&named, &nothing_exported())
        .expect("a file the host named may set base_url");

    assert_eq!(
        config.model.map(|model| model.value).as_deref(),
        Some("from-the-host")
    );
    assert_eq!(
        config.base_url.map(|url| url.value).as_deref(),
        Some("http://gateway/")
    );
    assert_eq!(config.files.len(), 1);
}

#[test]
fn a_lookup_is_recorded_in_three_spellings_and_defaults_to_nothing() {
    for (lookup, json) in [
        (ConfigLookup::None, r#""none""#),
        (ConfigLookup::Discover, r#""discover""#),
        (
            ConfigLookup::File(PathBuf::from("/etc/basis.json")),
            r#"{"file":"/etc/basis.json"}"#,
        ),
    ] {
        assert_eq!(serde_json::to_string(&lookup).expect("serializes"), json);
        assert_eq!(
            serde_json::from_str::<ConfigLookup>(json).expect("parses"),
            lookup
        );
    }
    assert_eq!(ConfigLookup::default(), ConfigLookup::None);

    let tmp = tempfile::tempdir().expect("tempdir");
    workspace_file(tmp.path(), r#"{"schema": 1, "model": "from-the-repo"}"#);
    assert!(
        ConfigLookup::None
            .load(tmp.path(), None)
            .expect("reads nothing")
            .is_empty()
    );
}