BREP_mcp_core 0.12.0

The next.BREP.io MCP server core for the Rust B-rep CAD app: the Model Context Protocol surface generated from the app's own registries, its sessions, script runner and transports (stdio and streamable HTTP). Embedded in the app behind `brep-app --mcp`; hosted headlessly by BREP_mcp.
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
//! Code mode: a restricted JavaScript program — a plain script body with
//! top-level `await` and `return`, its returned value the result — run on Boa
//! in a WORKER PROCESS of its own (`brep_script_core::worker`), talking to the
//! CAD service only by message passing.
//!
//! The worker is the host's OWN executable started with a hidden flag
//! ([`WORKER_FLAG`], [`worker_entry`]), so a shipped app — one binary — needs
//! nothing beside it. The host that starts the worker owns it. It sends the
//! start message `{names, limits, source}`: the `<namespace>.<action>` names
//! the program was granted ([`CadService::script_names`]) and no SDK source;
//! the worker builds the global `sdk` from them. It relays each
//! `{call, method, body}` to the service ([`CadService::script_call`]) and the
//! answer back as `{call, ok, value}` or `{call, ok: false, error}`, and it
//! KILLS the worker on an agent's halt, on the CPU budget (the worker's own
//! CPU time — it sleeps while it waits on the host), on the memory limit (its
//! resident set) or on the wall deadline. A kill stops any script however it
//! loops; nothing of the host is reachable from it. Accepted operations
//! belong to the service: an execution that ends, throws, hits a limit or is
//! halted detaches from them and lists them; it never cancels them.
use super::keys::{self, Purpose};
use super::ops::{Caller, Grants};
use super::wire::{self, ApiError, Effects};
use super::{canon, CadService};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::io::{BufRead, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, Mutex, Weak};
use std::time::{Duration, Instant};

pub const MAX_ACTIVE: usize = 4;
pub const MAX_ACTIVE_PER_SCOPE: usize = 2;
pub const MAX_RETAINED: usize = 128;

/// The §12 limits, as configured for one execution.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Limits {
    pub source_bytes: u64,
    pub input_bytes: u64,
    pub bridge_bytes: u64,
    pub js_cpu_ms: u64,
    pub js_heap_bytes: u64,
    pub wall_ms: u64,
    pub outstanding_host_calls: u64,
    pub log_bytes: u64,
    pub result_bytes: u64,
    pub artifact_count: u64,
    pub artifact_bytes: u64,
}

impl Default for Limits {
    fn default() -> Self {
        Limits {
            source_bytes: 256 << 10,
            input_bytes: 1 << 20,
            bridge_bytes: 16 << 20,
            js_cpu_ms: 5_000,
            js_heap_bytes: 64 << 20,
            wall_ms: 15 * 60 * 1000,
            outstanding_host_calls: 8,
            log_bytes: 64 << 10,
            result_bytes: 64 << 10,
            artifact_count: 16,
            artifact_bytes: 128 << 20,
        }
    }
}

const LIMIT_KEYS: &[&str] = &[
    "sourceBytes", "inputBytes", "bridgeBytes", "jsCpuMs", "jsHeapBytes", "wallMs",
    "outstandingHostCalls", "logBytes", "resultBytes", "artifactCount", "artifactBytes",
];

impl Limits {
    fn fields(&mut self) -> [&mut u64; 11] {
        [
            &mut self.source_bytes, &mut self.input_bytes, &mut self.bridge_bytes,
            &mut self.js_cpu_ms, &mut self.js_heap_bytes, &mut self.wall_ms, &mut self.outstanding_host_calls, &mut self.log_bytes,
            &mut self.result_bytes, &mut self.artifact_count, &mut self.artifact_bytes,
        ]
    }

    /// Requested limits may LOWER the defaults; raising one needs host policy,
    /// which this server does not grant.
    pub fn lowered(requested: Option<&Value>) -> Result<Limits, ApiError> {
        let mut limits = Limits::default();
        let Some(req) = requested.filter(|v| !v.is_null()) else { return Ok(limits) };
        let obj = req.as_object().ok_or_else(|| ApiError::new("invalid_arguments", "validation", "limits must be an object"))?;
        if let Some(k) = obj.keys().find(|k| !LIMIT_KEYS.contains(&k.as_str())) {
            return Err(ApiError::new("invalid_arguments", "validation", format!("unknown limit `{k}`")));
        }
        for (key, slot) in LIMIT_KEYS.iter().zip(limits.fields()) {
            if let Some(v) = obj.get(*key) {
                let n = v.as_u64().filter(|n| *n > 0 && *n <= (1 << 53)).ok_or_else(|| ApiError::new("invalid_arguments", "validation", format!("{key} must be a positive safe integer")))?;
                if n > *slot {
                    return Err(ApiError::new("capability_denied", "authorization", format!("raising {key} above {} needs host policy", *slot)));
                }
                *slot = n;
            }
        }
        Ok(limits)
    }

    pub fn to_json(&self) -> Value {
        let mut copy = *self;
        let mut out = serde_json::Map::new();
        for (key, v) in LIMIT_KEYS.iter().zip(copy.fields()) {
            out.insert(key.to_string(), json!(*v));
        }
        Value::Object(out)
    }
}

/// The host policy for code mode: what an execution may be granted at most.
/// `document.*` / `cad.*` / `artifact.*` are bounded to the documents and
/// artifacts the execution creates (or explicitly names); record controls are
/// `own` only. No filesystem, network, process, environment or plugin
/// capability exists to request.
fn effective_grants(requested: &Value, initial: &[(String, String)]) -> Result<(Grants, Value), ApiError> {
    const ALLOWED: &[&str] = &[
        "catalogue.read", "document.create", "document.read", "document.write", "document.close", "artifact.read", "artifact.write",
        "cad.export", "cad.import", "operation.read", "operation.cancel",
    ];
    let list = requested.as_array().ok_or_else(|| ApiError::new("invalid_arguments", "validation", "requestedCapabilities must be an array"))?;
    let mut names = Vec::new();
    let mut effective = Vec::new();
    let mut documents: Vec<String> = Vec::new();
    let mut document_grants = HashMap::<String, Vec<String>>::new();
    let mut created_capabilities = Vec::new();
    for grant in list {
        let obj = grant.as_object().ok_or_else(|| ApiError::new("invalid_arguments", "validation", "a capability grant must be an object"))?;
        const FIELDS: &[&str] = &["name", "documentIds", "allowCreatedDocuments", "allowExecutionArtifacts", "formats", "maxBytes", "controlScope"];
        if let Some(k) = obj.keys().find(|k| !FIELDS.contains(&k.as_str())) {
            return Err(ApiError::new("invalid_arguments", "validation", format!("unknown grant field `{k}`")));
        }
        let name = obj.get("name").and_then(Value::as_str).ok_or_else(|| ApiError::new("invalid_arguments", "validation", "a grant needs a name"))?;
        if !super::ops::CAPABILITIES.contains(&name) {
            return Err(ApiError::new("invalid_arguments", "validation", format!("unknown capability `{name}`")));
        }
        let attributes: &[&str] = match name {
            "document.read" | "document.write" | "document.close" => &["name", "documentIds", "allowCreatedDocuments"],
            "cad.import" | "cad.export" => &["name", "documentIds", "allowCreatedDocuments", "formats", "maxBytes"],
            "artifact.read" | "artifact.write" => &["name", "allowExecutionArtifacts", "maxBytes"],
            "operation.read" | "operation.cancel" => &["name", "controlScope"],
            _ => &["name"],
        };
        if let Some(key) = obj.keys().find(|k| !attributes.contains(&k.as_str())) {
            return Err(ApiError::new("invalid_arguments", "validation", format!("{key} is not an attribute of {name}")));
        }
        if name.starts_with("operation.") && obj.get("controlScope").is_some_and(|v| v.as_str() != Some("own")) {
            return Err(ApiError::new("capability_denied", "authorization", "code mode grants only `own` record control"));
        }
        if !ALLOWED.contains(&name) {
            // execution.*, code.execute and view.* are not grantable to a program:
            // it cannot inspect other executions or start new ones.
            return Err(ApiError::new("capability_denied", "authorization", format!("`{name}` cannot be granted to a code-mode program")));
        }
        if obj.get("formats").is_some_and(|v| *v != json!(["step"])) || obj.get("maxBytes").is_some_and(|v| v.as_u64() != Some(super::artifacts::MAX_ARTIFACT as u64)) {
            return Err(ApiError::new("capability_denied", "authorization", "only STEP with the fixed per-artifact byte limit is currently supported; use execution artifact limits to lower the budget"));
        }
        if obj.get("allowExecutionArtifacts").is_some_and(|v| *v != json!(true)) {
            return Err(ApiError::new("capability_denied", "authorization", "artifact capabilities require allowExecutionArtifacts=true"));
        }
        if obj.get("allowCreatedDocuments").is_some_and(|v| !v.is_boolean()) || obj.get("documentIds").is_some_and(|v| !v.is_array()) {
            return Err(ApiError::new("invalid_arguments", "validation", "invalid document grant"));
        }
        if obj.get("allowCreatedDocuments") == Some(&json!(true)) { created_capabilities.push(name.to_string()); }
        if let Some(ids) = obj.get("documentIds").and_then(Value::as_array) {
            for id in ids {
                let id = id.as_str().ok_or_else(|| ApiError::new("invalid_arguments", "validation", "documentIds holds strings"))?;
                // An existing document is granted only if the submission named it.
                if !initial.iter().any(|(d, _)| d == id) {
                    return Err(ApiError::new("capability_denied", "authorization", "a granted document must be one of initialDocuments"));
                }
                documents.push(id.to_string());
                document_grants.entry(name.to_string()).or_default().push(id.to_string());
            }
        }
        if !names.iter().any(|n| n == name) {
            names.push(name.to_string());
        }
        effective.push(grant.clone());
    }
    let grants = Grants { names, documents: Some(Arc::new(Mutex::new(documents))), created_documents: !created_capabilities.is_empty(), document_grants: Some(Arc::new(Mutex::new(document_grants))), created_capabilities };
    Ok((grants, Value::Array(effective)))
}

/// A host call the worker made: `sdk.<method>(body)`, owned JSON both ways.
struct BridgeCall {
    call: u64,
    method: String,
    body: Value,
}

enum Wake {
    Reply { call: u64, body: Result<String, String> },
    Stop,
    /// A line the worker wrote.
    Line(String),
    /// The worker's stdout closed.
    Eof,
}

struct Exec {
    id: String,
    scope: String,
    actor: String,
    envelope: String,
    manifest: Value,
    accepted_at: Instant,
    updated_at: Instant,
    key_deadline: Instant,
    state: &'static str,
    sequence: u64,
    capabilities: Value,
    /// Snapshot of the originating request; never changed by another client.
    task_form_supported: bool,
    effects_possible: bool,
    input: Option<InputWaiter>,
    limits: Limits,
    cancel: Arc<AtomicBool>,
    wake: Option<mpsc::SyncSender<Wake>>,
    result: Option<Value>,
    retain_until: Option<Instant>,
}

struct InputWaiter {
    form: super::inputs::PendingExport,
    reply: tokio::sync::oneshot::Sender<super::inputs::Resolution>,
}

impl Exec {
    fn terminal(&self) -> bool {
        matches!(self.state, "succeeded" | "failed" | "cancelled")
    }
    fn status(&self, ops: &[Value]) -> Value {
        let pending: Vec<&Value> = ops.iter().filter(|o| !matches!(o["state"].as_str(), Some("succeeded" | "failed" | "cancelled"))).map(|o| &o["operationId"]).collect();
        json!({
            "executionId": self.id,
            "manifest": self.manifest,
            "acceptedAt": wire::timestamp(self.accepted_at),
            "updatedAt": wire::timestamp(self.updated_at),
            "state": self.state,
            "sequence": self.sequence.to_string(),
            "effectiveCapabilities": self.capabilities,
            "effectiveLimits": self.limits.to_json(),
            "cancellationRequested": self.cancel.load(Ordering::Relaxed),
            "acceptedOperations": ops.iter().map(|o| &o["operationId"]).collect::<Vec<_>>(),
            "pendingOperations": pending,
            "retainUntil": self.retain_until.map(wire::timestamp),
        })
    }
}

#[derive(Default)]
struct State {
    execs: HashMap<String, Exec>,
    bindings: HashMap<(String, String), String>,
    journal: Option<super::journal::Journal>,
}

pub struct Executions {
    service: Weak<CadService>,
    state: Mutex<State>,
}

fn reject_unknown(req: &Value, allowed: &[&str]) -> Result<(), ApiError> {
    let obj = req.as_object().ok_or_else(|| ApiError::new("invalid_arguments", "validation", "the request must be an object"))?;
    if let Some(k) = obj.keys().find(|k| !allowed.contains(&k.as_str())) {
        return Err(ApiError::new("invalid_arguments", "validation", format!("unknown field `{k}`")));
    }
    Ok(())
}

impl Executions {
    pub fn new(service: Weak<CadService>) -> Self {
        Executions { service, state: Mutex::new(State::default()) }
    }

    /// Opt in before serving requests. Reopening never starts a worker: an
    /// incomplete admission becomes a terminal reconciliation failure.
    pub fn configure_persistence(&self, directory: &std::path::Path) -> Result<(), String> {
        let mut state = self.state.lock().unwrap();
        if state.journal.is_some() || !state.execs.is_empty() { return Err("configure persistence before admitting executions".into()); }
        let mut journal = super::journal::Journal::open(directory)?;
        for admission in journal.unfinished() {
            let id = &admission.execution_id;
            let error = ApiError::new("reconciliation_required", "recovery", "the server stopped before recording a terminal outcome; inspect document and external state before submitting new work")
                .effects(Effects::unknown()).exec(id);
            let mut recovery = journal.by_id(id, &admission.scope, &admission.actor).unwrap().recovery_evidence();
            recovery["interrupted"] = json!(true);
            journal.finish(id, json!({
                "executionId":id,"state":"failed","sequence":"2","finishedAt":wire::timestamp(Instant::now()),
                "output":null,"error":error.to_json(),
                "operations":[],"pendingOperationIds":[],"artifacts":[],"logArtifact":null,"retainUntil":null,
                "recovery":recovery
            }))?;
        }
        state.journal = Some(journal);
        Ok(())
    }

    fn start_host_call(&self, caller: &Caller, call_id: u64, method: &str) -> Result<bool, String> {
        let mut state = self.state.lock().unwrap();
        if state.journal.is_none() { return Ok(false); }
        let id = caller.execution.as_deref().ok_or("bridge call without execution")?;
        // The dispatcher owns caller identity. Re-check cancellation while
        // holding the same lock used by cancellation and terminal completion.
        let execution = state.execs.get(id).ok_or("execution no longer active")?;
        if execution.terminal() || execution.cancel.load(Ordering::Relaxed) { return Err("execution stopped before call admission".into()); }
        let intent = state.journal.as_mut().unwrap().start_call(id, call_id, method)?;
        // The intent's sync runs with the lock released: another execution's
        // admission, call or status read does not wait on this disk write.
        drop(state);
        if let Err(error) = intent.sync() {
            if let Some(journal) = self.state.lock().unwrap().journal.as_mut() {
                journal.poison();
            }
            return Err(error);
        }
        Ok(true)
    }

    fn finish_host_call(&self, caller: &Caller, call_id: u64, completion: super::journal::CallCompletion) -> Result<(), String> {
        let mut state = self.state.lock().unwrap();
        let id = caller.execution.as_deref().ok_or("bridge call without execution")?;
        state.journal.as_mut().ok_or("execution journal unavailable")?.finish_call(id, call_id, completion)
    }

    pub fn persistent(&self) -> bool { self.state.lock().unwrap().journal.is_some() }

    fn envelope(req: &Value, trusted: bool) -> Result<String, ApiError> {
        if req.to_string().len() > (1 << 20) + (256 << 10) {
            return Err(ApiError::new("resource_limit", "validation", "the submission is larger than the source and input limits"));
        }
        canon::canonical(&json!({
            "manifest":req.get("manifest"),"source":req.get("source"),
            "initialDocuments":req.get("initialDocuments"),"requestedCapabilities":req.get("requestedCapabilities"),
            "limits":req.get("limits"),"trusted":trusted,
        })).map_err(|e| ApiError::new("invalid_arguments", "validation", e))
    }

    fn durable_binding(caller: &Caller, issued: &str, retry: Option<&str>) -> String {
        super::journal::Journal::binding(&caller.scope, &caller.actor, if retry.is_some() { "front-door" } else { "issued" }, retry.unwrap_or(issued))
    }

    fn stored_status(record: &super::journal::Record) -> Value {
        let mut status = record.admission.status.clone();
        if let Some(outcome) = &record.outcome {
            status["state"] = outcome["state"].clone();
            status["sequence"] = outcome["sequence"].clone();
            status["updatedAt"] = outcome["finishedAt"].clone();
            status["pendingOperations"] = outcome["pendingOperationIds"].clone();
            status["acceptedOperations"] = outcome["operations"].as_array().into_iter().flatten().map(|op| op["operationId"].clone()).collect();
            status["retainUntil"] = Value::Null;
        }
        status["persistence"] = json!({"durable":true,"automaticReplay":false});
        status
    }

    fn stored_result(record: &super::journal::Record) -> Result<Value, ApiError> {
        let mut result = record.outcome.clone().ok_or_else(|| ApiError::new("reconciliation_required", "recovery", "durable admission has no terminal outcome").effects(Effects::unknown()))?;
        // Result JSON survives. Artifacts and app handles do not become durable
        // merely because their references occur in a durable result.
        result["hostCallEvidence"] = record.recovery_evidence();
        result["persistence"] = json!({"durable":true,"referencedArtifactsAndHandlesMayBeUnavailable":true,"automaticReplay":false});
        Ok(result)
    }

    fn durable_record<'a>(state: &'a State, caller: &Caller, id: &str) -> Result<Option<&'a super::journal::Record>, ApiError> {
        caller.require(&["execution.read"])?;
        if caller.execution.is_some() { return Ok(None); }
        Ok(state.journal.as_ref().and_then(|journal| journal.by_id(id, &caller.scope, &caller.actor)))
    }

    /// Check durable retries before starting an app session. Admission repeats
    /// this check under its lock, so simultaneous retries cannot race it.
    pub fn replay(&self, caller: &Caller, req: &Value, trusted: bool, retry: Option<&str>) -> Result<Option<Value>, ApiError> {
        let envelope = Self::envelope(req, trusted)?;
        let binding = Self::durable_binding(caller, req["idempotencyKey"].as_str().unwrap_or(""), retry);
        let state = self.state.lock().unwrap();
        self.replay_locked(&state, caller, &binding, &envelope)
    }

    fn replay_locked(&self, state: &State, caller: &Caller, binding: &str, envelope: &str) -> Result<Option<Value>, ApiError> {
        let Some(journal) = &state.journal else { return Ok(None) };
        caller.require(&["execution.read"])?;
        if caller.execution.is_some() { return Err(ApiError::new("capability_denied", "authorization", "programs cannot inspect executions")); }
        let record = journal.by_binding(binding, &canon::sha256_hex(envelope.as_bytes()))
            .map_err(|e| ApiError::new("idempotency_conflict", "admission", e))?;
        let Some(record) = record else { return Ok(None) };
        if let Some(exec) = state.execs.get(&record.admission.execution_id) {
            let service = self.service.upgrade().ok_or_else(|| ApiError::new("host_stopping", "lookup", "the service is stopping"))?;
            return Ok(Some(exec.status(&service.ops.of_execution(&exec.id))));
        }
        Ok(Some(Self::stored_status(record)))
    }

    pub async fn shutdown(&self) {
        {
            for execution in self.state.lock().unwrap().execs.values() {
                if !execution.terminal() {
                    execution.cancel.store(true, Ordering::Relaxed);
                    if let Some(wake) = &execution.wake { let _ = wake.try_send(Wake::Stop); }
                }
            }
        }
        // Let supervisors reap their child processes before the CLI runtime
        // exits; merely setting a flag can otherwise orphan a computing worker.
        let deadline = Instant::now() + Duration::from_secs(5);
        while Instant::now() < deadline {
            if self.state.lock().unwrap().execs.values().all(Exec::terminal) { break; }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    }

    fn sweep(st: &mut State) {
        let now = Instant::now();
        let gone: Vec<String> = st.execs.values().filter(|e| e.retain_until.is_some_and(|t| t <= now)).map(|e| e.id.clone()).collect();
        for id in &gone {
            st.execs.remove(id);
        }
        st.bindings.retain(|_, e| !gone.contains(e));
    }

    pub fn submit(&self, caller: &Caller, req: &Value) -> Result<Value, ApiError> {
        self.submit_as(caller, req, false)
    }

    /// `trusted`: the MCP's own `run` — the program gets the local
    /// caller's whole authority over documents and every app tool, but never
    /// the right to start or inspect executions. Otherwise the requested
    /// grants are intersected with code mode's policy.
    pub fn submit_as(&self, caller: &Caller, req: &Value, trusted: bool) -> Result<Value, ApiError> {
        self.admit(caller, req, trusted, None, None)
    }

    /// The host's own policy: a trusted submission whose limits the HOST sets
    /// (they may exceed the defaults a client can only lower). The test-mcp
    /// runner's script mode, whose gate scripts run up to an hour and drive
    /// hundreds of tool calls.
    pub fn submit_with_limits(&self, caller: &Caller, req: &Value, limits: Limits) -> Result<Value, ApiError> {
        self.admit(caller, req, true, Some(limits), None)
    }

    /// Drop a terminal execution now instead of at its retention deadline,
    /// with the artifacts it made: a host that has read the result and plays
    /// hundreds of programs in one process (the test-mcp runner) would
    /// otherwise reach `MAX_RETAINED`.
    pub fn forget(&self, id: &str) {
        let mut st = self.state.lock().unwrap();
        if st.execs.get(id).is_some_and(Exec::terminal) {
            st.execs.remove(id);
            st.bindings.retain(|_, e| e != id);
            if let Some(service) = self.service.upgrade() {
                service.artifacts.drop_execution(id);
            }
        }
    }

    pub fn submit_with_retry(&self, caller: &Caller, req: &Value, trusted: bool, retry: Option<&str>) -> Result<Value, ApiError> {
        self.admit(caller, req, trusted, None, retry)
    }

    fn admit(&self, caller: &Caller, req: &Value, trusted: bool, host_limits: Option<Limits>, retry: Option<&str>) -> Result<Value, ApiError> {
        // A program is JavaScript and nothing else: the field that once chose
        // a language is refused by name, before a key is bound.
        if req.get("language").is_some() {
            return Err(ApiError::new("invalid_arguments", "validation", "`language` is no longer a field: a program is JavaScript, a plain script body"));
        }
        reject_unknown(req, &["manifest", "source", "initialDocuments", "requestedCapabilities", "limits", "idempotencyKey"])?;
        let key_text = req.get("idempotencyKey").and_then(Value::as_str).ok_or_else(|| ApiError::new("invalid_arguments", "validation", "idempotencyKey is required (cad_issue_key with purpose execution)"))?;
        let envelope = Self::envelope(req, trusted)?;
        let service = self.service.upgrade().ok_or_else(|| ApiError::new("host_stopping", "admission", "the service is stopping"))?;
        let mut st = self.state.lock().unwrap();
        Self::sweep(&mut st);
        let durable_binding = Self::durable_binding(caller, key_text, retry);
        if let Some(status) = self.replay_locked(&st, caller, &durable_binding, &envelope)? { return Ok(status); }
        let key = keys::verify(key_text, &caller.scope, Purpose::Execution)?;
        let binding = (caller.scope.clone(), key.nonce.clone());
        if let Some(id) = st.bindings.get(&binding).cloned() {
            caller.require(&["execution.read"])?;
            let e = &st.execs[&id];
            if e.envelope != envelope {
                return Err(ApiError::new("idempotency_conflict", "admission", "this key was used for a different submission").exec(&id));
            }
            let ops = service.ops.of_execution(&id);
            return Ok(e.status(&ops));
        }
        if key.expired() {
            return Err(ApiError::new("idempotency_expired", "admission", "the key's first-admission window has closed").effects(Effects::unknown()));
        }
        caller.require(&["code.execute", "execution.read"])?;
        let manifest = req.get("manifest").cloned().unwrap_or(Value::Null);
        service.catalogue.check_manifest(&manifest)?;
        let limits = match host_limits {
            Some(limits) => limits,
            None => Limits::lowered(req.get("limits"))?,
        };
        if req.get("initialDocuments").map_or(0, |v| v.to_string().len()) as u64 > limits.input_bytes {
            return Err(ApiError::new("resource_limit", "validation", "initialDocuments exceeds inputBytes"));
        }
        let source = req.get("source").and_then(Value::as_str).ok_or_else(|| ApiError::new("invalid_arguments", "validation", "source is required"))?.to_string();
        if source.len() as u64 > limits.source_bytes {
            return Err(ApiError::new("resource_limit", "validation", format!("source is larger than {} bytes", limits.source_bytes)));
        }
        let mut initial = Vec::new();
        for c in req.get("initialDocuments").and_then(Value::as_array).cloned().unwrap_or_default() {
            initial.push(wire::document_context(&c)?);
        }
        let (grants, capabilities) = if trusted {
            let names: Vec<String> = super::ops::CAPABILITIES
                .iter()
                .filter(|n| !matches!(**n, "code.execute" | "execution.read" | "execution.cancel"))
                .map(|n| n.to_string())
                .collect();
            let listed = Value::Array(names.iter().map(|n| json!({ "name": n })).collect());
            (Grants { names, documents: None, created_documents: true, document_grants: None, created_capabilities: vec![] }, listed)
        } else {
            effective_grants(req.get("requestedCapabilities").unwrap_or(&json!([])), &initial)?
        };
        let active = st.execs.values().filter(|e| !e.terminal());
        let (total, scoped) = active.fold((0, 0), |(t, s), e| (t + 1, s + usize::from(e.scope == caller.scope)));
        if total >= MAX_ACTIVE || scoped >= MAX_ACTIVE_PER_SCOPE || st.execs.len() >= MAX_RETAINED {
            return Err(ApiError::new("overloaded", "admission", "too many executions are running; retry the same key shortly"));
        }
        let id = wire::mint("exec");
        let cancel = Arc::new(AtomicBool::new(false));
        let (wake_tx, wake_rx) = mpsc::sync_channel(32);
        let exec = Exec {
            effects_possible: false,
            id: id.clone(),
            scope: caller.scope.clone(),
            actor: caller.actor.clone(),
            envelope: envelope.clone(),
            manifest: manifest.clone(),
            accepted_at: Instant::now(),
            updated_at: Instant::now(),
            key_deadline: key.deadline,
            state: "queued",
            sequence: 1,
            capabilities,
            task_form_supported: trusted && super::inputs::task_form_supported(),
            input: None,
            limits,
            cancel: cancel.clone(),
            wake: Some(wake_tx.clone()),
            result: None,
            retain_until: None,
        };
        let status = exec.status(&[]);
        if let Some(journal) = &mut st.journal {
            journal.admit(super::journal::Admission { binding: durable_binding, submission: canon::sha256_hex(envelope.as_bytes()),
                execution_id:id.clone(),scope:caller.scope.clone(),actor:caller.actor.clone(),status:status.clone(),bridge_evidence:true })
                .map_err(|e| ApiError::new("persistence_failed", "admission", e).exec(&id).effects(Effects::unknown()))?;
        }
        service.artifacts.set_execution_budget(&id, limits.artifact_count, limits.artifact_bytes);
        st.execs.insert(id.clone(), exec);
        st.bindings.insert(binding, id.clone());
        drop(st);

        let program_caller = Caller { scope: caller.scope.clone(), actor: caller.actor.clone(), execution: Some(id.clone()), grants };
        // The granted names are all a worker is told of the SDK.
        let names = service.script_names(&program_caller);
        let runtime = tokio::runtime::Handle::current();
        let (bridge_tx, bridge_rx) = tokio::sync::mpsc::channel::<BridgeCall>(limits.outstanding_host_calls as usize);
        runtime.spawn(dispatch(service.clone(), program_caller, bridge_rx, wake_tx.clone()));
        let svc = service.clone();
        let exec_id = id.clone();
        let spawned = std::thread::Builder::new()
            .name(format!("brep-code-{}", &id[id.len() - 6..]))
            .spawn(move || {
                let outcome = realm(&svc, &exec_id, names, source, limits, cancel, bridge_tx, wake_tx, wake_rx);
                svc.code.finish(&svc, &exec_id, outcome);
            });
        if let Err(error) = spawned {
            self.finish(&service, &id, Outcome { result: Err(ApiError::new("internal_error", "admission", error.to_string())), logs: vec![] });
            return Err(ApiError::new("internal_error", "admission", error.to_string()).exec(&id));
        }
        Ok(status)
    }

    fn set_state(&self, id: &str, state: &'static str) {
        if let Some(e) = self.state.lock().unwrap().execs.get_mut(id) {
            let state = if e.input.is_some() { "input_required" } else { state };
            if !e.terminal() && e.state != state {
                e.state = state;
                e.updated_at = Instant::now();
                e.sequence += 1;
            }
        }
    }

    fn finish(&self, service: &CadService, id: &str, outcome: Outcome) {
        let ops = service.ops.of_execution(id);
        let pending: Vec<Value> = ops.iter().filter(|o| !matches!(o["state"].as_str(), Some("succeeded" | "failed" | "cancelled"))).map(|o| o["operationId"].clone()).collect();
        let (state, output, mut error) = match outcome.result {
            Ok(v) => ("succeeded", Some(v), None),
            Err(e) => (if e.code == "cancelled" { "cancelled" } else { "failed" }, None, Some(e)),
        };
        // Success requires every accepted operation to be terminal: unawaited
        // work is a failed execution that names it, never a hidden success.
        let (mut state, mut output) = if state == "succeeded" && !pending.is_empty() {
            error = Some(ApiError::new("invalid_arguments", "execution", format!("the program returned with {} accepted operation(s) still running; await them (sdk.operations.result with wait_ms)", pending.len())));
            ("failed", None)
        } else {
            (state, output)
        };
        let mut st = self.state.lock().unwrap();
        let Some(e) = st.execs.get_mut(id) else { return };
        if let Some(input) = e.input.take() {
            let _ = input.reply.send(super::inputs::Resolution::Cancelled);
            if state == "succeeded" {
                state = "failed"; output = None;
                error = Some(ApiError::new("invalid_arguments", "execution", "the program returned with an input request still pending; await sdk.inputs.exportOptions"));
            }
        }
        // Script failure is not a rollback. Raw tool calls and accepted operations
        // may have committed before the worker failed or lost its reply.
        if e.effects_possible {
            if let Some(error) = &mut error { error.effects = Effects::unknown(); error.retry = "inspect_then_new_submission"; }
        }
        service.event("execution_terminal", Some(id), Some(state), error.as_ref().map(|e| e.code), None);
        let now = Instant::now();
        e.state = state;
        e.updated_at = now;
        e.sequence += 1;
        e.wake = None;
        e.retain_until = Some((now + super::ops::RETENTION).max(e.key_deadline));
        let log = if outcome.logs.is_empty() {
            Value::Null
        } else {
            service
                .artifacts
                .create(super::artifacts::Owner { scope: e.scope.clone(), execution: Some(id.to_string()) }, "text/plain", outcome.logs.join("\n").into_bytes())
                .unwrap_or(Value::Null)
        };
        e.result = Some(json!({
            "executionId": id,
            "state": state,
            "sequence": e.sequence.to_string(),
            "finishedAt": wire::timestamp(now),
            "output": output,
            "error": error.map(|x| x.exec(id).to_json()),
            "operations": ops,
            "pendingOperationIds": pending,
            "artifacts": service.artifacts.owned_by(&e.scope, id),
            "logArtifact": log,
            "retainUntil": e.retain_until.map(wire::timestamp),
        }));
        let result = e.result.clone().unwrap();
        if let Some(journal) = &mut st.journal {
            if let Err(error) = journal.finish(id, result) {
                let e = st.execs.get_mut(id).unwrap();
                e.state = "failed";
                let result = e.result.as_mut().unwrap();
                result["state"] = json!("failed");
                result["error"] = ApiError::new("persistence_failed", "completion", error).effects(Effects::unknown()).exec(id).to_json();
                result["output"] = Value::Null;
            }
        }
    }

    fn lookup<'a>(st: &'a mut State, caller: &Caller, id: &str) -> Result<&'a mut Exec, ApiError> {
        caller.require(&["execution.read"])?;
        match wire::handle_shape("exec", id) {
            wire::HandleShape::Current => {}
            wire::HandleShape::OtherEpoch => return Err(ApiError::new("handle_epoch_mismatch", "lookup", "the execution is from an earlier run of the server").effects(Effects::unknown())),
            wire::HandleShape::Malformed => return Err(ApiError::new("invalid_arguments", "validation", "executionId is not an execution handle")),
        }
        Self::sweep(st);
        let unknown = || ApiError::new("execution_unknown", "lookup", "no retained execution has that id").effects(Effects::unknown());
        let e = st.execs.get_mut(id).ok_or_else(unknown)?;
        if e.scope != caller.scope || e.actor != caller.actor || caller.execution.is_some() {
            return Err(unknown());
        }
        Ok(e)
    }

    pub fn status(&self, caller: &Caller, req: &Value) -> Result<Value, ApiError> {
        reject_unknown(req, &["executionId"])?;
        let id = req.get("executionId").and_then(Value::as_str).unwrap_or_default();
        let service = self.service.upgrade().ok_or_else(|| ApiError::new("host_stopping", "lookup", "the service is stopping"))?;
        let mut st = self.state.lock().unwrap();
        Self::sweep(&mut st);
        if !st.execs.contains_key(id) {
            if let Some(record) = Self::durable_record(&st, caller, id)? { return Ok(Self::stored_status(record)); }
        }
        let e = Self::lookup(&mut st, caller, id)?;
        // A terminal status is the immutable snapshot taken when it ended.
        if let Some(r) = &e.result {
            let mut s = e.status(r["operations"].as_array().map(Vec::as_slice).unwrap_or(&[]));
            s["pendingOperations"] = r["pendingOperationIds"].clone();
            return Ok(s);
        }
        let ops = service.ops.of_execution(id);
        Ok(e.status(&ops))
    }

    pub fn result(&self, caller: &Caller, req: &Value) -> Result<Value, ApiError> {
        reject_unknown(req, &["executionId"])?;
        let id = req.get("executionId").and_then(Value::as_str).unwrap_or_default();
        let mut st = self.state.lock().unwrap();
        Self::sweep(&mut st);
        if !st.execs.contains_key(id) {
            if let Some(record) = Self::durable_record(&st, caller, id)? { return Self::stored_result(record); }
        }
        let e = Self::lookup(&mut st, caller, id)?;
        e.result.clone().ok_or_else(|| ApiError::new("not_ready", "lookup", format!("the execution is {}", e.state)).exec(id))
    }

    /// Execution-only cancellation: closes the bridge and stops the program
    /// at its next interrupt check. It never cancels accepted operations.
    pub fn cancel(&self, caller: &Caller, req: &Value) -> Result<Value, ApiError> {
        reject_unknown(req, &["executionId"])?;
        caller.require(&["execution.cancel"])?;
        let id = req.get("executionId").and_then(Value::as_str).unwrap_or_default();
        let service = self.service.upgrade().ok_or_else(|| ApiError::new("host_stopping", "lookup", "the service is stopping"))?;
        let mut st = self.state.lock().unwrap();
        Self::sweep(&mut st);
        if !st.execs.contains_key(id) {
            if let Some(record) = Self::durable_record(&st, caller, id)? { return Ok(Self::stored_status(record)); }
        }
        let e = Self::lookup(&mut st, caller, id)?;
        if e.terminal() {
            drop(st);
            return self.status(caller, req);
        }
        if !e.cancel.swap(true, Ordering::Relaxed) {
            if let Some(mut input) = e.input.take() {
                let resolution = input.form.cancel(Instant::now()).clone();
                let _ = input.reply.send(resolution);
            }
            e.updated_at = Instant::now();
            e.sequence += 1;
            service.event("cancel_requested", Some(id), Some(e.state), None, Some(e.sequence));
            if let Some(w) = &e.wake {
                let _ = w.try_send(Wake::Stop); // the atomic flag remains authoritative when the mailbox is full
            }
        }
        let ops = service.ops.of_execution(id);
        Ok(e.status(&ops))
    }

    /// Exposes only the requests owned by an externally addressable execution.
    pub(crate) fn input_requests(&self, caller: &Caller, id: &str) -> Result<rmcp::model::InputRequests, ApiError> {
        let mut state = self.state.lock().unwrap();
        let e = Self::lookup(&mut state, caller, id)?;
        Self::expire_input(e, Instant::now());
        match &mut e.input {
            Some(input) => input.form.input_requests(Instant::now()).map_err(|message| ApiError::new("internal_error", "input", message)),
            None => Ok(Default::default()),
        }
    }

    fn expire_input(e: &mut Exec, now: Instant) {
        let resolved = e.input.as_mut().and_then(|input| input.form.resolution(now).cloned());
        if let Some(resolved) = resolved {
            let input = e.input.take().unwrap();
            let _ = input.reply.send(resolved);
            e.state = "waiting"; e.updated_at = now; e.sequence += 1;
        }
    }

    pub(crate) fn update_input(&self, caller: &Caller, id: &str, responses: &rmcp::model::InputResponses) -> Result<(), ApiError> {
        let mut state = self.state.lock().unwrap();
        let e = Self::lookup(&mut state, caller, id)?;
        Self::expire_input(e, Instant::now());
        if e.cancel.load(Ordering::Relaxed) || e.terminal() || responses.len() != 1 {
            return Err(ApiError::new("invalid_arguments", "input", "update requires exactly one outstanding input request on a live execution"));
        }
        let input = e.input.as_mut().ok_or_else(|| ApiError::new("invalid_arguments", "input", "execution has no outstanding input request"))?;
        let (request_id, response) = responses.iter().next().unwrap();
        let resolved = input.form.respond(request_id, response, Instant::now())
            .map_err(|message| ApiError::new("invalid_arguments", "input", message))?.clone();
        let input = e.input.take().unwrap();
        let _ = input.reply.send(resolved);
        e.state = "waiting"; e.updated_at = Instant::now(); e.sequence += 1;
        Ok(())
    }

    pub(crate) async fn export_options(&self, caller: &Caller, request: &Value) -> Result<Value, ApiError> {
        use super::inputs::{ExportForm, PendingExport, Resolution};
        let invalid = |message| ApiError::new("invalid_arguments", "input", message);
        let service = self.service.upgrade().ok_or_else(|| invalid("service is stopping".into()))?;
        let descriptor = service.describe(&["document.export".into()]).await?;
        let formats = descriptor["methods"][0]["inputSchema"]["properties"]["format"]["enum"].as_array()
            .ok_or_else(|| invalid("export format catalogue is unavailable".into()))?
            .iter().map(|value| value.as_str().map(str::to_owned).ok_or_else(|| invalid("invalid export format catalogue".into())))
            .collect::<Result<Vec<_>, _>>()?;
        let form = ExportForm::new(request, formats).map_err(invalid)?;
        if let Some(options) = form.complete() { return Ok(json!({"format":options.format,"path":options.path})); }
        let id = caller.execution.as_deref().ok_or_else(|| invalid("exportOptions requires a script execution".into()))?;
        let (mut receiver, deadline) = {
            let mut state = self.state.lock().unwrap();
            let e = state.execs.get_mut(id).filter(|e| e.scope == caller.scope && e.actor == caller.actor)
                .ok_or_else(|| invalid("execution is unavailable".into()))?;
            if !e.task_form_supported {
                return Err(ApiError::new("input_required", "input", "Supply format and path explicitly, or start the program with wait_ms: 0 from a client supporting modern Tasks and form elicitation to request missing export options"));
            }
            if e.terminal() || e.cancel.load(Ordering::Relaxed) || e.input.is_some() {
                return Err(invalid("execution is terminal, cancelled or already waiting for input".into()));
            }
            let now = Instant::now();
            let pending = PendingExport::new(wire::mint("input"), form, now, e.accepted_at + Duration::from_millis(e.limits.wall_ms)).map_err(invalid)?;
            let deadline = pending.deadline();
            let (reply, receiver) = tokio::sync::oneshot::channel();
            e.input = Some(InputWaiter { form: pending, reply });
            e.state = "input_required"; e.updated_at = now; e.sequence += 1;
            (receiver, deadline)
        };
        let result = tokio::select! {
            result = &mut receiver => result,
            _ = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)) => {
                {
                    let mut state = self.state.lock().unwrap();
                    if let Some(e) = state.execs.get_mut(id) { Self::expire_input(e, Instant::now()); }
                }
                receiver.await
            }
        };
        match result.unwrap_or(Resolution::Cancelled) {
            Resolution::Accepted(options) => Ok(json!({"format":options.format,"path":options.path})),
            Resolution::Declined => Err(ApiError::new("input_declined", "input", "export choices were declined; no export was performed")),
            Resolution::Cancelled => Err(ApiError::new("cancelled", "input", "export input was cancelled; no export was performed")),
            Resolution::Expired => Err(ApiError::new("input_expired", "input", "export input expired; supply format and path explicitly or start a new request")),
        }
    }
}

/// What the realm thread hands back.
struct Outcome {
    result: Result<Value, ApiError>,
    logs: Vec<String>,
}

/// The bridge's host side: each call is served on the tokio runtime under
/// the execution's narrowed caller, and its reply is posted to the realm's
/// mailbox as owned JSON.
async fn dispatch(service: Arc<CadService>, caller: Caller, mut rx: tokio::sync::mpsc::Receiver<BridgeCall>, wake: mpsc::SyncSender<Wake>) {
    while let Some(call) = rx.recv().await {
        let service = service.clone();
        let caller = caller.clone();
        let wake = wake.clone();
        // The execution is the client: its calls keep their order in the
        // app's queue, and another execution's need not wait behind them.
        let client = caller.execution.as_deref().map(crate::host::client_of);
        tokio::spawn(crate::host::with_client(client, async move {
            let id = call.call;
            let body = serve_recorded(service.clone(), caller, call).await;
            // A realm that has gone away simply never reads this.
            let mut reply = Wake::Reply { call: id, body };
            loop {
                match wake.try_send(reply) {
                    Ok(()) => break,
                    Err(mpsc::TrySendError::Full(value)) => {
                        reply = value;
                        tokio::time::sleep(Duration::from_millis(5)).await;
                    }
                    Err(mpsc::TrySendError::Disconnected(_)) => {
                        service.event("late_reply_discarded", None, None, None, None);
                        break;
                    }
                }
            }
        }));
    }
}

/// Journal IO runs off the async executor. Once admitted, a host call may
/// finish after cancellation; its reply is still recorded as an observation.
async fn serve_recorded(service: Arc<CadService>, caller: Caller, call: BridgeCall) -> Result<String, String> {
    if !service.code.persistent() {
        return serve(&service, &caller, &call.method, call.body).await;
    }
    // Persist only a name this caller may call, never arbitrary worker-controlled text.
    let method = if service.script_known(&caller, &call.method).await { call.method.clone() } else { "unknown".into() };
    let recording_service = service.clone(); let recording_caller = caller.clone(); let call_id = call.call;
    tokio::task::spawn_blocking(move || recording_service.code.start_host_call(&recording_caller, call_id, &method))
        .await.map_err(|_| "host-call admission recorder failed")??;
    let body = serve(&service, &caller, &call.method, call.body).await;
    let completion = call_observation(&body);
    tokio::task::spawn_blocking(move || service.code.finish_host_call(&caller, call_id, completion))
        .await.map_err(|_| "host-call completion recorder failed; effects unknown")??;
    body
}

fn call_observation(body: &Result<String, String>) -> super::journal::CallCompletion {
    let value = body.as_ref().ok().and_then(|s| serde_json::from_str::<Value>(s).ok());
    let ok = value.as_ref().and_then(|v| v["ok"].as_bool());
    let operation = value.as_ref().and_then(|v| {
        let observation = if ok == Some(true) { &v["value"] } else { &v["error"] };
        let id = observation["operationId"].as_str()?;
        if !id.is_ascii() || wire::handle_shape("op", id) == wire::HandleShape::Malformed { return None; }
        let state = observation["state"].as_str().filter(|s| matches!(*s, "queued" | "running" | "evaluating" | "committing" | "succeeded" | "failed" | "cancelled")).map(str::to_owned);
        let effects = observation["effects"]["disposition"].as_str().filter(|s| matches!(*s, "none" | "committed" | "unknown" | "partial")).map(str::to_owned);
        Some(super::journal::OperationObservation { operation_id:id.into(),state,effects })
    });
    super::journal::CallCompletion {reply_received:body.is_ok(),ok,operation}
}

/// One script call, `sdk.<method>(body)`: a registry tool's own handler or a
/// service function (`cad::surface`), under the execution's narrowed caller.
/// The answer is the service's `{ok, value}` or `{ok: false, error}` record
/// as JSON text, which the worker's host relays as the call's reply.
async fn serve(service: &CadService, caller: &Caller, method: &str, body: Value) -> Result<String, String> {
    Ok(wire::respond(service.script_call(caller, method, body).await).to_string())
}

/// The hidden argument a host binary starts ITSELF with to be a code
/// worker: every shipped app is one executable, so it is its own worker.
pub const WORKER_FLAG: &str = "--brep-code-worker";

static SELF_WORKER: AtomicBool = AtomicBool::new(false);

/// Call first thing in a host binary's `main`. Started with [`WORKER_FLAG`],
/// this process IS a code worker: it runs the execution and answers true
/// (return from `main`). Otherwise it registers this executable as the
/// worker the code-mode host spawns, and answers false.
pub fn worker_entry() -> bool {
    if std::env::args().nth(1).as_deref() == Some(WORKER_FLAG) {
        brep_script_core::worker::main();
        return true;
    }
    SELF_WORKER.store(true, Ordering::Relaxed);
    false
}

/// The executable a code worker is spawned from (with [`WORKER_FLAG`]):
/// `BREP_CODE_WORKER` (any binary that calls [`worker_entry`]), else this
/// process's own executable when its `main` called [`worker_entry`].
fn worker_path() -> Option<std::path::PathBuf> {
    if let Some(p) = std::env::var_os("BREP_CODE_WORKER").map(std::path::PathBuf::from).filter(|p| p.is_file()) {
        return Some(p);
    }
    if SELF_WORKER.load(Ordering::Relaxed) {
        return std::env::current_exe().ok();
    }
    None
}

/// The worker's CPU time and resident memory, from `/proc` (Linux).
/// `None` where the platform does not say — then only the halt and the wall
/// deadline bound the worker.
fn usage(pid: u32) -> Option<(Duration, u64)> {
    let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    let fields: Vec<&str> = stat.rsplit(')').next()?.split_whitespace().collect();
    let ticks = |i: usize| fields.get(i).and_then(|v| v.parse::<u64>().ok());
    let cpu = Duration::from_millis((ticks(11)? + ticks(12)?) * 10);
    let status = std::fs::read_to_string(format!("/proc/{pid}/status")).ok()?;
    let rss = status.lines().find(|l| l.starts_with("VmRSS:"))?.split_whitespace().nth(1)?.parse::<u64>().ok()? * 1024;
    Some((cpu, rss))
}

/// A host call's reply on the wire, `{call, ok, value}` or `{call, ok: false,
/// error}`: the service's `{ok, …}` record (JSON object text) with the call's
/// id in front, spliced rather than parsed again (a reply can be megabytes).
fn reply_line(call: u64, response: &str) -> String {
    match response.strip_prefix('{') {
        Some(rest) if rest.len() > 1 => format!("{{\"call\":{call},{rest}"),
        _ => format!("{{\"call\":{call},\"ok\":false,\"error\":{}}}", ApiError::new("internal_error", "execution", "the host's reply was not a response record").to_json()),
    }
}

#[allow(clippy::too_many_arguments)]
fn realm(
    service: &CadService,
    id: &str,
    names: Vec<String>,
    source: String,
    limits: Limits,
    cancel: Arc<AtomicBool>,
    bridge: tokio::sync::mpsc::Sender<BridgeCall>,
    wake_tx: mpsc::SyncSender<Wake>,
    wake: mpsc::Receiver<Wake>,
) -> Outcome {
    let wall_deadline = Instant::now() + Duration::from_millis(limits.wall_ms);
    let fail = |e: ApiError| Outcome { result: Err(e), logs: vec![] };
    let Some(exe) = worker_path() else {
        return fail(ApiError::new("internal_error", "execution", "this host cannot start a code worker: its main did not call cad::code::worker_entry (or set BREP_CODE_WORKER)"));
    };
    let mut child = match std::process::Command::new(&exe)
        .arg(WORKER_FLAG)
        .env_clear()
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => return fail(ApiError::new("internal_error", "execution", format!("the code worker did not start: {e}"))),
    };
    let pid = child.id();
    let mut stdin = child.stdin.take().expect("piped");
    let stdout = child.stdout.take().expect("piped");
    // Pipe writes must never run on the supervisor: a worker doing compute
    // need not read stdin, but its deadline and halt must still be enforced.
    let (write_tx, write_rx) = mpsc::sync_channel::<String>(8);
    let writer = std::thread::spawn(move || {
        while let Ok(line) = write_rx.recv() {
            if writeln!(stdin, "{line}").and_then(|()| stdin.flush()).is_err() { break; }
        }
    });
    let reader = {
        let tx = wake_tx.clone();
        std::thread::spawn(move || {
            let mut input = std::io::BufReader::new(stdout);
            loop {
                let mut line = String::new();
                let read = std::io::Read::take(&mut input, (2 << 20) + 1).read_line(&mut line);
                if !matches!(read, Ok(n) if n > 0) { break; }
                if line.len() > 2 << 20 || !line.ends_with('\n') { break; }
                if tx.send(Wake::Line(line)).is_err() { break; }
            }
            let _ = tx.send(Wake::Eof);
        })
    };
    // All a worker is told: the names it may call, its limits, the program.
    let start = json!({ "names": names, "limits": limits.to_json(), "source": source });
    if write_tx.try_send(start.to_string()).is_err() {
        let _ = child.kill();
        let _ = child.wait();
        return fail(ApiError::new("internal_error", "execution", "the code worker closed its input"));
    }
    service.code.set_state(id, "running");

    let mut logs: Vec<String> = Vec::new();
    let (mut log_bytes, mut truncated) = (0usize, false);
    let mut outstanding: HashMap<u64, usize> = HashMap::new();
    let mut in_flight_bytes = 0u64;
    let kill = |child: &mut std::process::Child| {
        let _ = child.kill();
        let _ = child.wait();
    };
    let result = loop {
        let w = match wake.recv_timeout(Duration::from_millis(20)) {
            Ok(w) => Some(w),
            Err(mpsc::RecvTimeoutError::Timeout) => None,
            Err(mpsc::RecvTimeoutError::Disconnected) => break Err(ApiError::new("internal_error", "execution", "the host bridge closed")),
        };
        // The host's own checks, every turn: halt, wall, CPU, memory.
        if matches!(w, Some(Wake::Stop)) || cancel.load(Ordering::Relaxed) {
            kill(&mut child);
            break Err(ApiError::new("cancelled", "execution", "the execution was halted; its accepted operations continue"));
        }
        if Instant::now() > wall_deadline {
            kill(&mut child);
            break Err(ApiError::new("deadline_exceeded", "execution", format!("the execution ran longer than {} ms", limits.wall_ms)));
        }
        if let Some((cpu, rss)) = usage(pid) {
            if cpu > Duration::from_millis(limits.js_cpu_ms) {
                kill(&mut child);
                break Err(ApiError::new("resource_limit", "execution", format!("the program used more than {} ms of JS compute", limits.js_cpu_ms)));
            }
            if rss > limits.js_heap_bytes {
                kill(&mut child);
                break Err(ApiError::new("resource_limit", "execution", format!("out of memory: the program's worker passed {} bytes", limits.js_heap_bytes)));
            }
        }
        let Some(w) = w else { continue };
        match w {
            Wake::Line(line) => {
                let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };
                if let Some(text) = msg.get("log").and_then(Value::as_str) {
                    let text = wire::bounded(text.to_string(), 2048);
                    if log_bytes + text.len() <= limits.log_bytes as usize {
                        log_bytes += text.len();
                        logs.push(text);
                    } else if !truncated {
                        truncated = true;
                        logs.push("[console output truncated at the log limit]".into());
                    }
                } else if let Some(done) = msg.get("done") {
                    let _ = child.wait();
                    break match done.get("ok") {
                        Some(v) if v.to_string().len() as u64 > limits.result_bytes => {
                            Err(ApiError::new("resource_limit", "execution", format!("the program's result is larger than {} bytes", limits.result_bytes)))
                        }
                        Some(v) => Ok(v.clone()),
                        None => {
                            let code = done["error"]["code"].as_str().unwrap_or("script_failed");
                            let code = match code {
                                "compile_failed" => "compile_failed",
                                "invalid_arguments" => "invalid_arguments",
                                "job_failed" => "job_failed",
                                "internal_error" => "internal_error",
                                "resource_limit" => "resource_limit",
                                _ => "script_failed",
                            };
                            let phase = if code == "compile_failed" { "compilation" } else { "execution" };
                            Err(ApiError::new(code, phase, wire::sanitize(done["error"]["message"].as_str().unwrap_or("the program failed"))))
                        }
                    };
                } else if let (Some(call), Some(method)) = (msg.get("call").and_then(Value::as_u64), msg.get("method").and_then(Value::as_str)) {
                    // The bridge's bounds, before the host sees the call. A
                    // call is measured as the message that carried it.
                    let size = line.trim_end().len();
                    let refusal = if size > 1 << 20 {
                        Some("a host message may be at most 1 MiB")
                    } else if in_flight_bytes + size as u64 > limits.bridge_bytes {
                        Some("the bridge's resident payload limit is reached")
                    } else if outstanding.len() as u64 >= limits.outstanding_host_calls {
                        Some("too many host calls are outstanding")
                    } else {
                        None
                    };
                    let refused = match refusal {
                        Some(why) => Some(ApiError::new("resource_limit", "execution", why)),
                        None => match bridge.try_send(BridgeCall { call, method: method.to_string(), body: msg.get("body").cloned().unwrap_or_else(|| json!({})) }) {
                            Ok(()) => {
                                // Mark before consuming a terminal worker message: queued
                                // host work can outlive that worker and its response.
                                if super::surface::effects_possible(method) {
                                    if let Some(execution) = service.code.state.lock().unwrap().execs.get_mut(id) {
                                        execution.effects_possible = true;
                                    }
                                }
                                outstanding.insert(call, size);
                                in_flight_bytes += size as u64;
                                None
                            }
                            Err(_) => Some(ApiError::new("resource_limit", "execution", "the host bridge is full")),
                        },
                    };
                    if let Some(error) = refused {
                        if write_tx.try_send(reply_line(call, &wire::fail(&error).to_string())).is_err() {
                            break Err(ApiError::new("resource_limit", "execution", "worker reply queue is full"));
                        }
                    } else if outstanding.len() == 1 {
                        service.code.set_state(id, "waiting");
                    }
                }
            }
            Wake::Reply { call, body } => {
                if let Some(sent) = outstanding.remove(&call) {
                    in_flight_bytes = in_flight_bytes.saturating_sub(sent as u64);
                }
                let body = body.unwrap_or_else(|e| wire::fail(&ApiError::new("internal_error", "execution", e)).to_string());
                if body.len() as u64 > limits.bridge_bytes || write_tx.try_send(reply_line(call, &body)).is_err() {
                    break Err(ApiError::new("resource_limit", "execution", "worker reply exceeds the bridge budget or its queue is full"));
                }
                service.code.set_state(id, "running");
            }
            Wake::Eof => {
                let status = child.wait().ok();
                break Err(ApiError::new("internal_error", "execution", format!("the code worker ended without an answer ({status:?})")));
            }
            Wake::Stop => unreachable!("handled above"),
        }
    };
    // The bridge closes first: unaccepted calls are dropped, accepted
    // operations stay the service's; a late reply lands in a mailbox nobody reads.
    drop(bridge);
    kill(&mut child);
    drop(write_tx);
    drop(wake);
    let _ = writer.join();
    let _ = reader.join();
    Outcome { result, logs }
}