draftwright 0.2.15

Automated technical drawings from STEP B-rep: a Rust port of draftwright.
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
//! The command line over the document model (ADR R1), through [`draftwright::api`]. Each command
//! prints JSON.
//!
//! - `draftwright analyse part.step [--features r.json | --no-features]`: the Analysis
//! - `draftwright plan part.step [--features r.json | --no-features] [--spec s.json]`: the Plan;
//!   or `draftwright plan [part.step] --analysis a.json [--spec s.json]`, from an Analysis
//!   without analysing again
//! - `draftwright render part.step [--features r.json | --no-features | --analysis a.json]
//!   [--spec s.json] -o out [--formats svg,pdf,png] [--dpi 150]`: writes the files
//!   (`out.svg`, …; svg and pdf unless named, a PNG at `--dpi` pixels per inch; DXF export is
//!   disabled until it is fixed) and prints
//!   what was written, with the problems: the plan's, and what could not be drawn as planned
//! - `draftwright review part.step [--features r.json | --no-features | --analysis a.json]
//!   [--spec s.json]`: the drawing as SVG text, with the problems and lint's findings on the
//!   drawing
//! - `draftwright edit s.json ops.json`: the edited Spec
//! - `draftwright spec drawing.(svg|dxf|pdf|png)`: the Spec embedded in a rendered drawing
//! - `draftwright diff old.step new.step [--spec s.json] [--part K] -o dir [--title T]
//!   [--dpi 150]`: the drawing of *old* with the Spec, the Spec carried to *new* through
//!   quiddity's correspondence (ADR R3) and *new* drawn with it, and what changed
//!   ([`draftwright::revision`]). Writes `report.json`, `report.md` (a pull request comment),
//!   `spec.json` (the carried Spec), `changes.svg` and `changes.png` (the new drawing marked up)
//!   and `drawing.svg` into *dir*, and prints the verdict
//! - `draftwright parts part.step`: the file's distinct parts (`{parts: [{part, name,
//!   product_id, faces, instances}]}`), by which one part of an assembly is chosen
//! - `draftwright serve`: the JSON-lines service. One request per line on stdin, such as
//!   `{"id": 1, "op": "plan", "step": "part.step", "spec": {…}}`, and one reply per line on
//!   stdout: `{"id": 1, "ok": true, "result": …}` or `{"id": 1, "ok": false, "error": {"code",
//!   "message", "choices"?}}`. `{"op": "hello"}` gives the protocol version and the operations;
//!   the others, and their arguments, are those of [`draftwright::api::call`].
//! - `draftwright completions <SHELL>`: a completion script for bash, zsh, fish, powershell or
//!   elvish, on stdout
//!
//! The command line is parsed by clap: `--help` (on any command), `--version`, and clap's usage
//! errors on stderr. Values are checked here, so a bad `--part` or `--dpi` is refused as JSON.
//!
//! The features come from Rust quiddity's recognition, run on the part
//! ([`draftwright::api::Features::Native`]), unless one of these says otherwise. A part whose
//! recognition document is refused is not drawn (exit 1, with the refusal), and the families
//! that recognition does not give are named in the plan's problems (`features_not_recognised`).
//! `--features` names Python quiddity's recognition JSON for the same file
//! (`tools/recognise.py`, read by [`draftwright::bridge`]), used instead. `--no-features`
//! analyses the part with no features (no feature dimensions, sections or lint), as the library
//! does when given none: the way to draw a part whose recognition is refused. `--analysis` names
//! an Analysis that `draftwright analyse` printed for the same STEP file (with its features),
//! used in place of analysing the file again; it is refused with `--features` or
//! `--no-features`, or when made from another file. `serve` takes Python's JSON or none, as
//! [`draftwright::api::call`] does.
//!
//! `analyse`, `plan`, `render` and `review` take `--part K`: part K of an assembly (as `parts`
//! lists them) drawn alone, in its own frame and with its PMI only. Without it the whole file is
//! drawn as one part, and an assembly's plan warns (`assembly_drawn_whole`), naming its parts;
//! when every body coincides with one part's (`coincident_bodies`), or lies within the largest
//! body's box (`assembly_principal_drawn`), that part is drawn alone.
//!
//! Exit codes: 0 done; 2 the request is invalid (the JSON error says what would be accepted), or
//! the command line is (clap's usage error); 1 something failed and nothing was written in its
//! place.

use std::io::{BufRead, Write};
use std::process::ExitCode;

use clap::{Args, CommandFactory, Parser, Subcommand};
use draftwright::api::{self, Error, Features};
use draftwright::model::Spec;
use serde_json::{Value, json};

/// The service's protocol version, given by `hello`.
const PROTOCOL: u32 = 1;

const AFTER_HELP: &str = "Discovery: schemas/spec.json, docs/model.md and docs/mcp.md ship in the release.
JSON-lines serve: {\"op\":\"hello\"} lists operations; spec_schema and item_options use the MCP argument shapes.";

/// The command line. Values are kept as text and checked by [`run`], so a bad `--part` or
/// `--dpi` is refused with the JSON error it has always had; only the shape of the command line
/// is clap's.
#[derive(Parser)]
#[command(
    name = "draftwright",
    version,
    about = "draftwright — engineering drawings from STEP",
    after_help = AFTER_HELP,
    subcommand_required = true,
    disable_help_subcommand = true,
    args_override_self = true
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

/// Where the part's features come from, and the Spec and part drawn.
#[derive(Args)]
struct Drawing {
    /// Python quiddity's recognition JSON for the same STEP file, used instead of Rust
    /// quiddity's recognition
    #[arg(long, value_name = "JSON")]
    features: Option<String>,
    /// analyse the part with no features (no feature dimensions, sections or lint)
    #[arg(long)]
    no_features: bool,
    /// an Analysis `draftwright analyse` printed for the same STEP file, used instead of
    /// analysing it again
    #[arg(long, value_name = "JSON")]
    analysis: Option<String>,
    /// the Spec (without it, the defaults)
    #[arg(long, value_name = "JSON")]
    spec: Option<String>,
    /// part K of an assembly, as `draftwright parts` lists them, drawn alone
    #[arg(long, value_name = "K", allow_negative_numbers = true)]
    part: Option<String>,
}

#[derive(Subcommand)]
enum Command {
    /// print the part's Analysis
    Analyse {
        step: String,
        #[command(flatten)]
        drawing: Drawing,
    },
    /// print the Plan; from --analysis the STEP file may be left out
    Plan {
        #[arg(required_unless_present = "analysis")]
        step: Option<String>,
        #[command(flatten)]
        drawing: Drawing,
    },
    /// write the drawing's files and print what was written, with the problems
    Render {
        step: String,
        #[command(flatten)]
        drawing: Drawing,
        /// the output stem (out.svg, out.pdf, …)
        #[arg(
            short = 'o',
            value_name = "STEM",
            required = true,
            allow_hyphen_values = true
        )]
        output: Option<String>,
        /// the formats written, of svg, pdf and png
        #[arg(long, value_name = "LIST", default_value = "svg,pdf")]
        formats: String,
        /// a PNG's pixels per inch (default 150)
        #[arg(long, value_name = "DPI", allow_negative_numbers = true)]
        dpi: Option<String>,
    },
    /// print the drawing as SVG text, with the problems and lint's findings
    Review {
        step: String,
        #[command(flatten)]
        drawing: Drawing,
    },
    /// print a Spec with edit operations applied
    Edit {
        #[arg(value_name = "SPEC")]
        spec: String,
        ops: String,
    },
    /// print the Spec embedded in a rendered drawing (SVG, DXF, PDF or PNG)
    Spec { drawing: String },
    /// print the file's distinct parts
    Parts { step: String },
    /// write an assembly's drawing pack into a directory
    Pack {
        step: String,
        /// the output directory
        #[arg(
            short = 'o',
            value_name = "DIRECTORY",
            required = true,
            allow_hyphen_values = true
        )]
        output: Option<String>,
        /// the pack Spec
        #[arg(long, value_name = "JSON")]
        spec: Option<String>,
        /// the formats written
        #[arg(long, value_name = "LIST", default_value = "pdf,csv,json")]
        formats: String,
    },
    /// carry the Spec to a new revision of the part, draw it, and write what changed
    Diff {
        old: String,
        new: String,
        /// the output directory
        #[arg(
            short = 'o',
            value_name = "DIRECTORY",
            required = true,
            allow_hyphen_values = true
        )]
        output: Option<String>,
        /// the Spec of the old revision
        #[arg(long, value_name = "JSON")]
        spec: Option<String>,
        /// part K of an assembly, as `draftwright parts` lists them
        #[arg(long, value_name = "K", allow_negative_numbers = true)]
        part: Option<String>,
        /// the report's title (default: the new file's name)
        #[arg(long, value_name = "TITLE", allow_hyphen_values = true)]
        title: Option<String>,
        /// changes.png's pixels per inch (default 150)
        #[arg(long, value_name = "DPI", allow_negative_numbers = true)]
        dpi: Option<String>,
    },
    /// print the Spec's JSON Schema
    #[command(name = "spec_schema")]
    SpecSchema,
    /// print the settable paths of one item of a part opened by the MCP server
    #[command(name = "item_options")]
    ItemOptions {
        part_ref: String,
        id: String,
        #[arg(long, value_name = "JSON")]
        spec: Option<String>,
    },
    /// answer JSON-lines requests on stdin
    Serve,
    /// the MCP server over stdio
    McpStdio,
    /// the MCP server over HTTP on a loopback address
    McpHttp {
        /// default 127.0.0.1:8765
        address: Option<String>,
    },
    /// print a shell completion script to stdout
    Completions {
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },
}

/// What the command was given, for [`run`].
#[derive(Default)]
struct Given {
    positionals: Vec<String>,
    spec: Option<String>,
    features: Option<String>,
    analysis: Option<String>,
    no_features: bool,
    part: Option<String>,
    output: Option<String>,
    formats: Option<String>,
    dpi: Option<String>,
    title: Option<String>,
}

impl Given {
    fn drawing(positionals: Vec<String>, d: Drawing) -> Self {
        Given {
            positionals,
            spec: d.spec,
            features: d.features,
            analysis: d.analysis,
            no_features: d.no_features,
            part: d.part,
            ..Given::default()
        }
    }
}

fn main() -> ExitCode {
    let (name, given) = match Cli::parse().command {
        Command::Completions { shell } => {
            clap_complete::generate(
                shell,
                &mut Cli::command(),
                "draftwright",
                &mut std::io::stdout(),
            );
            return ExitCode::SUCCESS;
        }
        command @ (Command::McpStdio | Command::McpHttp { .. }) => {
            let args: Vec<String> = match command {
                Command::McpHttp { address } => {
                    std::iter::once("mcp-http".into()).chain(address).collect()
                }
                _ => vec!["mcp-stdio".into()],
            };
            return match draftwright::mcp::run(&args) {
                Ok(()) => ExitCode::SUCCESS,
                Err(e) => {
                    eprintln!("{e}");
                    ExitCode::FAILURE
                }
            };
        }
        Command::Serve => return serve(),
        Command::Analyse { step, drawing } => ("analyse", Given::drawing(vec![step], drawing)),
        Command::Plan { step, drawing } => {
            ("plan", Given::drawing(step.into_iter().collect(), drawing))
        }
        Command::Review { step, drawing } => ("review", Given::drawing(vec![step], drawing)),
        Command::Render {
            step,
            drawing,
            output,
            formats,
            dpi,
        } => (
            "render",
            Given {
                output,
                formats: Some(formats),
                dpi,
                ..Given::drawing(vec![step], drawing)
            },
        ),
        Command::Edit { spec, ops } => (
            "edit",
            Given {
                positionals: vec![spec, ops],
                ..Given::default()
            },
        ),
        Command::Spec { drawing } => (
            "spec",
            Given {
                positionals: vec![drawing],
                ..Given::default()
            },
        ),
        Command::Parts { step } => (
            "parts",
            Given {
                positionals: vec![step],
                ..Given::default()
            },
        ),
        Command::Pack {
            step,
            output,
            spec,
            formats,
        } => (
            "pack",
            Given {
                positionals: vec![step],
                output,
                spec,
                formats: Some(formats),
                ..Given::default()
            },
        ),
        Command::Diff {
            old,
            new,
            output,
            spec,
            part,
            title,
            dpi,
        } => (
            "diff",
            Given {
                positionals: vec![old, new],
                output,
                spec,
                part,
                title,
                dpi,
                ..Given::default()
            },
        ),
        Command::SpecSchema => ("spec_schema", Given::default()),
        Command::ItemOptions { part_ref, id, spec } => (
            "item_options",
            Given {
                positionals: vec![part_ref, id],
                spec,
                ..Given::default()
            },
        ),
    };
    match run(name, &given) {
        Ok(out) => {
            println!("{}", serde_json::to_string_pretty(&out).expect("JSON"));
            ExitCode::SUCCESS
        }
        Err(error) => {
            println!(
                "{}",
                serde_json::to_string_pretty(&json!({ "ok": false, "error": error }))
                    .expect("JSON")
            );
            ExitCode::from(if error.code == "invalid" { 2 } else { 1 })
        }
    }
}

fn read_json(path: &str) -> Result<Value, Error> {
    let text = std::fs::read_to_string(path)
        .map_err(|e| Error::invalid(format!("cannot read {path}: {e}")))?;
    serde_json::from_str(&text).map_err(|e| Error::invalid(format!("{path} is not valid: {e}")))
}

/// Runs the command, its arguments put as [`api::call`] takes them.
fn run(command: &str, given: &Given) -> Result<Value, Error> {
    // clap has required each command's positionals; `plan` from an Analysis may have none.
    let arg = |i: usize| {
        given
            .positionals
            .get(i - 1)
            .map(String::as_str)
            .ok_or_else(|| Error::invalid(format!("{command} needs a STEP file")))
    };
    let spec = match &given.spec {
        Some(path) => read_json(path)?,
        None => Value::Null,
    };
    let features = given.features.as_deref();
    let analysis = match &given.analysis {
        Some(path) => read_json(path)?,
        None => Value::Null,
    };
    let no_features = given.no_features;
    let part = given
        .part
        .as_deref()
        .map(|k| {
            k.parse::<usize>().map_err(|_| {
                Error::invalid(format!(
                    "--part {k:?} is not a part's index; `draftwright parts <step>` lists them"
                ))
            })
        })
        .transpose()?;
    if no_features && (features.is_some() || !analysis.is_null()) {
        return Err(Error::invalid(
            "--no-features is not taken with --features or --analysis: it means no features at all.",
        ));
    }
    let output = || {
        given
            .output
            .as_deref()
            .ok_or_else(|| Error::invalid("render needs -o <output stem>"))
    };
    let formats = || {
        given
            .formats
            .as_deref()
            .unwrap_or("svg,pdf")
            .split(',')
            .collect::<Vec<_>>()
    };
    let dpi = || {
        given
            .dpi
            .as_deref()
            .map(|d| {
                d.parse::<f64>()
                    .map_err(|_| Error::invalid(format!("--dpi {d:?} is not a number")))
            })
            .transpose()
    };
    if command == "parts" {
        return guarded(command, || {
            let parts = api::parts(std::path::Path::new(arg(1)?))?;
            let keys = draftwright::pack::part_keys(&parts);
            let parts: Vec<_> = parts
                .iter()
                .zip(keys)
                .map(|(part, key)| {
                    let mut value = serde_json::to_value(part).expect("part serialises");
                    value["key"] = json!(key);
                    value
                })
                .collect();
            Ok(json!({"parts": parts}))
        });
    }
    if command == "pack" {
        let step = std::path::Path::new(arg(1)?);
        let dir = std::path::Path::new(
            given
                .output
                .as_deref()
                .ok_or_else(|| Error::invalid("pack needs -o <directory>"))?,
        );
        let spec = if spec.is_null() {
            draftwright::pack::PackSpec::default()
        } else {
            serde_json::from_value(spec)
                .map_err(|e| Error::invalid(format!("invalid pack Spec: {e}")))?
        };
        let formats: Vec<_> = given
            .formats
            .as_deref()
            .unwrap_or("pdf,csv,json")
            .split(',')
            .collect();
        return guarded(command, || {
            let (report, files, timings) =
                draftwright::pack::render_profiled(step, &spec, &formats)?;
            std::fs::create_dir_all(dir)
                .map_err(|e| Error::failed(format!("cannot create {}: {e}", dir.display())))?;
            let written = api::write(&dir.join("pack"), &files)?;
            Ok(json!({ "written": written, "report": report, "timings": timings }))
        });
    }
    if command == "diff" {
        let (old, new) = (std::path::Path::new(arg(1)?), std::path::Path::new(arg(2)?));
        let dir = std::path::PathBuf::from(
            given
                .output
                .as_deref()
                .ok_or_else(|| Error::invalid("diff needs -o <output directory>"))?,
        );
        let spec = if spec.is_null() {
            json!({ "schema": draftwright::model::SPEC_SCHEMA, "sheet": {} })
        } else {
            spec
        };
        let dpi = dpi()?.unwrap_or(api::DPI);
        let title = given.title.clone().unwrap_or_else(|| {
            new.file_name()
                .map_or("part".into(), |n| n.to_string_lossy().into_owned())
        });
        return guarded(command, || {
            let revised = draftwright::revision::diff(old, new, part, &spec)?;
            let marked = revised.marked();
            let pretty = |v: &Value| serde_json::to_vec_pretty(v).expect("JSON serialises");
            let files: Vec<(&str, Vec<u8>)> = vec![
                ("report.json", pretty(&json_of(&revised.report))),
                (
                    "report.md",
                    revised.markdown(&title, Some("changes.png")).into_bytes(),
                ),
                ("spec.json", pretty(&revised.report.carried_spec)),
                ("changes.svg", marked.svg().into_bytes()),
                ("changes.png", marked.png(dpi).map_err(Error::failed)?),
                ("drawing.svg", revised.new.drawing().svg().into_bytes()),
            ];
            std::fs::create_dir_all(&dir)
                .map_err(|e| Error::failed(format!("cannot create {}: {e}", dir.display())))?;
            let mut written = Vec::new();
            for (name, bytes) in files {
                let path = dir.join(name);
                std::fs::write(&path, bytes)
                    .map_err(|e| Error::failed(format!("cannot write {}: {e}", path.display())))?;
                written.push(path.display().to_string());
            }
            Ok(json!({
                "written": written,
                "verdict": revised.report.verdict,
                "summary": revised.report.summary,
            }))
        });
    }
    if matches!(command, "analyse" | "plan" | "render" | "review")
        && features.is_none()
        && analysis.is_null()
        && !no_features
    {
        let step = std::path::Path::new(arg(1)?);
        let spec: Spec = if spec.is_null() {
            Spec::default()
        } else {
            serde_json::from_value(spec)
                .map_err(|e| Error::invalid(format!("the spec is not valid: {e}")))?
        };
        let native = Features::Native;
        return guarded(command, || {
            Ok(match command {
                "analyse" => json_of(&api::analyse_part(step, part, native)?),
                "plan" => json_of(&api::plan_part(step, part, native, &spec)?),
                "review" => json_of(&api::review_part(step, part, native, &spec)?),
                _ => {
                    let (output, dpi) = (output()?, dpi()?.unwrap_or(api::DPI));
                    let (plan, files) =
                        api::render_part(step, part, native, &spec, &formats(), dpi)?;
                    let written = api::write(std::path::Path::new(output), &files)?;
                    json!({ "written": written, "problems": plan.problems })
                }
            })
        });
    }
    let request = match command {
        // From an Analysis, plan needs no STEP file.
        "plan" if !analysis.is_null() => json!({
            "step": given.positionals.first(),
            "features": features,
            "analysis": analysis,
            "spec": spec,
            "part": part,
        }),
        "analyse" | "plan" | "review" => json!({
            "step": arg(1)?,
            "features": features,
            "analysis": analysis,
            "spec": spec,
            "part": part,
        }),
        "render" => json!({
            "step": arg(1)?,
            "features": features,
            "analysis": analysis,
            "spec": spec,
            "part": part,
            "output": output()?,
            "formats": formats(),
            "dpi": dpi()?,
        }),
        "spec_schema" => json!({}),
        "item_options" => {
            let mut request = json!({ "part_ref": arg(1)?, "id": arg(2)? });
            if !spec.is_null() {
                request["spec"] = spec;
            }
            request
        }
        "edit" => json!({ "spec": read_json(arg(1)?)?, "ops": read_json(arg(2)?)? }),
        "spec" => json!({ "drawing": arg(1)? }),
        "parts" => json!({ "step": arg(1)? }),
        other => unreachable!("{other} is not a command"),
    };
    api::call(command, &request)
}

/// *op*'s result, a panic inside it answered as `failed`, as [`api::call`] answers it.
fn guarded(op: &str, f: impl FnOnce() -> Result<Value, Error>) -> Result<Value, Error> {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_else(|panic| {
        let why = panic
            .downcast_ref::<&str>()
            .map(|s| s.to_string())
            .or_else(|| panic.downcast_ref::<String>().cloned())
            .unwrap_or_default();
        Err(Error::failed(format!("{op} stopped: {why}")))
    })
}

fn json_of(document: &impl serde::Serialize) -> Value {
    serde_json::to_value(document).expect("a document serialises")
}

/// Answers requests, one JSON object per line, until stdin closes.
fn serve() -> ExitCode {
    let stdout = std::io::stdout();
    let mut service = api::Service::default();
    for line in std::io::stdin().lock().lines() {
        let Ok(line) = line else { break };
        if line.trim().is_empty() {
            continue;
        }
        let reply = match serde_json::from_str::<Value>(&line) {
            Ok(request) => reply(&request, &mut service),
            Err(e) => json!({ "id": null, "ok": false, "error": Error::invalid(e.to_string()) }),
        };
        let mut out = stdout.lock();
        if writeln!(out, "{reply}").and_then(|_| out.flush()).is_err() {
            break;
        }
    }
    ExitCode::SUCCESS
}

/// A request's reply: its result, or a structured error.
fn reply(request: &Value, service: &mut api::Service) -> Value {
    let Some(fields) = request.as_object() else {
        let error = Error::invalid("a request is a JSON object");
        return json!({ "id": null, "ok": false, "error": error });
    };
    let id = fields.get("id").cloned().unwrap_or(Value::Null);
    let result = match fields.get("op").and_then(Value::as_str) {
        Some("hello") => Ok(
            json!({ "protocol": PROTOCOL, "ops": api::OPERATIONS.iter().chain(api::SESSION_OPERATIONS.iter()).chain(api::STATELESS_OPERATIONS.iter()).collect::<Vec<_>>() }),
        ),
        Some(op) => service.call(op, request),
        None => Err(Error::invalid("a request needs \"op\"")),
    };
    match result {
        Ok(result) => json!({ "id": id, "ok": true, "result": result }),
        Err(error) => json!({ "id": id, "ok": false, "error": error }),
    }
}