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
//! The native host's side of the script namespace (`sdk.<namespace>.<action>`,
//! [`crate::script_sdk`]): the service functions this server adds to the
//! registry's tools, and the two hooks a code worker's host calls:
//!
//! - [`CadService::script_names`]: the names a caller is granted, which is
//!   all a worker is told (it is sent no SDK source);
//! - [`CadService::script_call`]: one call, by name, under that caller.
//!
//! A registry tool runs its own handler, the very code path the tool has
//! always taken. A service function is this module's: the operation
//! lifecycle, documents by identity, artifacts, queries and input requests.
//! Each answers its value; a failure is the contract's `ApiError`, which the
//! worker throws in the program.
use super::catalogue::{artifact_ref, context_schema, document_info, obj};
use super::ops::Caller;
use super::wire::{ApiError, Effects};
use super::CadService;
use crate::script_sdk::{Guide, ServiceEntry, Surface, Target};
use crate::tools::{ToolSet, ToolSpec};
use serde_json::{json, Value};
use std::time::Duration;

/// The largest reply handed to a program: well under a worker's heap once
/// parsed into JavaScript values.
const MAX_REPLY: usize = 12 << 20;

/// How long `sdk.operations.result` may wait for a terminal result.
const MAX_RESULT_WAIT_MS: u64 = 600_000;

fn open(props: Value, required: &[&str]) -> Value {
    json!({ "type": "object", "properties": props, "required": required, "additionalProperties": true })
}

fn text() -> Value {
    json!({ "type": "string" })
}

fn count() -> Value {
    json!({ "type": "integer", "minimum": 0 })
}

/// The service functions, by `sdk.<namespace>.<action>`: the old `cad.*`
/// service merged into the one namespace (contract ยง3).
pub fn service_entries(catalogue: &super::catalogue::Catalogue) -> Vec<ServiceEntry> {
    let mut info = document_info();
    info["properties"]["busy"] = json!({ "type": "boolean", "description": "an accepted operation on this document has not finished" });
    let nullable = |schema: Value| json!({ "anyOf": [schema, { "type": "null" }] });
    let manifest = || json!({ "type": "object", "description": "Optional: this server's manifest identity is used when omitted." });
    let retention = open(json!({ "scope": text(), "epoch": text(), "retainUntil": nullable(text()), "terminalRetentionMs": count(), "artifactRetentionMs": count() }), &["scope", "epoch"]);
    let admission = |extra: Value, required: &[&str]| {
        let mut props = json!({ "operationId": text(), "acceptedAt": text(), "context": nullable(context_schema()), "state": { "enum": ["queued", "running", "evaluating", "committing", "succeeded", "failed", "cancelled"] }, "sequence": text(), "retention": retention.clone() });
        for (k, v) in extra.as_object().cloned().unwrap_or_default() { props[k] = v; }
        let mut all = vec!["operationId", "acceptedAt", "context", "state", "sequence", "retention"];
        all.extend_from_slice(required);
        open(props, &all)
    };
    let status = admission(json!({
        "command": text(),
        "cancellation": obj(json!({ "requested": { "type": "boolean" }, "effectiveNow": { "type": "boolean" }, "nonPreemptible": { "type": "boolean" } }), &["requested", "effectiveNow", "nonPreemptible"]),
        "progress": open(json!({ "stage": text(), "summary": text() }), &["stage", "summary"]),
    }), &["command", "cancellation", "progress"]);
    // What `document.create` answers: the new document, and the operation
    // that made it (a durable journal records a call's operation from these).
    let mut created = document_info();
    created["properties"]["operationId"] = text();
    created["properties"]["state"] = json!({ "const": "succeeded" });
    created["properties"]["effects"] = json!({ "type": "object", "description": "the operation's effects: disposition and the documents it changed" });
    created["required"] = json!(["context", "title", "lifecycle", "dirty", "operationId", "state", "effects"]);
    let step = json!({ "const": "model/step" });
    let export = catalogue.get("cad.inputs.exportOptions").expect("the catalogue declares cad.inputs.exportOptions");
    // The catalogue's commands are not script functions (they take a
    // document context and run as operations): what each takes and answers
    // is said where a program submits one, from the command's own schemas.
    let commands = |execution: &str| -> String {
        catalogue.descriptors.iter().filter(|d| d.execution == execution).map(|d| {
            format!(" `{}`: {} args {} -> output {}.", d.path, d.summary.trim_end_matches('.'), crate::declarations::ts_type(&d.input_schema), crate::declarations::ts_type(&d.output_schema))
        }).collect()
    };
    let entry = |namespace, action, doc: &str, input_schema, output_schema, grants: &[&'static str], read_only| ServiceEntry { namespace, action, method: "", doc: doc.to_string(), input_schema, output_schema, grants: grants.to_vec(), read_only, destructive: false };
    let mut entries = vec![
        entry("document", "list",
            "The open documents this program may read, each with its context ({documentId, expectedRevision}), title, lifecycle, dirty and busy.",
            obj(json!({}), &[]), obj(json!({ "documents": { "type": "array", "items": info.clone() } }), &["documents"]), &["document.read"][..], true),
        entry("document", "get",
            "One open document by its identity: its current context, title, lifecycle, dirty and busy.",
            obj(json!({ "documentId": text() }), &["documentId"]), info.clone(), &["document.read"][..], true),
        entry("document", "create",
            "Create a new, empty millimetre part document behind the visible one and wait for it. Answers its DocumentInfo (its `context` is what the next write names) with the operation that made it: operationId, state and effects. One accepted operation, start to finish.",
            catalogue.get("cad.documents.create").expect("the catalogue declares cad.documents.create").input_schema.clone(), created, &["document.create", "operation.read"][..], false),
        entry("document", "bind",
            "Check a document context: answers the document's DocumentInfo when it is open at exactly that revision, and fails with revision_conflict (carrying the current context) when it has moved on. It changes nothing.",
            context_schema(), info, &["document.read"][..], true),
        entry("artifacts", "read",
            "Read a chunk of an artifact's bytes as base64 (offset defaults to 0; limit to the default chunk).",
            obj(json!({ "artifactId": text(), "offset": count(), "limit": { "type": "integer", "minimum": 1 } }), &["artifactId"]),
            obj(json!({ "artifact": artifact_ref(), "offset": count(), "bytesBase64": text(), "eof": { "type": "boolean" } }), &["artifact", "offset", "bytesBase64", "eof"]), &["artifact.read"][..], true),
        entry("artifacts", "create",
            "Create a STEP artifact from bytes (bytesBase64) or, for the local user, from a file on the host (path): exactly one of the two.",
            obj(json!({ "mediaType": step.clone(), "bytesBase64": text(), "path": text() }), &["mediaType"]), artifact_ref(), &["artifact.write"][..], false),
        entry("artifacts", "begin",
            "Start a chunked upload of a STEP artifact larger than one request: its byte length and SHA-256. Answers the uploadId and the largest chunk.",
            obj(json!({ "mediaType": step, "byteLength": count(), "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" } }), &["mediaType", "byteLength", "sha256"]),
            obj(json!({ "uploadId": text(), "maxChunkBytes": count(), "expiresAt": text() }), &["uploadId", "maxChunkBytes", "expiresAt"]), &["artifact.write"][..], false),
        entry("artifacts", "append",
            "Append the next chunk of an upload; offset is where the upload stands.",
            obj(json!({ "uploadId": text(), "offset": count(), "bytesBase64": text() }), &["uploadId", "offset", "bytesBase64"]),
            obj(json!({ "uploadId": text(), "received": count(), "byteLength": count() }), &["uploadId", "received", "byteLength"]), &["artifact.write"][..], false),
        entry("artifacts", "commit",
            "Finish an upload: the bytes must be exactly the declared length and digest. Answers the artifact.",
            obj(json!({ "uploadId": text() }), &["uploadId"]), artifact_ref(), &["artifact.write"][..], false),
        entry("operations", "issueKey",
            "Issue an idempotency key for one command submission. A lost reply is recovered by resubmitting the SAME key and request.",
            obj(json!({ "purpose": { "const": "command", "default": "command" } }), &[]),
            obj(json!({ "key": text(), "firstAdmissionExpiresAt": text() }), &["key", "firstAdmissionExpiresAt"]), &["operation.read"][..], false),
        entry("operations", "submit",
            &format!("Submit one catalogue command as an operation. `context` is the document it acts on, {{documentId, expectedRevision}} (null for cad.documents.create); a write answers the document's new context in its output. Answers the admission at once: wait for the outcome with sdk.operations.result({{operationId, wait_ms}}). The commands:{}", commands("operation")),
            obj(json!({ "command": text(), "args": { "type": "object" }, "context": nullable(context_schema()), "idempotencyKey": { "type": "string", "description": "from sdk.operations.issueKey" }, "manifest": manifest() }), &["command", "args", "context", "idempotencyKey"]),
            admission(json!({}), &[]), &["operation.read"][..], false),
        entry("operations", "status",
            "An operation's state, cancellation and progress; with afterSequence, whether it changed since.",
            obj(json!({ "operationId": text(), "afterSequence": text() }), &["operationId"]),
            obj(json!({ "changed": { "type": "boolean" }, "status": status.clone() }), &["changed", "status"]), &["operation.read"][..], true),
        entry("operations", "result",
            "An operation's terminal result: state (succeeded, failed, cancelled), effects, geometry, output and error. With wait_ms it waits up to that long for the operation to finish; while it has not, the call fails with not_ready.",
            obj(json!({ "operationId": text(), "wait_ms": { "type": "integer", "minimum": 0, "maximum": MAX_RESULT_WAIT_MS } }), &["operationId"]),
            open(json!({ "operationId": text(), "state": { "enum": ["succeeded", "failed", "cancelled"] }, "sequence": text(), "accepted": { "const": true }, "finishedAt": text(), "effects": { "type": "object" }, "geometry": { "type": "object" }, "output": {}, "error": {}, "retention": retention.clone() }), &["operationId", "state", "sequence", "finishedAt", "effects", "output", "error"]), &["operation.read"][..], true),
        entry("operations", "cancel",
            "Ask an accepted operation to stop. Answers what the request could still do: requested, cancelled_before_start, too_late or already_terminal.",
            obj(json!({ "operationId": text() }), &["operationId"]),
            obj(json!({ "operationId": text(), "disposition": { "enum": ["requested", "cancelled_before_start", "too_late", "already_terminal"] }, "status": status }), &["operationId", "disposition", "status"]), &["operation.cancel"][..], false),
        entry("commands", "query",
            &format!("Run a catalogue query command inline, at the document's current revision. Answers {{context, output}}. The commands:{}", commands("query")),
            obj(json!({ "command": { "const": "cad.model.inspect" }, "args": obj(json!({}), &[]), "context": context_schema(), "manifest": manifest() }), &["command", "context"]),
            obj(json!({ "context": context_schema(), "output": catalogue.get("cad.model.inspect").expect("the catalogue declares cad.model.inspect").output_schema.clone() }), &["context", "output"]), &["document.read"][..], true),
        entry("inputs", "exportOptions", export.documentation, export.input_schema.clone(), export.output_schema.clone(), &[][..], false),
    ];
    for e in &mut entries {
        e.method = match (e.namespace, e.action) {
            ("document", "list") => "cad.documents.list",
            ("document", "get") => "cad.documents.get",
            ("document", "create") => "cad.documents.create",
            ("document", "bind") => "cad.documents.bind",
            ("artifacts", "read") => "cad.artifacts.read",
            ("artifacts", "create") => "cad.artifacts.create",
            ("artifacts", "begin") => "cad.artifacts.begin",
            ("artifacts", "append") => "cad.artifacts.append",
            ("artifacts", "commit") => "cad.artifacts.commit",
            ("operations", "issueKey") => "cad.operations.issueKey",
            ("operations", "submit") => "cad.operations.submit",
            ("operations", "status") => "cad.operations.status",
            ("operations", "result") => "cad.operations.result",
            ("operations", "cancel") => "cad.operations.cancel",
            ("commands", "query") => "cad.commands.query",
            _ => "cad.inputs.exportOptions",
        };
    }
    // Every catalogue command that acts on one document is a typed function
    // of its own, `sdk.<group>.<verb>({context, ...args})`: one accepted
    // operation start to finish (or one query), so a program does not walk
    // issueKey / submit / result itself. Generated from the descriptors:
    // a new document-scoped command is a new function.
    for d in catalogue.descriptors.iter().filter(|d| d.document_scope == "one") {
        let Some((namespace, action)) = typed_path(d.path) else { continue };
        let operation = d.execution == "operation";
        let mut input_schema = d.input_schema.clone();
        input_schema["properties"]["context"] = context_schema();
        let mut required = vec![json!("context")];
        required.extend(input_schema["required"].as_array().cloned().unwrap_or_default());
        input_schema["required"] = Value::Array(required);
        let mut output_schema = d.output_schema.clone();
        let mut grants: Vec<&'static str> = d.required_capabilities.to_vec();
        if operation {
            // The operation that did it, beside its output (as `document.create` answers).
            output_schema["properties"]["operationId"] = text();
            output_schema["properties"]["state"] = json!({ "const": "succeeded" });
            output_schema["properties"]["effects"] = json!({ "type": "object", "description": "the operation's effects: disposition and the documents it changed" });
            if let Some(required) = output_schema["required"].as_array_mut() { required.extend([json!("operationId"), json!("state"), json!("effects")]); }
            grants.push("operation.read");
        }
        let how = if operation {
            "`context` names the document and the revision the caller expects. One accepted operation, start to finish: it answers the command's output with the operation that made it (operationId, state, effects), or throws its error. A write's output carries the document's next `context`."
        } else {
            "`context` names the document. An ordered read, run inline: it answers the command's output, tagged with the document's current context."
        };
        entries.push(ServiceEntry {
            namespace, action, method: d.path,
            doc: format!("{} {} {how}", d.summary, d.documentation),
            input_schema, output_schema, grants,
            read_only: !operation,
            destructive: d.effect_classes.contains(&"document_lifecycle"),
        });
    }
    entries
}

/// Where a document-scoped catalogue command sits in the namespace:
/// `cad.<group>.<verb>` is `sdk.<group>.<verb>`, with the old `documents`
/// group under `document` (as the documents-by-identity functions are).
pub fn typed_path(command: &'static str) -> Option<(&'static str, &'static str)> {
    let (group, verb) = command.strip_prefix("cad.")?.split_once('.')?;
    Some((if group == "documents" { "document" } else { group }, verb))
}

/// Every old `cad.*` spelling a program could write and what became of it:
/// `(old, new)` for a function that moved, `(old, "")` with the reason for
/// one that is gone. A document-scoped command was a method of the old
/// bound-document object (`doc.sketch.create(args)`): it is now a function
/// that takes the document's `context` with its arguments. `service` marks the methods the old low-level `service`
/// export also carried (`service.documents.list`): those returned a
/// `{ok, value}` envelope, where the new function answers the value and
/// throws on failure. The generated mapping file is built from this table.
pub struct Legacy {
    pub old: &'static str,
    pub new: &'static str,
    pub reason: &'static str,
    pub service: bool,
}

const NESTED: &str = "a program cannot start or inspect executions (no nested executions); use the `run` tool";

pub const LEGACY: &[Legacy] = &[
    Legacy { old: "cad.inputs.exportOptions", new: "sdk.inputs.exportOptions", reason: "", service: true },
    Legacy { old: "cad.discovery.search", new: "", reason: "discovery is the `sdk` tool, not a script function: sdk({query})", service: true },
    Legacy { old: "cad.discovery.describe", new: "", reason: "discovery is the `sdk` tool, not a script function: sdk({topic: \"<namespace>.<action>\"})", service: true },
    Legacy { old: "cad.docs.list", new: "", reason: "discovery is the `sdk` tool, not a script function: sdk({}) lists the guides", service: false },
    Legacy { old: "cad.docs.read", new: "", reason: "discovery is the `sdk` tool, not a script function: sdk({topic: \"guide.<name>\"}) returns a guide; a brep:// reference is read with MCP resources/read", service: false },
    Legacy { old: "cad.docs.sdk", new: "", reason: "discovery is the `sdk` tool, not a script function: sdk({topic: \"<namespace>\"}) lists a namespace, sdk({topic: \"<namespace>.<action>\"}) gives a signature", service: false },
    Legacy { old: "cad.session.summary", new: "", reason: "it was SDK-side JavaScript and no SDK source is sent to a worker: read sdk.document.docs_list({}) and sdk.history.listing({})", service: false },
    Legacy { old: "cad.documents.list", new: "sdk.document.list", reason: "", service: true },
    Legacy { old: "cad.documents.get", new: "sdk.document.get", reason: "", service: true },
    Legacy { old: "cad.documents.create", new: "sdk.document.create", reason: "", service: false },
    Legacy { old: "cad.documents.bind", new: "sdk.document.bind", reason: "", service: false },
    Legacy { old: "cad.documents.close", new: "sdk.document.close", reason: "", service: false },
    Legacy { old: "cad.sketch.create", new: "sdk.sketch.create", reason: "", service: false },
    Legacy { old: "cad.solids.extrude", new: "sdk.solids.extrude", reason: "", service: false },
    Legacy { old: "cad.files.export", new: "sdk.files.export", reason: "", service: false },
    Legacy { old: "cad.files.import", new: "sdk.files.import", reason: "", service: false },
    Legacy { old: "cad.model.inspect", new: "sdk.model.inspect", reason: "", service: false },
    Legacy { old: "cad.operations.issueKey", new: "sdk.operations.issueKey", reason: "", service: true },
    Legacy { old: "cad.operations.submit", new: "sdk.operations.submit", reason: "", service: true },
    Legacy { old: "cad.operations.status", new: "sdk.operations.status", reason: "", service: true },
    Legacy { old: "cad.operations.result", new: "sdk.operations.result", reason: "", service: true },
    Legacy { old: "cad.operations.cancel", new: "sdk.operations.cancel", reason: "", service: true },
    Legacy { old: "cad.commands.query", new: "sdk.commands.query", reason: "", service: true },
    Legacy { old: "cad.code.submit", new: "", reason: NESTED, service: true },
    Legacy { old: "cad.code.status", new: "", reason: NESTED, service: true },
    Legacy { old: "cad.code.result", new: "", reason: NESTED, service: true },
    Legacy { old: "cad.code.cancel", new: "", reason: NESTED, service: true },
    Legacy { old: "cad.artifacts.read", new: "sdk.artifacts.read", reason: "", service: true },
    Legacy { old: "cad.artifacts.create", new: "sdk.artifacts.create", reason: "", service: true },
    Legacy { old: "cad.artifacts.begin", new: "sdk.artifacts.begin", reason: "", service: true },
    Legacy { old: "cad.artifacts.append", new: "sdk.artifacts.append", reason: "", service: true },
    Legacy { old: "cad.artifacts.commit", new: "sdk.artifacts.commit", reason: "", service: true },
    Legacy { old: "cad.internal.awaitOperation", new: "", reason: "it was the SDK's own bridge call: sdk.operations.result({operationId, wait_ms}) waits for an operation", service: false },
    Legacy { old: "cad.internal.pause", new: "", reason: "it was the SDK's own bridge call (its backoff between overloaded submissions)", service: false },
];

/// Whether a call by this name may change something: every registry tool
/// (a tool's failure may follow a partial mutation) and the service functions
/// that write. A program that fails after such a call does not claim that
/// nothing happened.
pub fn effects_possible(method: &str) -> bool {
    !matches!(method, "document.list" | "document.get" | "document.bind" | "artifacts.read" | "operations.issueKey" | "operations.status" | "operations.result" | "operations.cancel" | "commands.query" | "inputs.exportOptions" | "model.inspect")
}

/// [`effects_possible`], under the name the worker's host first called it by.
pub fn may_have_effects(method: &str) -> bool {
    effects_possible(method)
}

/// [`fields`], under the name the worker's host first called it by.
pub(crate) fn signature(schema: &Value) -> String {
    fields(schema)
}

fn tool_refusal(error: &str, spec: &ToolSpec) -> String {
    let argument_error = ["unknown field", "missing field", "invalid type", "unknown variant", "there are no fields"].iter().any(|m| error.contains(m));
    if !argument_error || error.contains(" takes {") { return error.to_string(); }
    format!("{error} โ€” sdk.{} takes {}", crate::script_sdk::path_of(spec.group, &spec.name), fields(&spec.input_schema))
}

/// `{id: string, patch?: object}` from an input schema, at most ~600 bytes:
/// an argument error names the fields the function takes, so an agent does
/// not guess one round trip per spelling.
pub(crate) fn fields(schema: &Value) -> String {
    let Some(props) = schema.get("properties").and_then(Value::as_object).filter(|p| !p.is_empty()) else { return "{} (no arguments)".into() };
    let required: Vec<&str> = schema["required"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
    let mut out = Vec::new();
    let mut len = 0;
    for (name, p) in props {
        let ty = match &p["type"] {
            Value::String(t) => t.clone(),
            Value::Array(ts) => ts.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("|"),
            _ if p.get("enum").is_some() => p["enum"].as_array().into_iter().flatten().take(6).map(|v| v.to_string()).collect::<Vec<_>>().join("|"),
            _ => "any".into(),
        };
        let field = format!("{name}{}: {ty}", if required.contains(&name.as_str()) { "" } else { "?" });
        len += field.len() + 2;
        if len > 600 { out.push("โ€ฆ".to_string()); break; }
        out.push(field);
    }
    format!("{{{}}}", out.join(", "))
}

/// A succeeded operation's output with the operation beside it.
fn receipt(result: &Value) -> Value {
    let mut output = result["output"].clone();
    if let Some(fields) = output.as_object_mut() {
        for key in ["operationId", "state", "effects"] {
            fields.insert(key.into(), result[key].clone());
        }
    }
    output
}

/// A stored error record (an operation's terminal `error`) as an `ApiError`.
fn error_of(record: &Value, operation: &str) -> ApiError {
    const CODES: &[&str] = &[
        "invalid_arguments", "unsupported_version", "manifest_mismatch", "method_unknown", "capability_denied", "document_unknown",
        "document_closed", "document_not_active", "document_busy", "document_mismatch", "revision_conflict", "overloaded",
        "idempotency_conflict", "idempotency_expired", "operation_unknown", "handle_epoch_mismatch", "not_ready", "cancelled",
        "geometry_refused", "evaluation_failed", "job_failed", "deadline_exceeded", "resource_limit", "external_io_failed",
        "artifact_unknown", "artifact_expired", "host_stopping", "host_stopped", "internal_error",
    ];
    const PHASES: &[&str] = &["validation", "authorization", "admission", "queue", "running", "evaluation", "commit", "external_io", "lookup", "completion"];
    let known = |list: &[&'static str], value: &Value, otherwise| list.iter().copied().find(|c| value.as_str() == Some(*c)).unwrap_or(otherwise);
    let mut error = ApiError::new(known(CODES, &record["code"], "job_failed"), known(PHASES, &record["phase"], "running"), record["message"].as_str().unwrap_or("the operation did not succeed")).op(operation);
    error.effects = Effects {
        disposition: known(&["none", "committed", "partial", "unknown"], &record["effects"]["disposition"], "unknown"),
        documents: record["effects"]["documents"].as_array().cloned().unwrap_or_default(),
        external: record["effects"]["external"].as_array().cloned().unwrap_or_default(),
    };
    error.retry = known(&["do_not_retry", "query_operation", "retry_same_key_within_retention", "inspect_then_new_submission"], &record["retry"], error.retry);
    if !record["context"].is_null() { error.context = Some(record["context"].clone()); }
    error
}

fn string<'a>(req: &'a Value, key: &str) -> Result<&'a str, ApiError> {
    req.get(key).and_then(Value::as_str).ok_or_else(|| ApiError::new("invalid_arguments", "validation", format!("{key} is required")))
}

fn only(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())) {
        let takes = if allowed.is_empty() { "it takes no fields".to_string() } else { format!("it takes {{{}}}", allowed.join(", ")) };
        return Err(ApiError::new("invalid_arguments", "validation", format!("unknown field `{k}`; {takes}")));
    }
    Ok(())
}

/// What a name resolved to, owned (the tool set's lock is not held across a call).
enum Found {
    Tool(Box<ToolSpec>),
    Service(&'static str),
}

impl CadService {
    /// The catalogue for the tool set as it is now: the registry's
    /// script-callable tools (a live session adds the app's), this server's
    /// service functions, and the skills as guides.
    pub fn surface<'a>(&'a self, tools: &'a ToolSet, state: Option<&'a crate::server::ServerState>) -> Surface<'a> {
        let skills = state.map_or(crate::skills::Catalogue::embedded(), |s| s.skills());
        let guides = skills.skills.iter().map(|s| Guide { name: s.name, description: s.description, text: s.text }).collect();
        Surface::new(&tools.specs, &self.services, guides)
    }

    /// The functions `caller` may call, as `<namespace>.<action>`: the
    /// granted names only, which is all a worker is given. An ungranted name
    /// is simply absent, so the worker answers it as it answers a misspelt
    /// one. Never waits on the runtime: callable from a worker's host thread
    /// and from a task alike.
    pub fn script_names(&self, caller: &Caller) -> Vec<String> {
        let state = self.server_state();
        let granted = |tools: &ToolSet| self.surface(tools, state.as_deref()).granted(|g| caller.grants.has(g)).names();
        let Some(state) = &state else { return granted(&ToolSet::default()) };
        if let Ok(set) = state.tools.try_read() { return granted(&set); }
        // A writer holds the set for one assignment (a session started or
        // stopped): wait for it where this thread is allowed to.
        match tokio::runtime::Handle::try_current() {
            Err(_) => granted(&state.tools.blocking_read()),
            Ok(handle) if handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread => {
                tokio::task::block_in_place(|| granted(&handle.block_on(state.tools.read())))
            }
            Ok(_) => loop {
                if let Ok(set) = state.tools.try_read() { break granted(&set); }
                std::thread::yield_now();
            },
        }
    }

    /// Whether `method` is a name `caller` was granted: what a host records
    /// of a call (a journal keeps only names that are, never arbitrary
    /// worker-controlled text).
    pub async fn script_known(&self, caller: &Caller, method: &str) -> bool {
        let state = self.server_state();
        let empty = ToolSet::default();
        let guard = match &state { Some(state) => Some(state.tools.read().await), None => None };
        self.surface(guard.as_deref().unwrap_or(&empty), None).get(method).is_some_and(|entry| entry.grants().iter().all(|g| caller.grants.has(g)))
    }

    /// One script call: `method` is `<namespace>.<action>` (as
    /// [`Self::script_names`] lists it), `body` its one argument. A registry
    /// tool runs its own handler; a service function runs here. A name the
    /// caller was not granted, or that does not exist, fails saying what does.
    pub async fn script_call(&self, caller: &Caller, method: &str, body: Value) -> Result<Value, ApiError> {
        if body.to_string().len() > 1 << 20 {
            return Err(ApiError::new("resource_limit", "validation", "the request is larger than 1 MiB"));
        }
        let state = self.server_state();
        let found = {
            let empty = ToolSet::default();
            let guard = match &state { Some(state) => Some(state.tools.read().await), None => None };
            let surface = self.surface(guard.as_deref().unwrap_or(&empty), None);
            match surface.get(method) {
                Some(entry) => match entry.grants().iter().find(|g| !caller.grants.has(g)) {
                    Some(missing) => return Err(ApiError::new("capability_denied", "authorization", format!("sdk.{} needs `{missing}`, which this program was not granted", entry.path()))),
                    None => match entry.target {
                        Target::Tool(spec) => Found::Tool(Box::new(spec.clone())),
                        Target::Service(service) => Found::Service(service.method),
                    },
                },
                // Only what the caller may call is suggested.
                None => return Err(ApiError::new("method_unknown", "lookup", surface.granted(|g| caller.grants.has(g)).unknown(method))),
            }
        };
        let value = match found {
            Found::Tool(spec) => self.call_tool(caller, &spec, body).await?,
            Found::Service(service) => self.call_service(caller, service, body).await?,
        };
        // A reply this large would exhaust the program's worker when parsed:
        // refuse it softly, by size.
        let size = value.to_string().len();
        if size > MAX_REPLY {
            return Err(ApiError::new("resource_limit", "evaluation", format!("sdk.{method}'s result is {size} bytes, more than a script can take ({MAX_REPLY}); ask for less (a filter, a page, one entity)")));
        }
        Ok(value)
    }

    /// A registry tool as a script function: the tool's own handler, the
    /// very code path the tool takes anywhere else.
    async fn call_tool(&self, caller: &Caller, spec: &ToolSpec, args: Value) -> Result<Value, ApiError> {
        if let Some(message) = crate::script_sdk::undeclared_context(&spec.name, &spec.input_schema, &args) {
            return Err(ApiError::new("invalid_arguments", "validation", message));
        }
        // The file functions run as the PROGRAM, not as the local user the
        // registry handler stands for: its own artifact area, its own grants.
        let result = if spec.group == "files" {
            match spec.name.strip_prefix("files_").ok_or_else(|| "invalid file method".to_string()).and_then(|op| crate::files::operation_request(op, args)) {
                Ok(request) => self.files.call(self, caller, request).await,
                Err(error) => Err(error),
            }
        } else {
            (spec.handler)(args).await
        };
        let out = result.map_err(|e| {
            let mut error = ApiError::from_app(&tool_refusal(&e, spec), "evaluation");
            // An unclassified tool failure may follow a partial mutation.
            if error.code == "evaluation_failed" { error.effects = Effects::unknown(); }
            error
        })?;
        let mut value = out.json;
        if !out.images.is_empty() {
            // A picture reaches a program as an artifact of its own (bytes
            // do not cross the bridge); `run` attaches the ones it returns.
            let mut refs = Vec::new();
            for image in out.images {
                refs.push(self.artifacts.create(caller.owner(), image.mime, image.png)?);
            }
            match value.as_object_mut() {
                Some(o) => { o.insert("images".into(), Value::Array(refs)); }
                None => value = json!({ "value": value, "images": refs }),
            }
        }
        Ok(value)
    }

    /// One accepted operation, start to finish: a key issued once, one
    /// submission (retried on overload with the SAME key), then its terminal
    /// result. Answers the command's output with the operation's identity,
    /// state and effects beside it: the reply is what a durable journal
    /// reads a host call's operation from, so a restart can say what
    /// committed.
    async fn operate(&self, caller: &Caller, command: &str, args: Value, context: Value) -> Result<Value, ApiError> {
        let key = self.ops.issue_key(caller, &json!({ "purpose": "command" }))?["key"].clone();
        let request = json!({ "manifest": self.catalogue.identity(), "command": command, "args": args, "context": context, "idempotencyKey": key });
        let mut attempt = 0u32;
        let admission = loop {
            match self.ops.submit(caller, &request) {
                Ok(admission) => break admission,
                Err(e) if e.code == "overloaded" && attempt < 20 => {
                    tokio::time::sleep(Duration::from_millis((100u64 << attempt.min(4)).min(1000))).await;
                    attempt += 1;
                }
                Err(e) => return Err(e),
            }
        };
        let id = admission["operationId"].as_str().unwrap_or_default().to_string();
        let result = self.operation_result(caller, &json!({ "operationId": id }), None).await?;
        if result["state"] != "succeeded" {
            return Err(error_of(&result["error"], &id));
        }
        Ok(receipt(&result))
    }

    /// An operation's terminal result, waited for host-side (no transport
    /// request is held): until it ends, or until `deadline`.
    async fn operation_result(&self, caller: &Caller, req: &Value, deadline: Option<std::time::Instant>) -> Result<Value, ApiError> {
        let mut delay = 25;
        loop {
            match self.ops.result(caller, req) {
                Err(e) if e.code == "not_ready" && deadline.is_none_or(|d| std::time::Instant::now() < d) => {
                    tokio::time::sleep(Duration::from_millis(delay)).await;
                    delay = (delay * 2).min(250);
                }
                other => return other,
            }
        }
    }

    /// A service function, by the name its entry dispatches to.
    pub(crate) async fn call_service(&self, caller: &Caller, method: &str, mut req: Value) -> Result<Value, ApiError> {
        // A program has no manifest constant: an omitted one is this server's.
        if matches!(method, "cad.operations.submit" | "cad.commands.query") && req.is_object() && req.get("manifest").is_none_or(Value::is_null) {
            req["manifest"] = self.catalogue.identity();
        }
        let req = &req;
        match method {
            "cad.inputs.exportOptions" => self.code.export_options(caller, req).await,
            "cad.documents.list" => {
                only(req, &[])?;
                self.ops.documents(caller, None).await
            }
            "cad.documents.get" => {
                only(req, &["documentId"])?;
                self.ops.documents(caller, Some(string(req, "documentId")?)).await
            }
            "cad.documents.create" => self.operate(caller, "cad.documents.create", req.clone(), Value::Null).await,
            // A check, not a mutation: the document must be open at exactly
            // the revision the caller expects.
            "cad.documents.bind" => {
                only(req, &["documentId", "expectedRevision"])?;
                let (document, expected) = super::wire::document_context(req)?;
                let info = self.ops.documents(caller, Some(&document)).await?;
                let current = info["context"]["expectedRevision"].as_str().unwrap_or_default();
                if current != expected {
                    return Err(ApiError::new("revision_conflict", "admission", format!("the document is at revision {current}, not {expected}")).context(info["context"].clone()));
                }
                Ok(info)
            }
            "cad.operations.issueKey" => {
                only(req, &["purpose"])?;
                self.ops.issue_key(caller, &json!({ "purpose": req.get("purpose").cloned().unwrap_or(json!("command")) }))
            }
            "cad.operations.submit" => self.ops.submit(caller, req),
            "cad.operations.status" => self.ops.status(caller, req),
            "cad.operations.result" => {
                only(req, &["operationId", "wait_ms"])?;
                let wait = match req.get("wait_ms") {
                    None => 0,
                    Some(v) => v.as_u64().filter(|ms| *ms <= MAX_RESULT_WAIT_MS).ok_or_else(|| ApiError::new("invalid_arguments", "validation", format!("wait_ms must be an integer from 0 to {MAX_RESULT_WAIT_MS}")))?,
                };
                let lookup = json!({ "operationId": req.get("operationId") });
                self.operation_result(caller, &lookup, Some(std::time::Instant::now() + Duration::from_millis(wait))).await
            }
            "cad.operations.cancel" => self.ops.cancel(caller, req),
            "cad.commands.query" => self.ops.query(caller, req).await,
            "cad.artifacts.read" => {
                caller.require(&["artifact.read"])?;
                only(req, &["artifactId", "offset", "limit"])?;
                let offset = req.get("offset").map_or(Some(0), Value::as_u64).ok_or_else(|| ApiError::new("invalid_arguments", "validation", "offset must be a non-negative integer"))?;
                let limit = match req.get("limit") {
                    None => None,
                    Some(v) => Some(v.as_u64().ok_or_else(|| ApiError::new("invalid_arguments", "validation", "limit must be a positive integer"))? as usize),
                };
                self.artifacts.read(&caller.owner(), string(req, "artifactId")?, offset as usize, limit)
            }
            "cad.artifacts.create" => {
                caller.require(&["artifact.write"])?;
                only(req, &["mediaType", "bytesBase64", "path"])?;
                if string(req, "mediaType")? != "model/step" {
                    return Err(ApiError::new("invalid_arguments", "validation", "mediaType must be model/step"));
                }
                // Either the bytes, or (for the local user's program) a file
                // on the host: the way a large input reaches a program.
                let bytes = match (req.get("bytesBase64"), req.get("path").and_then(Value::as_str)) {
                    (None, Some(path)) => {
                        caller.require(&["host.files.read"])?;
                        let len = std::fs::metadata(path).map_err(|e| ApiError::new("invalid_arguments", "external_io", format!("{path}: {e}")))?.len();
                        if len > super::artifacts::MAX_ARTIFACT as u64 {
                            return Err(ApiError::new("resource_limit", "external_io", format!("{path} is larger than {} bytes", super::artifacts::MAX_ARTIFACT)));
                        }
                        std::fs::read(path).map_err(|e| ApiError::new("invalid_arguments", "external_io", format!("{path}: {e}")))?
                    }
                    (Some(_), None) => {
                        use base64::Engine as _;
                        base64::engine::general_purpose::STANDARD
                            .decode(string(req, "bytesBase64")?)
                            .map_err(|e| ApiError::new("invalid_arguments", "validation", format!("bytesBase64: {e}")))?
                    }
                    _ => return Err(ApiError::new("invalid_arguments", "validation", "give exactly one of bytesBase64 and path")),
                };
                self.artifacts.create(caller.owner(), "model/step", bytes)
            }
            // The streaming route for an input above the 1 MiB transport
            // limit: begin with the length and digest, append chunks in
            // order, commit. The artifact exists only once it all matches.
            "cad.artifacts.begin" => {
                caller.require(&["artifact.write"])?;
                only(req, &["mediaType", "byteLength", "sha256"])?;
                if string(req, "mediaType")? != "model/step" {
                    return Err(ApiError::new("invalid_arguments", "validation", "mediaType must be model/step"));
                }
                let length = req.get("byteLength").and_then(Value::as_u64).ok_or_else(|| ApiError::new("invalid_arguments", "validation", "byteLength is required"))?;
                self.artifacts.begin(caller.owner(), "model/step", length as usize, string(req, "sha256")?)
            }
            "cad.artifacts.append" => {
                caller.require(&["artifact.write"])?;
                only(req, &["uploadId", "offset", "bytesBase64"])?;
                let offset = req.get("offset").and_then(Value::as_u64).ok_or_else(|| ApiError::new("invalid_arguments", "validation", "offset is required"))?;
                use base64::Engine as _;
                let bytes = base64::engine::general_purpose::STANDARD
                    .decode(string(req, "bytesBase64")?)
                    .map_err(|e| ApiError::new("invalid_arguments", "validation", format!("bytesBase64: {e}")))?;
                self.artifacts.append(&caller.owner(), string(req, "uploadId")?, offset as usize, bytes)
            }
            "cad.artifacts.commit" => {
                caller.require(&["artifact.write"])?;
                only(req, &["uploadId"])?;
                self.artifacts.commit(&caller.owner(), string(req, "uploadId")?)
            }
            // A document-scoped catalogue command as one typed call: the
            // `context` beside its arguments, the whole lifecycle here.
            other => {
                let descriptor = self.catalogue.get(other).filter(|d| d.document_scope == "one")
                    .ok_or_else(|| ApiError::new("method_unknown", "lookup", format!("no service function `{other}`")))?;
                let mut args = req.clone();
                let fields = args.as_object_mut().ok_or_else(|| ApiError::new("invalid_arguments", "validation", "the request must be an object"))?;
                let context = fields.remove("context").filter(|c| !c.is_null())
                    .ok_or_else(|| ApiError::new("invalid_arguments", "validation", format!("context is required: the document `{other}` acts on, {{documentId, expectedRevision}} (sdk.document.create and every write answer one)")))?;
                if descriptor.execution == "query" {
                    let answer = self.ops.query(caller, &json!({ "manifest": self.catalogue.identity(), "command": other, "args": args, "context": context })).await?;
                    Ok(answer["output"].clone())
                } else {
                    self.operate(caller, descriptor.path, args, context).await
                }
            }
        }
    }
}