capsule-runtime 0.11.0

The runtime that executes Murmur capsules. Runs packaged AI agents in isolation, enforcing WASI capability grants on a Wasmtime component sandbox.
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
//! Loading a process driver: the artifact a `transport: process` manifest names under
//! `inference.driver`, which knows how to drive one harness CLI.
//!
//! A process driver is pure translation and is granted nothing. [`ProcessDriver`] instantiates
//! it on an empty WASI context with no Murmur host import, so a driver that reaches for anything
//! else fails to load rather than running with less than it expected.

use murmur_artifact::{version_fit, FitSubject, VersionFit, WitContracts, WitLevel};
use wasmtime::component::{Component, Linker, ResourceTable};
use wasmtime::{Engine, Store};
use wasmtime_wasi::{WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView};

use crate::bindings::process_driver::ProcessDriver as ProcessDriverBindings;
use crate::errors::RuntimeError;
use crate::limits::{
    classify_guest_failure, CallDeadlines, ComponentRole, EpochTicker, ExecutionLimiter,
    GuestFailure, WallDeadline,
};
use crate::ExecutionLimits;

pub use crate::bindings::process_driver::exports::murmur::driver::process::{
    Bridge, Description, DriverFile, Event, ExitStatus, FailureKind, HarnessNeeds, InterruptMethod,
    LaunchPlan, LaunchRequest, LoginCheck, LoginOutput, LoginState, PathAccess, PathNeed,
    QuotaState, QuotaWindow, RetryInfo, Session, SessionInfo, SessionMode, ToolCallInfo,
    ToolCallProgress, ToolCallStart, ToolResultInfo, TurnFailure, Usage,
};

impl QuotaState {
    /// The WIT spelling of the state, which every record and frame carrying it uses.
    pub fn wire_name(self) -> &'static str {
        match self {
            QuotaState::Ok => "ok",
            QuotaState::Warning => "warning",
            QuotaState::Exhausted => "exhausted",
        }
    }
}

/// The instance name every process driver exports.
pub const PROCESS_DRIVER_IFACE: &str = "murmur:driver/process@0.6.0";

/// Every version of the process interface starts with this, so an export built against another
/// version is still recognised as a process driver.
const PROCESS_DRIVER_IFACE_PREFIX: &str = "murmur:driver/process@";

/// Checks the inference driver's exports against the transport that names it and the WIT level
/// this host serves.
///
/// Under `process` the driver's exports must include the process interface at the version
/// `level` lists for `murmur:driver` (for the served level, [`PROCESS_DRIVER_IFACE`]) under that
/// exact name; other instances alongside it are ignored. A driver exporting the process interface
/// only at other versions does not fit the level and is refused with
/// [`RuntimeError::WitLevelMismatch`]; one exporting no version of it is not a process driver and
/// is refused with [`RuntimeError::ProcessDriverInterfaceMissing`]. Under `http` it must export
/// no version of the process interface. `contracts` is what
/// [`murmur_artifact::extract_wit_contracts`] read out of the driver's wasm; `None` (a core
/// module, or bytes it could not read) counts as exporting nothing. Any other transport passes.
pub fn check_driver_interface(
    transport: &str,
    name: &str,
    version: &str,
    contracts: Option<&WitContracts>,
    level: &WitLevel,
) -> Result<(), RuntimeError> {
    let process_exports: Vec<String> = contracts
        .map(|c| {
            c.exports
                .iter()
                .filter(|export| export.starts_with(PROCESS_DRIVER_IFACE_PREFIX))
                .cloned()
                .collect()
        })
        .unwrap_or_default();
    let expected = level_interface(level, "murmur:driver", "process")
        .unwrap_or_else(|| PROCESS_DRIVER_IFACE.to_string());
    match transport {
        "process" if process_exports.contains(&expected) => Ok(()),
        "process" if process_exports.is_empty() => {
            Err(RuntimeError::ProcessDriverInterfaceMissing {
                name: name.to_string(),
                version: version.to_string(),
                expected,
            })
        }
        // Refuse even if every export fits the level: none is `expected`, so the driver must not
        // pass.
        "process" => Err(
            level_mismatch(name, version, level, process_exports, Vec::new()).unwrap_or_else(
                || RuntimeError::ProcessDriverInterfaceMissing {
                    name: name.to_string(),
                    version: version.to_string(),
                    expected,
                },
            ),
        ),
        "http" if !process_exports.is_empty() => {
            Err(RuntimeError::HttpDriverExportsProcessInterface {
                name: name.to_string(),
                version: version.to_string(),
                exported: process_exports,
            })
        }
        _ => Ok(()),
    }
}

/// Every instance of the retired `murmur:text` package starts with this. No version of it is
/// served: `murmur:stream/events` replaced it.
const RETIRED_TEXT_IFACE_PREFIX: &str = "murmur:text/";

/// Every instance of the `murmur:stream` package starts with this.
const STREAM_IFACE_PREFIX: &str = "murmur:stream/";

/// Checks a `runtime: driver` artifact's imports against the stream interface of the WIT level
/// this host serves.
///
/// Refuses a component importing any `murmur:text/*` instance, or any `murmur:stream/*` instance
/// other than exactly `murmur:stream/events` at the version `level` lists (for the served level,
/// [`WIT_STREAM_EVENTS_IFACE`]): the host serves neither, so the driver would fail to instantiate
/// on its first turn. The imports among those that do not fit `level` are refused with
/// [`RuntimeError::WitLevelMismatch`]; only when every one is at the level's version of its
/// package, under an interface name that does not exist, is it
/// [`RuntimeError::DriverStreamInterfaceNotServed`]. `contracts` is what
/// [`murmur_artifact::extract_wit_contracts`] read out of the driver's wasm; `None`, and a
/// component importing neither package, pass.
///
/// [`WIT_STREAM_EVENTS_IFACE`]: crate::runtime::WIT_STREAM_EVENTS_IFACE
pub fn check_stream_interface(
    name: &str,
    version: &str,
    contracts: Option<&WitContracts>,
    level: &WitLevel,
) -> Result<(), RuntimeError> {
    let expected = level_interface(level, "murmur:stream", "events")
        .unwrap_or_else(|| crate::runtime::WIT_STREAM_EVENTS_IFACE.to_string());
    let imported: Vec<String> = contracts
        .map(|c| {
            c.imports
                .iter()
                .filter(|import| {
                    import.starts_with(RETIRED_TEXT_IFACE_PREFIX)
                        || (import.starts_with(STREAM_IFACE_PREFIX) && **import != expected)
                })
                .cloned()
                .collect()
        })
        .unwrap_or_default();
    if imported.is_empty() {
        return Ok(());
    }
    if let Some(mismatch) = level_mismatch(name, version, level, Vec::new(), imported.clone()) {
        return Err(mismatch);
    }
    Err(RuntimeError::DriverStreamInterfaceNotServed {
        name: name.to_string(),
        version: version.to_string(),
        imported,
        expected,
    })
}

/// The one refusal of a driver both [`check_stream_interface`] and [`check_driver_interface`]
/// checked: a level mismatch over any other, both checks' mismatches together (exports first)
/// when each found one, and otherwise the stream check's refusal before the driver check's.
pub(crate) fn driver_refusal(
    stream: Result<(), RuntimeError>,
    driver: Result<(), RuntimeError>,
) -> Result<(), RuntimeError> {
    match (stream, driver) {
        (
            Err(RuntimeError::WitLevelMismatch {
                mismatched: imports,
                ..
            }),
            Err(RuntimeError::WitLevelMismatch {
                name,
                version,
                level,
                mismatched: mut exports,
            }),
        ) => {
            exports.extend(imports);
            Err(RuntimeError::WitLevelMismatch {
                name,
                version,
                level,
                mismatched: exports,
            })
        }
        (Err(_), Err(driver @ RuntimeError::WitLevelMismatch { .. })) => Err(driver),
        (Err(stream), _) => Err(stream),
        (Ok(()), driver) => driver,
    }
}

/// `<package>/<interface>@<version>` at the version `level` lists for `package`, if it lists one.
fn level_interface(level: &WitLevel, package: &str, interface: &str) -> Option<String> {
    level
        .version_of(package)
        .map(|version| format!("{package}/{interface}@{version}"))
}

/// Refuses a WASM tool, driver or script capsule whose `murmur:*` exports and imports do not all
/// fit `level`, with [`RuntimeError::WitLevelMismatch`] naming each one that does not. A component
/// built for an earlier level would otherwise stage and fail on its first call.
pub(crate) fn check_component_level(
    name: &str,
    version: &str,
    contracts: WitContracts,
    level: &WitLevel,
) -> Result<(), RuntimeError> {
    match level_mismatch(name, version, level, contracts.exports, contracts.imports) {
        Some(mismatch) => Err(mismatch),
        None => Ok(()),
    }
}

/// [`RuntimeError::WitLevelMismatch`] for the refused names among `exports` and `imports` that do
/// not fit `level`, or `None` when every one of them does.
fn level_mismatch(
    name: &str,
    version: &str,
    level: &WitLevel,
    exports: Vec<String>,
    imports: Vec<String>,
) -> Option<RuntimeError> {
    let subject = FitSubject::component(WitContracts { exports, imports });
    match version_fit(&subject, level) {
        VersionFit::Unserved(mismatched) => Some(RuntimeError::WitLevelMismatch {
            name: name.to_string(),
            version: version.to_string(),
            level: level.level,
            mismatched,
        }),
        VersionFit::Fits => None,
    }
}

/// Checks that every variable `description.required_env` names is declared in
/// `capabilities.env.allow`, given as `env_allow`. Names match exactly.
///
/// The refusal lists every undeclared name, in the driver's order, each once.
pub fn check_required_env(
    name: &str,
    version: &str,
    description: &Description,
    env_allow: &[String],
) -> Result<(), RuntimeError> {
    let mut missing: Vec<String> = Vec::new();
    for var in &description.required_env {
        if !env_allow.contains(var) && !missing.contains(var) {
            missing.push(var.clone());
        }
    }
    if missing.is_empty() {
        Ok(())
    } else {
        Err(RuntimeError::ProcessDriverRequiredEnvNotAllowed {
            name: name.to_string(),
            version: version.to_string(),
            missing,
        })
    }
}

/// The store a process driver runs in: an empty WASI context and the execution limits.
struct ProcessDriverStoreState {
    wasi: WasiCtx,
    table: ResourceTable,
    limits: ExecutionLimiter,
}

impl WasiView for ProcessDriverStoreState {
    fn ctx(&mut self) -> WasiCtxView<'_> {
        WasiCtxView {
            ctx: &mut self.wasi,
            table: &mut self.table,
        }
    }
}

/// One instantiated process driver. The runtime keeps one for a whole run, so the driver may
/// carry what `launch` was given into `parse`.
pub struct ProcessDriver {
    name: String,
    version: String,
    body: DriverBody,
    /// The session's latch, where a call the wall-clock bound stops is recorded.
    call_deadlines: CallDeadlines,
    /// The call the wall-clock bound stopped, once one has, and its deadline in seconds. The
    /// stopped call's future was dropped mid-guest, so the instance is never entered again.
    cut: Option<(&'static str, u64)>,
}

/// Where a process driver instance lives: in this process's store, or in the driver guest worker,
/// which runs the same instance body and answers each call.
enum DriverBody {
    Local {
        store: Store<ProcessDriverStoreState>,
        bindings: ProcessDriverBindings,
    },
    Remote(crate::guest_worker::RemoteProcessDriver),
}

/// One process driver call, as it crosses to the driver guest worker.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum DriverCall {
    Describe,
    Launch(LaunchRequest),
    Parse(Vec<String>),
    ClassifyExit(ExitStatus),
    ReadLogin(LoginOutput),
}

/// A process driver call's answer from the driver guest worker.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum DriverAnswer {
    Opened,
    Description(Description),
    Launch(Result<LaunchPlan, String>),
    Events(Vec<Event>),
    Event(Event),
    Login(LoginState),
}

/// A process driver's [`RuntimeError`] as it crosses from the driver guest worker; the
/// supervisor names the driver again on the way back.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) enum DriverError {
    Load(String),
    CallFailed { call: String, message: String },
    Other(String),
}

impl DriverError {
    pub(crate) fn from_runtime(error: RuntimeError) -> Self {
        match error {
            RuntimeError::ProcessDriverLoad { message, .. } => Self::Load(message),
            RuntimeError::ProcessDriverCallFailed { call, message, .. } => {
                Self::CallFailed { call, message }
            }
            other => Self::Other(other.to_string()),
        }
    }

    pub(crate) fn into_runtime(self, name: &str, version: &str) -> RuntimeError {
        match self {
            Self::Load(message) => RuntimeError::ProcessDriverLoad {
                name: name.to_string(),
                version: version.to_string(),
                message,
            },
            Self::CallFailed { call, message } => RuntimeError::ProcessDriverCallFailed {
                name: name.to_string(),
                version: version.to_string(),
                call,
                message,
            },
            Self::Other(message) => RuntimeError::Runtime(message),
        }
    }
}

impl ProcessDriver {
    /// Instantiates `component` as [`Self::instantiate`] does: in the driver guest worker when
    /// `workers` is given, in this process otherwise.
    pub(crate) async fn open(
        workers: Option<&std::sync::Arc<crate::guest_worker::GuestWorkers>>,
        engine: &Engine,
        component: &Component,
        name: &str,
        version: &str,
        call_deadlines: CallDeadlines,
    ) -> Result<Self, RuntimeError> {
        let Some(workers) = workers else {
            return Self::instantiate(engine, component, name, version, call_deadlines).await;
        };
        let remote = crate::guest_worker::RemoteProcessDriver::open(
            workers,
            component,
            name,
            version,
            &call_deadlines,
        )
        .await?;
        Ok(Self {
            name: name.to_string(),
            version: version.to_string(),
            body: DriverBody::Remote(remote),
            call_deadlines,
            cut: None,
        })
    }

    /// Runs `call` on this instance, whichever process holds it. The worker side of a remote
    /// instance runs this same method on its local instance.
    pub(crate) async fn call(&mut self, call: DriverCall) -> Result<DriverAnswer, RuntimeError> {
        Ok(match call {
            DriverCall::Describe => DriverAnswer::Description(self.describe().await?),
            DriverCall::Launch(request) => DriverAnswer::Launch(self.launch(request).await?),
            DriverCall::Parse(lines) => DriverAnswer::Events(self.parse(lines).await?),
            DriverCall::ClassifyExit(exit) => DriverAnswer::Event(self.classify_exit(exit).await?),
            DriverCall::ReadLogin(output) => DriverAnswer::Login(self.read_login(output).await?),
        })
    }

    /// `call` on the driver worker's instance, or `None` for a local instance.
    async fn remote_call(
        &mut self,
        call: DriverCall,
    ) -> Option<Result<DriverAnswer, RuntimeError>> {
        match &self.body {
            DriverBody::Remote(remote) => Some(remote.call(call, &self.call_deadlines).await),
            DriverBody::Local { .. } => None,
        }
    }

    fn unexpected(&self, call: &str, answer: DriverAnswer) -> RuntimeError {
        self.failed_in(call, format!("the guest worker answered {answer:?}"))
    }

    /// Instantiates `component` with no grants: a WASI context with no environment, arguments,
    /// preopened directories, inherited stdio or network, and no Murmur host import.
    ///
    /// Each call into the driver is bounded by the hook call limits
    /// ([`ExecutionLimits::for_hook_calls`] with no declared deadline), so `engine` must have an
    /// epoch ticker running, and to the same wall-clock bound, recorded in `call_deadlines`.
    /// `name` and `version` identify the driver in errors. Any failure, including an import the
    /// empty context does not provide, is [`RuntimeError::ProcessDriverLoad`] carrying wasmtime's
    /// message.
    pub(crate) async fn instantiate(
        engine: &Engine,
        component: &Component,
        name: &str,
        version: &str,
        call_deadlines: CallDeadlines,
    ) -> Result<Self, RuntimeError> {
        let load_error = |message: String| RuntimeError::ProcessDriverLoad {
            name: name.to_string(),
            version: version.to_string(),
            message,
        };
        let limits = ExecutionLimits::default().for_hook_calls(None);
        crate::guest_worker::check_store_placement(crate::guest_worker::StoreSite::ProcessDriver)?;

        let mut linker: Linker<ProcessDriverStoreState> = Linker::new(engine);
        wasmtime_wasi::p2::add_to_linker_async(&mut linker)
            .map_err(|e| load_error(e.to_string()))?;

        let state = ProcessDriverStoreState {
            // The builder's defaults are the grant: no environment, arguments, preopens or
            // stdio, no name lookup, and a socket address check that refuses every address.
            wasi: WasiCtxBuilder::new().build(),
            table: ResourceTable::new(),
            limits: limits.limiter(),
        };
        let mut store = Store::new(engine, state);
        store.limiter(|state| &mut state.limits);
        store.set_epoch_deadline(limits.deadline_ticks());

        let bindings = call_deadlines
            .bound(
                name,
                ComponentRole::ProcessDriver,
                "instantiate",
                &limits,
                ProcessDriverBindings::instantiate_async(&mut store, component, &linker),
            )
            .await
            .map_err(|_| load_error(format!("instantiation {}", wall_deadline_text(&limits))))?
            .map_err(|e| load_error(format!("{e:#}")))?;
        Ok(Self {
            name: name.to_string(),
            version: version.to_string(),
            body: DriverBody::Local { store, bindings },
            call_deadlines,
            cut: None,
        })
    }

    /// Calls the driver's `describe`.
    ///
    /// A trap, an exceeded deadline, a `required-env` entry that is not a usable variable name
    /// (empty, or containing `=` or NUL), or a `login-check` command naming no arguments is
    /// [`RuntimeError::ProcessDriverLoad`]. The bare harness binary may start a session, so the
    /// login check must never run it with nothing after it.
    pub async fn describe(&mut self) -> Result<Description, RuntimeError> {
        if let Some(answer) = self.remote_call(DriverCall::Describe).await {
            return match answer? {
                DriverAnswer::Description(description) => Ok(description),
                other => Err(self.unexpected("describe", other)),
            };
        }
        self.enter("describe")
            .map_err(|message| self.load_error(message))?;
        let limits = self.reset_deadline();
        let DriverBody::Local { store, bindings } = &mut self.body else {
            unreachable!("a remote driver answered above")
        };
        let called = self
            .call_deadlines
            .bound(
                &self.name,
                ComponentRole::ProcessDriver,
                "describe",
                &limits,
                bindings.murmur_driver_process().call_describe(&mut *store),
            )
            .await;
        let description = self
            .settle("describe", &limits, called)
            .map_err(|message| self.load_error(format!("describe() {message}")))?
            .map_err(|e| {
                let message = match classify_guest_failure(&e, self.limiter()) {
                    GuestFailure::DeadlineExceeded { seconds } => {
                        format!("describe() exceeded its {seconds}s deadline and was interrupted")
                    }
                    GuestFailure::ResourceLimit { message } => {
                        format!("describe() exceeded its resource limits: {message}")
                    }
                    GuestFailure::Other => format!("describe() trapped: {e:#}"),
                };
                self.load_error(message)
            })?;
        validate_description(&self.name, &self.version, &description)?;
        Ok(description)
    }

    /// Asks the driver to plan one harness run. The inner `Err` is the driver's own refusal,
    /// reported to the operator verbatim; the outer one is a trap or an exceeded deadline.
    pub async fn launch(
        &mut self,
        request: LaunchRequest,
    ) -> Result<Result<LaunchPlan, String>, RuntimeError> {
        if let DriverBody::Remote(remote) = &self.body {
            return match remote
                .call(DriverCall::Launch(request), &self.call_deadlines)
                .await?
            {
                DriverAnswer::Launch(plan) => Ok(plan),
                other => Err(self.unexpected("launch", other)),
            };
        }
        self.enter("launch")
            .map_err(|message| self.failed_in("launch", message))?;
        let limits = self.reset_deadline();
        let DriverBody::Local { store, bindings } = &mut self.body else {
            unreachable!("a remote driver answered above")
        };
        let called = self
            .call_deadlines
            .bound(
                &self.name,
                ComponentRole::ProcessDriver,
                "launch",
                &limits,
                bindings
                    .murmur_driver_process()
                    .call_launch(&mut *store, &request),
            )
            .await;
        self.settle("launch", &limits, called)
            .map_err(|message| self.failed_in("launch", message))?
            .map_err(|e| self.call_error("launch", &e))
    }

    /// Reads one batch of complete stdout lines into events. The same instance serves a whole
    /// run, so the driver may answer from what `launch` was given.
    pub async fn parse(&mut self, lines: Vec<String>) -> Result<Vec<Event>, RuntimeError> {
        if let DriverBody::Remote(remote) = &self.body {
            return match remote
                .call(DriverCall::Parse(lines), &self.call_deadlines)
                .await?
            {
                DriverAnswer::Events(events) => Ok(events),
                other => Err(self.unexpected("parse", other)),
            };
        }
        self.enter("parse")
            .map_err(|message| self.failed_in("parse", message))?;
        let limits = self.reset_deadline();
        let DriverBody::Local { store, bindings } = &mut self.body else {
            unreachable!("a remote driver answered above")
        };
        let called = self
            .call_deadlines
            .bound(
                &self.name,
                ComponentRole::ProcessDriver,
                "parse",
                &limits,
                bindings
                    .murmur_driver_process()
                    .call_parse(&mut *store, &lines),
            )
            .await;
        self.settle("parse", &limits, called)
            .map_err(|message| self.failed_in("parse", message))?
            .map_err(|e| self.call_error("parse", &e))
    }

    /// Asks the driver what a run whose output ended without a terminal event amounts to.
    pub async fn classify_exit(&mut self, exit: ExitStatus) -> Result<Event, RuntimeError> {
        if let DriverBody::Remote(remote) = &self.body {
            return match remote
                .call(DriverCall::ClassifyExit(exit), &self.call_deadlines)
                .await?
            {
                DriverAnswer::Event(event) => Ok(event),
                other => Err(self.unexpected("classify-exit", other)),
            };
        }
        self.enter("classify-exit")
            .map_err(|message| self.failed_in("classify-exit", message))?;
        let limits = self.reset_deadline();
        let DriverBody::Local { store, bindings } = &mut self.body else {
            unreachable!("a remote driver answered above")
        };
        let called = self
            .call_deadlines
            .bound(
                &self.name,
                ComponentRole::ProcessDriver,
                "classify-exit",
                &limits,
                bindings
                    .murmur_driver_process()
                    .call_classify_exit(&mut *store, &exit),
            )
            .await;
        self.settle("classify-exit", &limits, called)
            .map_err(|message| self.failed_in("classify-exit", message))?
            .map_err(|e| self.call_error("classify-exit", &e))
    }

    /// Asks the driver to read what its `login-check` command printed.
    pub async fn read_login(&mut self, output: LoginOutput) -> Result<LoginState, RuntimeError> {
        if let DriverBody::Remote(remote) = &self.body {
            return match remote
                .call(DriverCall::ReadLogin(output), &self.call_deadlines)
                .await?
            {
                DriverAnswer::Login(state) => Ok(state),
                other => Err(self.unexpected("read-login", other)),
            };
        }
        self.enter("read-login")
            .map_err(|message| self.failed_in("read-login", message))?;
        let limits = self.reset_deadline();
        let DriverBody::Local { store, bindings } = &mut self.body else {
            unreachable!("a remote driver answered above")
        };
        let called = self
            .call_deadlines
            .bound(
                &self.name,
                ComponentRole::ProcessDriver,
                "read-login",
                &limits,
                bindings
                    .murmur_driver_process()
                    .call_read_login(&mut *store, &output),
            )
            .await;
        self.settle("read-login", &limits, called)
            .map_err(|message| self.failed_in("read-login", message))?
            .map_err(|e| self.call_error("read-login", &e))
    }

    /// Gives the next call its own deadline, and returns the limits it runs under. Without this
    /// the ticks the previous call spent would count against it, so a long run would eventually
    /// interrupt a driver that had done nothing wrong.
    fn reset_deadline(&mut self) -> ExecutionLimits {
        let DriverBody::Local { store, .. } = &mut self.body else {
            return ExecutionLimits::default().for_hook_calls(None);
        };
        let limits = store.data().limits.limits();
        store.set_epoch_deadline(limits.deadline_ticks());
        limits
    }

    /// The local store's limiter, read when a guest failure is classified.
    fn limiter(&self) -> &ExecutionLimiter {
        match &self.body {
            DriverBody::Local { store, .. } => &store.data().limits,
            DriverBody::Remote(_) => unreachable!("a remote driver classifies in its worker"),
        }
    }

    /// Refuses a call into an instance the wall-clock bound stopped earlier, naming that call.
    fn enter(&self, call: &str) -> Result<(), String> {
        match self.cut {
            None => Ok(()),
            Some((earlier, seconds)) => Err(format!(
                "{call} was not called: the earlier {earlier} call was stopped at its {seconds}s \
                 deadline, and a stopped driver is not entered again"
            )),
        }
    }

    /// A bound call's outcome: the call's own result, or, when the wall-clock bound stopped it,
    /// the instance marked cut and the text saying so.
    fn settle<T>(
        &mut self,
        call: &'static str,
        limits: &ExecutionLimits,
        called: Result<T, WallDeadline>,
    ) -> Result<T, String> {
        called.map_err(|_| {
            self.cut = Some((call, limits.deadline_seconds));
            wall_deadline_text(limits)
        })
    }

    fn failed_in(&self, call: &str, message: String) -> RuntimeError {
        RuntimeError::ProcessDriverCallFailed {
            name: self.name.clone(),
            version: self.version.clone(),
            call: call.to_string(),
            message,
        }
    }

    fn call_error(&self, call: &str, error: &wasmtime::Error) -> RuntimeError {
        let message = match classify_guest_failure(error, self.limiter()) {
            GuestFailure::DeadlineExceeded { seconds } => {
                format!("exceeded its {seconds}s deadline and was interrupted")
            }
            GuestFailure::ResourceLimit { message } => {
                format!("exceeded its resource limits: {message}")
            }
            GuestFailure::Other => format!("trapped: {error:#}"),
        };
        self.failed_in(call, message)
    }

    fn load_error(&self, message: String) -> RuntimeError {
        RuntimeError::ProcessDriverLoad {
            name: self.name.clone(),
            version: self.version.clone(),
            message,
        }
    }
}

/// What a process driver phase the wall-clock bound stopped reports, in the wording of the
/// epoch's "exceeded its …s deadline and was interrupted": the driver's deadline is the hook
/// default, which no manifest key sets.
fn wall_deadline_text(limits: &ExecutionLimits) -> String {
    format!(
        "waited on the host past its {}s deadline and was stopped",
        limits.deadline_seconds
    )
}

/// Whether `name` can be set as an environment variable.
///
/// A name carrying `=` would set a second variable when an environment is built, and one carrying
/// NUL truncates it; an empty name is neither. Both places a driver names a variable — its
/// `required-env`, checked at load, and its launch plan's `env-set`, checked at spawn — hold to
/// this one rule.
pub(crate) fn is_usable_env_name(name: &str) -> bool {
    !name.is_empty() && !name.contains('=') && !name.contains('\0')
}

/// The first `required-env` name that could not be set as an environment variable, if any.
/// Rejected where the driver's word is first taken, rather than wherever it is later spent.
fn unusable_env_name(description: &Description) -> Option<&str> {
    description
        .required_env
        .iter()
        .find(|var| !is_usable_env_name(var))
        .map(String::as_str)
}

/// Refuses a description the runtime cannot act on, as [`RuntimeError::ProcessDriverLoad`]: a
/// `required-env` name that is not a usable variable name, or a `login-check` command with no
/// arguments.
fn validate_description(
    name: &str,
    version: &str,
    description: &Description,
) -> Result<(), RuntimeError> {
    let load_error = |message: String| RuntimeError::ProcessDriverLoad {
        name: name.to_string(),
        version: version.to_string(),
        message,
    };
    if let Some(bad) = unusable_env_name(description) {
        return Err(load_error(format!(
            "describe() names {bad:?} in required-env, which is not a usable variable name"
        )));
    }
    if matches!(&description.login_check, LoginCheck::Command(args) if args.is_empty()) {
        return Err(load_error(
            "describe() names a login-check command with no arguments; the bare harness binary \
             may start a session, so the login check must name the arguments that make it report \
             its login"
                .to_string(),
        ));
    }
    if let Err(reason) = crate::harness_needs::validate_harness_needs(&description.harness_needs) {
        return Err(load_error(format!("describe() {reason}")));
    }
    Ok(())
}

/// The name and version the `*_process_driver_wasm` helpers give a driver in errors, since bare
/// bytes carry no artifact name.
const STANDALONE_NAME: &str = "<wasm>";
const STANDALONE_VERSION: &str = "";

/// `wasm` compiled on a fresh engine with its own epoch ticker, and a current-thread runtime to
/// drive one instance of it on: everything the `*_process_driver_wasm` helpers share.
pub(crate) struct StandaloneDriver {
    engine: Engine,
    component: Component,
    pub(crate) rt: tokio::runtime::Runtime,
    _ticker: EpochTicker,
    name: String,
    version: String,
    /// The driver guest worker the instance runs in, when this process uses worker processes.
    workers: Option<std::sync::Arc<crate::guest_worker::GuestWorkers>>,
}

impl StandaloneDriver {
    fn compile(wasm: &[u8]) -> Result<Self, RuntimeError> {
        Self::compile_named(wasm, STANDALONE_NAME, STANDALONE_VERSION)
    }

    /// Compiles `wasm`, naming the driver `name` and `version` in every error.
    pub(crate) fn compile_named(
        wasm: &[u8],
        name: &str,
        version: &str,
    ) -> Result<Self, RuntimeError> {
        let engine = crate::runtime::build_engine()?;
        let ticker = EpochTicker::spawn(&engine);
        let component =
            Component::new(&engine, wasm).map_err(|e| RuntimeError::ToolComponentCompile {
                name: name.to_string(),
                version: version.to_string(),
                message: e.to_string(),
            })?;
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| {
                RuntimeError::Runtime(format!("failed to build process driver runtime: {e}"))
            })?;
        Ok(StandaloneDriver {
            engine,
            component,
            rt,
            _ticker: ticker,
            name: name.to_string(),
            version: version.to_string(),
            workers: crate::guest_worker::session_launcher()
                .map(crate::guest_worker::GuestWorkers::new),
        })
    }

    pub(crate) async fn instantiate(&self) -> Result<ProcessDriver, RuntimeError> {
        ProcessDriver::open(
            self.workers.as_ref(),
            &self.engine,
            &self.component,
            &self.name,
            &self.version,
            // No session trace exists to drain a firing into.
            CallDeadlines::default(),
        )
        .await
    }
}

/// Compiles `wasm` as a process driver on a fresh engine, instantiates it with no grants, and
/// returns what its `describe` reports.
///
/// For tests and tools that hold a driver's bytes outside any capsule. It blocks on its own
/// current-thread runtime, so it must not be called from inside one. Errors name the driver as
/// `<wasm>` with an empty version, since the bytes carry no artifact name.
pub fn describe_process_driver_wasm(wasm: &[u8]) -> Result<Description, RuntimeError> {
    let driver = StandaloneDriver::compile(wasm)?;
    driver.rt.block_on(async {
        let mut instance = driver.instantiate().await?;
        instance.describe().await
    })
}

/// Compiles `wasm` as a process driver the way [`describe_process_driver_wasm`] does, then calls
/// `launch` with `request` and `parse` with `lines` on that one instance, as a run would.
///
/// Returns the driver's launch answer — its own refusal is the inner `Err` — and the events
/// `parse` read. `parse` is called whether or not `launch` refused, so a driver's line reading
/// can be checked on its own. The same blocking and error-naming rules apply.
pub fn launch_and_parse_process_driver_wasm(
    wasm: &[u8],
    request: LaunchRequest,
    lines: Vec<String>,
) -> Result<(Result<LaunchPlan, String>, Vec<Event>), RuntimeError> {
    let driver = StandaloneDriver::compile(wasm)?;
    driver.rt.block_on(async {
        let mut instance = driver.instantiate().await?;
        let plan = instance.launch(request).await?;
        let events = instance.parse(lines).await?;
        Ok((plan, events))
    })
}

#[cfg(test)]
mod tests {
    use murmur_artifact::ContractDirection;

    use super::*;

    fn served() -> &'static WitLevel {
        crate::served_wit_level()
    }

    fn contracts(exports: &[&str]) -> WitContracts {
        WitContracts {
            exports: exports.iter().map(|e| e.to_string()).collect(),
            imports: Vec::new(),
        }
    }

    #[test]
    fn process_driver_interface_process_transport_accepts_the_process_export() {
        let c = contracts(&[PROCESS_DRIVER_IFACE]);
        assert!(check_driver_interface("process", "d", "1.0.0", Some(&c), served()).is_ok());
    }

    #[test]
    fn process_driver_interface_process_transport_refuses_a_tool_export() {
        let c = contracts(&["murmur:tool/run@0.2.0"]);
        let err = check_driver_interface("process", "d", "1.0.0", Some(&c), served()).unwrap_err();
        match &err {
            RuntimeError::ProcessDriverInterfaceMissing { expected, .. } => {
                assert_eq!(expected, PROCESS_DRIVER_IFACE);
            }
            other => panic!("unexpected error: {other:?}"),
        }
        let message = err.to_string();
        assert!(message.contains("'d@1.0.0'"), "{message}");
        assert!(message.contains(PROCESS_DRIVER_IFACE), "{message}");
    }

    #[test]
    fn process_driver_interface_process_transport_refuses_another_version_as_a_level_mismatch() {
        let c = contracts(&["murmur:driver/process@0.0.1"]);
        let err = check_driver_interface("process", "d", "1.0.0", Some(&c), served()).unwrap_err();
        match &err {
            RuntimeError::WitLevelMismatch {
                level, mismatched, ..
            } => {
                assert_eq!(*level, served().level);
                assert_eq!(mismatched.len(), 1);
                assert_eq!(mismatched[0].interface, "murmur:driver/process@0.0.1");
                assert_eq!(mismatched[0].direction, ContractDirection::Export);
            }
            other => panic!("unexpected error: {other:?}"),
        }
        assert_eq!(
            err.to_string(),
            format!(
                "artifact 'd@1.0.0' does not fit WIT level {0}, the level this mur serves: it \
                 exports murmur:driver/process@0.0.1, and level {0} has murmur:driver@{1}",
                served().level,
                served().version_of("murmur:driver").unwrap()
            )
        );
    }

    /// Level 1, the committed level before the one this host serves, which has
    /// `murmur:driver@0.3.0`.
    fn level_1() -> &'static WitLevel {
        &crate::wit_versions::wit_levels()[0]
    }

    #[test]
    fn process_driver_interface_follows_the_level_it_is_given() {
        let c = contracts(&[PROCESS_DRIVER_IFACE]);
        assert!(check_driver_interface("process", "d", "1.0.0", Some(&c), served()).is_ok());
        match check_driver_interface("process", "d", "1.0.0", Some(&c), level_1()).unwrap_err() {
            RuntimeError::WitLevelMismatch {
                level, mismatched, ..
            } => {
                assert_eq!(level, 1);
                assert_eq!(mismatched[0].direction, ContractDirection::Export);
                assert_eq!(mismatched[0].package, "murmur:driver");
                assert_eq!(mismatched[0].served_version.as_deref(), Some("0.3.0"));
            }
            other => panic!("unexpected error: {other:?}"),
        }
        let old = contracts(&["murmur:driver/process@0.3.0"]);
        assert!(check_driver_interface("process", "d", "1.0.0", Some(&old), level_1()).is_ok());
        let stream = importing(&["murmur:stream/events@0.1.0"]);
        assert!(check_stream_interface("d", "1.0.0", Some(&stream), level_1()).is_ok());
    }

    #[test]
    fn process_driver_interface_process_transport_refuses_no_contracts() {
        let err = check_driver_interface("process", "d", "1.0.0", None, served()).unwrap_err();
        assert!(matches!(
            err,
            RuntimeError::ProcessDriverInterfaceMissing { .. }
        ));
    }

    #[test]
    fn process_driver_interface_http_transport_refuses_the_process_export() {
        let c = contracts(&[PROCESS_DRIVER_IFACE]);
        let err = check_driver_interface("http", "d", "1.0.0", Some(&c), served()).unwrap_err();
        match &err {
            RuntimeError::HttpDriverExportsProcessInterface { name, exported, .. } => {
                assert_eq!(name, "d");
                assert_eq!(exported, &vec![PROCESS_DRIVER_IFACE.to_string()]);
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn process_driver_interface_http_transport_accepts_a_tool_export() {
        let c = contracts(&["murmur:tool/run@0.2.0"]);
        assert!(check_driver_interface("http", "d", "1.0.0", Some(&c), served()).is_ok());
    }

    fn importing(imports: &[&str]) -> WitContracts {
        WitContracts {
            exports: vec!["murmur:tool/run@0.2.0".to_string()],
            imports: imports.iter().map(|i| i.to_string()).collect(),
        }
    }

    #[test]
    fn stream_interface_refuses_and_lists_a_murmur_text_import() {
        let c = importing(&[
            "wasi:cli/environment@0.2.12",
            "murmur:text/chunks@0.1.0",
            "murmur:task/task@0.1.0",
        ]);
        let err = check_stream_interface("d", "1.0.0", Some(&c), served()).unwrap_err();
        match &err {
            RuntimeError::WitLevelMismatch {
                name,
                version,
                mismatched,
                ..
            } => {
                assert_eq!((name.as_str(), version.as_str()), ("d", "1.0.0"));
                assert_eq!(mismatched.len(), 1);
                assert_eq!(mismatched[0].interface, "murmur:text/chunks@0.1.0");
                assert_eq!(mismatched[0].served_version, None);
            }
            other => panic!("unexpected error: {other:?}"),
        }
        let message = err.to_string();
        assert!(message.contains("'d@1.0.0'"), "{message}");
        assert!(
            message.contains(
                "it imports murmur:text/chunks@0.1.0, and level 6 has no version of murmur:text"
            ),
            "{message}"
        );
    }

    #[test]
    fn stream_interface_refuses_another_version_of_murmur_stream() {
        let c = importing(&["murmur:stream/events@0.2.0"]);
        let err = check_stream_interface("d", "1.0.0", Some(&c), served()).unwrap_err();
        assert!(matches!(
            err,
            RuntimeError::WitLevelMismatch { ref mismatched, .. }
                if mismatched.len() == 1 && mismatched[0].interface == "murmur:stream/events@0.2.0"
        ));
    }

    /// An import at the served version of `murmur:stream` under an interface the package does not
    /// define fits the level, so it is not a level mismatch: the interface does not exist.
    #[test]
    fn stream_interface_refuses_an_unknown_interface_at_the_served_version_as_not_served() {
        let c = importing(&["murmur:stream/other@0.1.0"]);
        let err = check_stream_interface("d", "1.0.0", Some(&c), served()).unwrap_err();
        match &err {
            RuntimeError::DriverStreamInterfaceNotServed {
                imported, expected, ..
            } => {
                assert_eq!(imported, &vec!["murmur:stream/other@0.1.0".to_string()]);
                assert_eq!(expected, crate::runtime::WIT_STREAM_EVENTS_IFACE);
            }
            other => panic!("unexpected error: {other:?}"),
        }
        // With a level mismatch beside it, the mismatch is what is reported.
        let both = importing(&["murmur:stream/other@0.1.0", "murmur:text/chunks@0.1.0"]);
        assert!(matches!(
            check_stream_interface("d", "1.0.0", Some(&both), served()).unwrap_err(),
            RuntimeError::WitLevelMismatch { ref mismatched, .. }
                if mismatched.len() == 1 && mismatched[0].interface == "murmur:text/chunks@0.1.0"
        ));
    }

    #[test]
    fn driver_refusal_reports_a_level_mismatch_over_any_other() {
        let not_served = || {
            check_stream_interface(
                "d",
                "1.0.0",
                Some(&importing(&["murmur:stream/other@0.1.0"])),
                served(),
            )
        };
        let old_export = || {
            check_driver_interface(
                "process",
                "d",
                "1.0.0",
                Some(&contracts(&["murmur:driver/process@0.2.0"])),
                served(),
            )
        };
        let text_import = || {
            check_stream_interface(
                "d",
                "1.0.0",
                Some(&importing(&["murmur:text/chunks@0.1.0"])),
                served(),
            )
        };
        let no_export = || check_driver_interface("process", "d", "1.0.0", None, served());

        assert!(matches!(
            driver_refusal(not_served(), old_export()),
            Err(RuntimeError::WitLevelMismatch { .. })
        ));
        assert!(matches!(
            driver_refusal(text_import(), no_export()),
            Err(RuntimeError::WitLevelMismatch { .. })
        ));
        assert!(matches!(
            driver_refusal(not_served(), no_export()),
            Err(RuntimeError::DriverStreamInterfaceNotServed { .. })
        ));
        match driver_refusal(text_import(), old_export()) {
            Err(RuntimeError::WitLevelMismatch { mismatched, .. }) => {
                let names: Vec<&str> = mismatched.iter().map(|m| m.interface.as_str()).collect();
                assert_eq!(
                    names,
                    ["murmur:driver/process@0.2.0", "murmur:text/chunks@0.1.0"]
                );
            }
            other => panic!("unexpected result: {other:?}"),
        }
        assert!(driver_refusal(Ok(()), Ok(())).is_ok());
    }

    #[test]
    fn stream_interface_accepts_exactly_the_served_instance() {
        let c = importing(&["murmur:stream/events@0.1.0", "wasi:http/types@0.2.12"]);
        assert!(check_stream_interface("d", "1.0.0", Some(&c), served()).is_ok());
    }

    #[test]
    fn stream_interface_accepts_a_component_with_no_murmur_import() {
        let c = importing(&["wasi:cli/environment@0.2.12"]);
        assert!(check_stream_interface("d", "1.0.0", Some(&c), served()).is_ok());
        assert!(check_stream_interface("d", "1.0.0", Some(&importing(&[])), served()).is_ok());
    }

    #[test]
    fn stream_interface_accepts_no_contracts() {
        assert!(check_stream_interface("d", "1.0.0", None, served()).is_ok());
    }

    fn description(required_env: &[&str]) -> Description {
        Description {
            harness: "h".to_string(),
            binary: "b".to_string(),
            version_args: Vec::new(),
            tested_versions: Vec::new(),
            interrupt: InterruptMethod::Unsupported,
            required_env: required_env.iter().map(|v| v.to_string()).collect(),
            streams_text: false,
            reports_usage: false,
            login_check: LoginCheck::Unavailable("no login".to_string()),
            harness_needs: HarnessNeeds {
                paths: Vec::new(),
                hosts: Vec::new(),
            },
        }
    }

    #[test]
    fn login_check_command_with_arguments_passes() {
        let mut described = description(&[]);
        described.login_check = LoginCheck::Command(vec!["auth".to_string(), "status".to_string()]);
        assert!(validate_description("d", "1.0.0", &described).is_ok());
        assert!(validate_description("d", "1.0.0", &description(&[])).is_ok());
    }

    /// A bare harness binary may start a session, so a login check naming no arguments is a
    /// driver that cannot load.
    #[test]
    fn login_check_command_with_no_arguments_is_refused_at_load() {
        let mut described = description(&[]);
        described.login_check = LoginCheck::Command(Vec::new());
        let err = validate_description("d", "1.0.0", &described).unwrap_err();
        match &err {
            RuntimeError::ProcessDriverLoad { message, .. } => {
                assert!(
                    message.contains("login-check command with no arguments"),
                    "{message}"
                );
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn required_env_all_declared_passes() {
        let allow = vec!["A".to_string(), "B".to_string(), "C".to_string()];
        assert!(check_required_env("d", "1.0.0", &description(&["B", "A"]), &allow).is_ok());
    }

    #[test]
    fn required_env_reports_missing_names_in_order_once_each() {
        let allow = vec!["B".to_string()];
        let err = check_required_env("d", "1.0.0", &description(&["Z", "B", "A", "Z"]), &allow)
            .unwrap_err();
        match &err {
            RuntimeError::ProcessDriverRequiredEnvNotAllowed { missing, .. } => {
                assert_eq!(missing, &vec!["Z".to_string(), "A".to_string()]);
            }
            other => panic!("unexpected error: {other:?}"),
        }
        let message = err.to_string();
        assert!(message.contains("'d@1.0.0'"), "{message}");
        assert!(message.contains("Z, A"), "{message}");
    }

    #[test]
    fn required_env_usable_names_pass() {
        assert_eq!(
            unusable_env_name(&description(&["HOME", "PROFILE_2"])),
            None
        );
        assert_eq!(unusable_env_name(&description(&[])), None);
    }

    #[test]
    fn required_env_refuses_a_name_that_is_not_a_variable() {
        for bad in ["", "A=B", "A\0B"] {
            assert_eq!(
                unusable_env_name(&description(&["HOME", bad, "TAIL"])),
                Some(bad),
                "{bad:?} should be refused"
            );
        }
    }

    /// What one `parse` call costs, and what instantiating a driver costs.
    ///
    /// Ignored: it measures rather than asserts, and the numbers only mean anything in a release
    /// build. Run it with
    /// `cargo test -p capsule-runtime --release process_driver_parse_cost -- --ignored --nocapture`.
    #[test]
    #[ignore = "a measurement, not an assertion; run with --release --ignored --nocapture"]
    fn process_driver_parse_cost() {
        use std::time::Instant;

        const WASM: &[u8] = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../murmur-cli/tests/fixtures/process-driver/tool/process-driver.wasm"
        ));
        let engine = crate::runtime::build_engine().expect("engine");
        let _ticker = EpochTicker::spawn(&engine);
        let component = Component::new(&engine, WASM).expect("fixture compiles");
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("runtime");

        let instantiations = 50;
        let start = Instant::now();
        for _ in 0..instantiations {
            rt.block_on(ProcessDriver::instantiate(
                &engine,
                &component,
                "d",
                "0.1.0",
                CallDeadlines::default(),
            ))
            .expect("instantiates");
        }
        let per_instantiation = start.elapsed() / instantiations;

        let mut driver = rt
            .block_on(ProcessDriver::instantiate(
                &engine,
                &component,
                "d",
                "0.1.0",
                CallDeadlines::default(),
            ))
            .expect("instantiates");
        for lines in [1usize, 64] {
            let batch: Vec<String> = (0..lines).map(|i| format!("text line {i}")).collect();
            let runs = 2_000;
            let mut samples = Vec::with_capacity(runs);
            for _ in 0..runs {
                let start = Instant::now();
                let events = rt.block_on(driver.parse(batch.clone())).expect("parses");
                samples.push(start.elapsed());
                assert_eq!(events.len(), lines);
            }
            samples.sort_unstable();
            let median = samples[samples.len() / 2];
            let p95 = samples[samples.len() * 95 / 100];
            crate::diagnostic::raw_to_stdout(&format!(
                "parse {lines}-line batch on one reused instance: median {median:?}, p95 {p95:?} \
                 ({runs} calls)\n"
            ));
        }
        crate::diagnostic::raw_to_stdout(&format!(
            "instantiate one driver: {per_instantiation:?} (mean of {instantiations})\n"
        ));
    }

    #[test]
    fn process_driver_granted_nothing() {
        let wat = r#"(component
            (import "murmur:stream/events@0.1.0" (instance
                (export "emit-chunk" (func (param "chunk" string)))
            ))
        )"#;
        let bytes = wat::parse_str(wat).expect("component WAT parses");
        let engine = crate::runtime::build_engine().expect("engine");
        let _ticker = EpochTicker::spawn(&engine);
        let component = Component::new(&engine, &bytes).expect("component compiles");
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("runtime");
        let result = rt.block_on(ProcessDriver::instantiate(
            &engine,
            &component,
            "d",
            "1.0.0",
            CallDeadlines::default(),
        ));
        match result {
            Err(RuntimeError::ProcessDriverLoad { name, message, .. }) => {
                assert_eq!(name, "d");
                assert!(message.contains("murmur:stream/events@0.1.0"), "{message}");
            }
            Err(other) => panic!("unexpected error: {other:?}"),
            Ok(_) => panic!("a driver importing a Murmur interface instantiated"),
        }
    }

    #[test]
    fn launch_and_parse_run_on_one_instance() {
        const WASM: &[u8] = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../murmur-cli/tests/fixtures/process-driver/tool/process-driver.wasm"
        ));
        let request = LaunchRequest {
            model: None,
            system_prompt: String::new(),
            config: None,
            bridge: Some(Bridge {
                server_name: "murmur".to_string(),
                url: "http://127.0.0.1:1/mcp".to_string(),
                bearer_token: "token".to_string(),
                tool_names: vec!["python3".to_string()],
            }),
            session: Session {
                id: "s1".to_string(),
                mode: SessionMode::New,
            },
            harness_version: None,
            task: "probe".to_string(),
        };
        let lines = vec![
            r#"tool c1 murmur__python3 {"command":"x"}"#.to_string(),
            "end done".to_string(),
        ];
        let (plan, events) =
            launch_and_parse_process_driver_wasm(WASM, request, lines).expect("driver runs");
        let plan = plan.expect("the fixture accepts a non-empty task");
        assert!(plan
            .env_set
            .iter()
            .any(|(name, value)| name == "FIXTURE_BRIDGE_TOKEN" && value == "token"));
        // The fixture strips the `<server-name>__` prefix it remembered in `launch`, so a bare
        // name here shows `parse` ran on the instance `launch` configured.
        match &events[..] {
            [Event::ToolCall(call), Event::TurnEnd(summary)] => {
                assert_eq!(call.name, "python3");
                assert_eq!(call.input, r#"{"command":"x"}"#);
                assert_eq!(summary, "done");
            }
            other => panic!("unexpected events: {other:?}"),
        }
    }
}