Skip to main content

kute_cli/
lib.rs

1//! `kute`: train, encode, decode, inspect, validate, compare, export, benchmark.
2//!
3//! Results go to stdout as JSON (or raw bytes for `decode`), messages to
4//! stderr. Exit status is 0 on success and 1 on any error.
5
6pub mod http;
7pub mod live;
8pub mod registry;
9pub mod shadow;
10pub mod sign;
11pub mod mcp;
12
13use clap::{Parser, Subcommand, ValueEnum};
14use kute::{vocab, AdapterConfig, Engine, KuteError, Pretokenizer, TokenSequence, TrainingConfig, Version, VocabularyId};
15use serde_json::json;
16use std::io::Write;
17use std::path::PathBuf;
18use std::process::ExitCode;
19
20#[derive(Parser)]
21#[command(name = "kute", version, about = "Kannaka Universal Tokenization Engine", long_about = None)]
22struct Cli {
23    #[command(subcommand)]
24    command: Command,
25}
26
27#[derive(Subcommand)]
28enum Command {
29    /// Learn a vocabulary from files and write it as KVF.
30    Train(Box<TrainArgs>),
31    /// Encode a file to a .kute token sequence.
32    Encode {
33        #[arg(long)]
34        vocab: PathBuf,
35        #[arg(long)]
36        input: PathBuf,
37        /// Where to write the .kute container. Without it, token ids are printed as JSON.
38        #[arg(long)]
39        output: Option<PathBuf>,
40        /// Write the compressed container (format 2) instead of plain varint ids.
41        #[arg(long, requires = "output")]
42        compress: bool,
43        /// What to do with a symbol the vocabulary does not contain:
44        /// `strict` refuses the input, `escape` carries the symbol literally
45        /// in the sequence so it still decodes exactly.
46        #[arg(long, default_value = "strict")]
47        unknown: String,
48    },
49    /// Decode a .kute token sequence back to bytes.
50    Decode {
51        #[arg(long)]
52        vocab: PathBuf,
53        #[arg(long)]
54        input: PathBuf,
55        /// Where to write the decoded bytes. Without it, they go to stdout.
56        #[arg(long)]
57        output: Option<PathBuf>,
58        /// Refuse a sequence that would decode to more than this many bytes
59        /// or symbols. Use it for sequences from an untrusted source.
60        #[arg(long)]
61        max_units: Option<u64>,
62    },
63    /// Summarize a vocabulary, or show tokens from it.
64    Inspect {
65        vocab: PathBuf,
66        /// Show the full envelope of one token id.
67        #[arg(long)]
68        token: Option<u32>,
69        /// Show the N longest learned tokens.
70        #[arg(long, default_value_t = 0)]
71        longest: usize,
72    },
73    /// Check structure, integrity and the embedded test vectors.
74    Validate { vocab: PathBuf },
75    /// Make an Ed25519 signing key. The private half goes to the file,
76    /// unencrypted; the public half and the key's id are printed.
77    Keygen {
78        /// Where to write the private key (PEM). Must not exist.
79        #[arg(long)]
80        output: PathBuf,
81    },
82    /// Add a signature to a vocabulary. Its digest does not change.
83    Sign {
84        #[arg(long)]
85        vocab: PathBuf,
86        /// A private key made by `kute keygen`.
87        #[arg(long)]
88        key: PathBuf,
89        #[arg(long)]
90        output: PathBuf,
91        #[arg(long)]
92        force: bool,
93    },
94    /// Check a vocabulary's signatures against keys you trust. Exits 1
95    /// unless a trusted key's signature of this exact content is there.
96    Verify {
97        #[arg(long)]
98        vocab: PathBuf,
99        /// A public key as printed by `kute keygen`. Repeatable.
100        #[arg(long = "trusted-key", value_name = "BASE64", required = true)]
101        trusted_keys: Vec<String>,
102    },
103    /// Compare two vocabularies by token content.
104    Compare { a: PathBuf, b: PathBuf },
105    /// Rewrite a vocabulary in the other file form: compact binary when the
106    /// output ends in .kvfb, JSON otherwise. The digest does not change.
107    Convert {
108        #[arg(long)]
109        input: PathBuf,
110        #[arg(long)]
111        output: PathBuf,
112        /// Replace an existing output file.
113        #[arg(long)]
114        force: bool,
115    },
116    /// Convert a vocabulary to another tool's format.
117    Export {
118        #[arg(long)]
119        vocab: PathBuf,
120        #[arg(long, value_enum, default_value_t = ExportFormat::Tiktoken)]
121        format: ExportFormat,
122        /// Output file, e.g. general.tiktoken. A `.json` sidecar with the
123        /// pattern and special tokens is written next to it.
124        #[arg(long)]
125        output: PathBuf,
126    },
127    /// Measure a vocabulary on a dataset, or run the benchmark suite.
128    Benchmark {
129        #[arg(long, required_unless_present = "suite")]
130        vocab: Option<PathBuf>,
131        /// File or directory to evaluate on. Keep it separate from training data.
132        #[arg(long, required_unless_present = "suite")]
133        dataset: Option<PathBuf>,
134        /// Run the built-in benchmark program instead.
135        #[arg(long, conflicts_with_all = ["vocab", "dataset"])]
136        suite: bool,
137        /// Repository root for the suite's in-repo corpora.
138        #[arg(long)]
139        repo_root: Option<PathBuf>,
140        /// A large UTF-8 text file for the suite's real-data case (for example enwik8).
141        /// The first 90% trains a 32K vocabulary; the rest is the evaluation set.
142        #[arg(long, requires = "suite")]
143        large_text: Option<PathBuf>,
144        #[arg(long, default_value_t = 5)]
145        iterations: usize,
146        /// Also write the JSON report to this file.
147        #[arg(long)]
148        output: Option<PathBuf>,
149    },
150    /// Find recurring patterns in symbol streams, without training a tokenizer.
151    Discover(Box<DiscoverArgs>),
152    /// Derive the next version of an event vocabulary by adding symbols or
153    /// symbol sequences. Existing token ids do not change.
154    Evolve {
155        #[arg(long)]
156        vocab: PathBuf,
157        /// A symbol, or several separated by spaces for a sequence. Repeatable.
158        #[arg(long = "add", required = true, value_name = "SYMBOLS")]
159        additions: Vec<String>,
160        /// Version of the new vocabulary; must be greater than the current one.
161        #[arg(long)]
162        new_version: String,
163        #[arg(long)]
164        output: PathBuf,
165        #[arg(long)]
166        force: bool,
167    },
168    /// Exchange vocabularies and encoded messages with another kute process,
169    /// over TLS with a certificate on both sides.
170    Peer {
171        #[command(subcommand)]
172        action: PeerAction,
173    },
174    /// Serve encode, decode, inspect, compare and discover as Model Context
175    /// Protocol tools on standard input and output. Works only on the
176    /// vocabularies named here and on data passed in each call: no file is
177    /// read or written by a tool, nothing is trained, stored or published.
178    Mcp {
179        /// Vocabularies the tools may use. Repeatable.
180        #[arg(long)]
181        vocab: Vec<PathBuf>,
182        /// Most bytes of input in one encode or discover call.
183        #[arg(long, default_value_t = 1_048_576)]
184        max_input_bytes: u64,
185        /// Most bytes one decode call gives back.
186        #[arg(long, default_value_t = 4_194_304)]
187        max_output_bytes: u64,
188    },
189    /// Measure how well an entity's recent events predict its next one,
190    /// on time that was held out, against two baselines. A measurement,
191    /// not a predictor to deploy; association, not cause.
192    Predict {
193        /// JSON Lines files or directories, one event per line.
194        #[arg(long, required = true, num_args = 1..)]
195        input: Vec<PathBuf>,
196        /// Field holding the event name.
197        #[arg(long, value_name = "FIELD")]
198        symbol_field: String,
199        /// Field holding the event time, a whole number.
200        #[arg(long, value_name = "FIELD")]
201        time_field: String,
202        /// Unit of the time field: s, ms, us or ns.
203        #[arg(long, default_value = "s")]
204        time_unit: String,
205        /// Field naming the entity an event belongs to.
206        #[arg(long, value_name = "FIELD")]
207        group_field: Option<String>,
208        /// Share of the events, latest in time, held out and predicted.
209        #[arg(long, default_value_t = 0.25)]
210        holdout_fraction: f64,
211        /// Most past events the context predictor looks at (1 to 8).
212        #[arg(long, default_value_t = 3)]
213        max_context: usize,
214        /// A run of past events is used only if seen this often before the cut.
215        #[arg(long, default_value_t = 5)]
216        min_count: u64,
217        /// Parts the held-out time is cut into, to show drift.
218        #[arg(long, default_value_t = 4)]
219        windows: usize,
220        /// Resamples of the held-out entities for the intervals.
221        #[arg(long, default_value_t = 1000)]
222        resamples: usize,
223        #[arg(long, default_value_t = 1)]
224        seed: u64,
225        /// Also write the JSON report to this file.
226        #[arg(long)]
227        output: Option<PathBuf>,
228    },
229    /// Try a candidate vocabulary beside the one in use, on data neither
230    /// was made from, and decide whether it has earned its place. Encodes
231    /// every input with both; publishes and replaces nothing.
232    Shadow {
233        /// The vocabulary in use.
234        #[arg(long)]
235        parent: PathBuf,
236        /// The vocabulary proposed in its place.
237        #[arg(long)]
238        candidate: PathBuf,
239        /// Held-out inputs, each encoded as one message.
240        #[arg(long, required = true, num_args = 1..)]
241        input: Vec<PathBuf>,
242        /// What to do with a symbol a vocabulary lacks: `escape` or `strict`.
243        #[arg(long, default_value = "escape")]
244        unknown: String,
245        /// Least net saving to approve, as a share of the parent's bytes.
246        #[arg(long, default_value_t = 0.01)]
247        min_improvement: f64,
248        /// Traffic the candidate will carry, as a multiple of the inputs.
249        #[arg(long, default_value_t = 1.0)]
250        horizon: f64,
251        /// Times the candidate vocabulary file has to be sent.
252        #[arg(long, default_value_t = 1)]
253        distributions: u64,
254        /// Most the candidate may slow encoding, as a ratio.
255        #[arg(long, default_value_t = 2.0)]
256        max_slowdown: f64,
257        /// Timed passes with each vocabulary, in alternating order; the least time is used.
258        #[arg(long, default_value_t = 3)]
259        passes: usize,
260        /// Exit with status 1 when the candidate is rejected.
261        #[arg(long)]
262        fail_on_reject: bool,
263    },
264    /// Discovery over events as they arrive, by event time, in windows
265    /// that forget: JSON Lines in, one report per closed window out.
266    /// Memory is bounded by the options. Experimental.
267    Live {
268        /// JSON Lines to read; standard input when absent.
269        input: Option<PathBuf>,
270        /// Field holding the event name.
271        #[arg(long, value_name = "FIELD")]
272        symbol_field: String,
273        /// Field holding the time, a whole number of any unit.
274        #[arg(long, value_name = "FIELD")]
275        time_field: String,
276        /// Field naming the entity an event belongs to.
277        #[arg(long, value_name = "FIELD")]
278        group_field: Option<String>,
279        /// Length of a pane, in the unit of the time field.
280        #[arg(long)]
281        pane: i64,
282        /// Panes in a window: 1 for tumbling windows, more for a sliding one.
283        #[arg(long, default_value_t = 1)]
284        panes: usize,
285        /// How far behind the latest time an event may arrive and still count.
286        #[arg(long, default_value_t = 0)]
287        lateness: i64,
288        /// An event that ends its entity's sequence: once counted, the
289        /// entity is forgotten and its place freed. Repeatable.
290        #[arg(long = "end-on", value_name = "EVENT")]
291        end_on: Vec<String>,
292        /// Start an entity's sequence afresh when its last event was
293        /// more than this long ago, in the unit of --pane; and let
294        /// entities idle that long go first when places run out.
295        #[arg(long, value_name = "TICKS")]
296        idle: Option<i64>,
297        /// Events held waiting to be put in time order.
298        #[arg(long, default_value_t = 100_000)]
299        max_buffered: usize,
300        /// Longest sequence counted.
301        #[arg(long, default_value_t = 6)]
302        max_length: usize,
303        /// Distinct event names known; later ones are folded together.
304        #[arg(long, default_value_t = 65_536)]
305        max_symbols: usize,
306        /// Sequences counted at each length in each pane.
307        #[arg(long, default_value_t = 200_000)]
308        max_candidates: usize,
309        /// Entities whose recent events are remembered.
310        #[arg(long, default_value_t = 100_000)]
311        max_entities: usize,
312        #[arg(long, default_value_t = 5)]
313        min_support: u64,
314        #[arg(long, default_value_t = 1.0)]
315        min_cohesion_bits: f64,
316        /// Patterns in each report.
317        #[arg(long, default_value_t = 100)]
318        max_patterns: usize,
319        /// File the state is saved to as windows close.
320        #[arg(long)]
321        checkpoint: Option<PathBuf>,
322        /// Save after this many window reports.
323        #[arg(long, default_value_t = 1)]
324        checkpoint_every: u64,
325        /// Start from the checkpoint, passing over the input it had read.
326        #[arg(long)]
327        resume: bool,
328        /// Count lines that are not events and go on, instead of stopping.
329        #[arg(long)]
330        skip_bad_lines: bool,
331    },
332    /// Complete event records (entity, time and every other field) packed
333    /// by column into one container, and back. Experimental.
334    Events {
335        #[command(subcommand)]
336        action: EventsAction,
337    },
338    /// A sequence of numbers kept exactly, or within an error bound that
339    /// is checked on every value, in one container, and back. Experimental.
340    Signals {
341        #[command(subcommand)]
342        action: SignalsAction,
343    },
344    /// Serve encode, decode, inspect, compare and discover over HTTP, under
345    /// /v1/. Read-only, like `kute mcp`, and through the same code. No TLS
346    /// and no authentication: it listens on loopback unless told otherwise.
347    Serve {
348        /// Vocabularies the operations may use. Repeatable.
349        #[arg(long)]
350        vocab: Vec<PathBuf>,
351        /// Address to listen on. Port 0 picks a free one; the address in
352        /// use is printed as JSON on standard output.
353        #[arg(long, default_value = "127.0.0.1:8787")]
354        listen: String,
355        /// Allow an address that is not loopback. Anyone who can reach it
356        /// can use it: there is no TLS and no authentication.
357        #[arg(long)]
358        insecure_remote: bool,
359        /// Also serve KUTE Studio, a page for looking at what the service
360        /// holds and does, at /studio. Loopback only. The page loads
361        /// nothing from outside and calls only this service.
362        #[arg(long)]
363        studio: bool,
364        /// Also give the files of the vocabularies named with --vocab to
365        /// whoever asks, by digest, under /v1/vocabularies (`kute fetch`
366        /// takes them). Read-only: nothing can be sent to it.
367        #[arg(long)]
368        registry: bool,
369        /// Be a registry and nothing else: the five operations are not
370        /// answered, so no caller can make this process compute.
371        #[arg(long, conflicts_with = "studio")]
372        registry_only: bool,
373        /// Another registry (http://host:port) to ask for a vocabulary
374        /// this one does not hold. What comes back is checked as `kute
375        /// fetch` checks it, kept in memory, and given on. Repeatable;
376        /// asked in the order given. Needs --registry or --registry-only.
377        #[arg(long, value_name = "URL")]
378        upstream: Vec<String>,
379        /// Keep an upstream file only if a key named here signed it: a
380        /// public key (ed25519:...) or a key file. Repeatable. Without
381        /// it an upstream file is checked against its digest and its
382        /// test vectors, and passed on whoever signed it or nobody.
383        #[arg(long, value_name = "KEY")]
384        upstream_trusted_key: Vec<String>,
385        /// Seconds to wait for one upstream.
386        #[arg(long, default_value_t = 10)]
387        upstream_timeout: u64,
388        /// Largest file taken from an upstream.
389        #[arg(long, default_value_t = 16_777_216)]
390        upstream_max_bytes: u64,
391        /// Most bytes of upstream files kept in memory; the oldest go first.
392        #[arg(long, default_value_t = 67_108_864)]
393        upstream_cache_bytes: u64,
394        /// Most bytes of input in one encode or discover call.
395        #[arg(long, default_value_t = 1_048_576)]
396        max_input_bytes: u64,
397        /// Most bytes one decode call gives back.
398        #[arg(long, default_value_t = 4_194_304)]
399        max_output_bytes: u64,
400        /// Requests handled at once.
401        #[arg(long, default_value_t = 4)]
402        workers: usize,
403        /// Seconds a request may take to arrive.
404        #[arg(long, default_value_t = 10)]
405        timeout: u64,
406    },
407    /// Take a vocabulary from a registry (`kute serve --registry`) by its
408    /// digest. The digest is recomputed from what arrives and the file is
409    /// written only if it matches; with --trusted-key, only if one of
410    /// those keys signed it. Plain HTTP: the registry and the network are
411    /// not trusted with the content, and can see it.
412    Fetch {
413        /// A registry, as http://host:port. Repeatable: they are asked
414        /// in the order given, and the first that gives the vocabulary
415        /// and passes every check is used. --timeout is for each.
416        #[arg(long, required = true)]
417        from: Vec<String>,
418        /// The vocabulary wanted: sha256: and 64 hex digits.
419        #[arg(long, required_unless_present = "list", conflicts_with = "list")]
420        digest: Option<String>,
421        /// Where to write it.
422        #[arg(long, required_unless_present = "list")]
423        output: Option<PathBuf>,
424        /// Keep the vocabulary only if one of these keys signed it (the
425        /// base64 public key `kute keygen` prints). Repeatable.
426        #[arg(long = "trusted-key", value_name = "BASE64")]
427        trusted_keys: Vec<String>,
428        /// Replace the output if it exists.
429        #[arg(long)]
430        force: bool,
431        /// Print what the registry says it holds, and fetch nothing.
432        #[arg(long)]
433        list: bool,
434        /// Largest file taken. All of it is held and read before its
435        /// digest is known, so this is what a registry can make this
436        /// process hold. A vocabulary of 32,768 tokens is about 3 MB.
437        #[arg(long, default_value_t = 67_108_864)]
438        max_bytes: u64,
439        /// Seconds the whole exchange may take.
440        #[arg(long, default_value_t = 60)]
441        timeout: u64,
442    },
443    /// List registered algorithms and adapters and what each declares.
444    Capabilities,
445    /// Write the seeded example datasets used by the documentation.
446    SampleData {
447        /// Directory to create the files in.
448        #[arg(long)]
449        output: PathBuf,
450    },
451}
452
453#[derive(Clone, Copy, ValueEnum)]
454enum ExportFormat {
455    Tiktoken,
456}
457
458#[derive(Subcommand)]
459enum EventsAction {
460    /// Pack JSON Lines, one object per event, keeping every field.
461    Pack {
462        /// JSON Lines to read.
463        input: PathBuf,
464        /// Container to write.
465        #[arg(long)]
466        output: PathBuf,
467        /// Field holding the event name.
468        #[arg(long, value_name = "FIELD")]
469        symbol_field: String,
470        /// Field holding the time, a whole number.
471        #[arg(long, value_name = "FIELD")]
472        time_field: Option<String>,
473        /// Field naming the entity an event belongs to.
474        #[arg(long, value_name = "FIELD")]
475        group_field: Option<String>,
476        /// How columns are compressed: zstd, or zlib for a container that
477        /// needs only a zlib reader. The default is zstd when this build
478        /// has it (the `zstd` feature, on unless turned off) and zlib
479        /// when it does not.
480        #[arg(long)]
481        codec: Option<String>,
482    },
483    /// Write the records back as canonical JSON Lines, in source order.
484    Unpack {
485        input: PathBuf,
486        /// File to write; standard output when absent.
487        #[arg(long)]
488        output: Option<PathBuf>,
489        /// Refuse a container that unpacks to more bytes than this.
490        #[arg(long, default_value_t = 1 << 32)]
491        max_bytes: u64,
492    },
493    /// Show a container's header: layout, counts, digest and columns.
494    Inspect { input: PathBuf },
495}
496
497#[derive(Subcommand)]
498enum SignalsAction {
499    /// Pack one number per line (or one column of a delimited file).
500    Pack {
501        /// Text, one value per line. An empty value, `?`, `NA` or `NaN`
502        /// is a missing value and comes back as NaN.
503        input: PathBuf,
504        #[arg(long)]
505        output: PathBuf,
506        /// Keep every finite value within this absolute error instead of
507        /// exactly. Values that are not finite are still kept exactly.
508        #[arg(long, value_name = "ERROR")]
509        max_error: Option<f64>,
510        /// How the parts are compressed: zstd or zlib. The default is
511        /// zstd when this build has it and zlib when it does not.
512        #[arg(long)]
513        codec: Option<String>,
514        /// Take this column of each line, counting from 1.
515        #[arg(long, requires = "delimiter")]
516        column: Option<usize>,
517        /// The character between columns.
518        #[arg(long, requires = "column")]
519        delimiter: Option<char>,
520        /// Lines to pass over at the top, such as a header.
521        #[arg(long, default_value_t = 0)]
522        skip_lines: usize,
523    },
524    /// Write the values, one per line, in the shortest form that reads
525    /// back as the same number.
526    Unpack {
527        input: PathBuf,
528        /// Where to write; standard output when absent.
529        #[arg(long)]
530        output: Option<PathBuf>,
531        /// Refuse a container holding more values than this. Reading can
532        /// take about 44 bytes of memory a value, so the default allows
533        /// about 740 MB.
534        #[arg(long, default_value_t = 1 << 24)]
535        max_values: u64,
536    },
537    /// Print the container's header: the contract and what it measured.
538    Inspect { input: PathBuf },
539}
540
541#[derive(Subcommand)]
542enum PeerAction {
543    /// Wait for one connection and answer it until it closes.
544    Serve {
545        /// Address to listen on, e.g. 127.0.0.1:7411.
546        #[arg(long)]
547        listen: String,
548        /// Vocabularies this side already holds. Repeatable.
549        #[arg(long)]
550        vocab: Vec<PathBuf>,
551        /// Take vocabularies this side does not already hold. Off by
552        /// default: the other side can add nothing unless told it may.
553        #[arg(long)]
554        accept_vocabularies: bool,
555        /// Let the other side extend vocabularies held here.
556        #[arg(long)]
557        accept_proposals: bool,
558        /// Take a vocabulary from the other side only if it carries a
559        /// valid signature from one of these keys (the base64 public key
560        /// `kute keygen` prints). Repeatable. Vocabularies given with
561        /// --vocab are yours and are not checked. With --accept-proposals,
562        /// a proposal is taken only if it carries such a signature of the
563        /// vocabulary it derives (`kute peer send --sign-with`).
564        #[arg(long, value_name = "PUBLIC_KEY", requires = "accept_vocabularies")]
565        require_signature_from: Vec<String>,
566        /// Send a held vocabulary's file to the other side when it asks.
567        #[arg(long)]
568        give_vocabularies: bool,
569        /// Answer whether a held vocabulary has a token for given symbols.
570        #[arg(long)]
571        answer_queries: bool,
572        /// Re-encode the other side's sequences under another held vocabulary.
573        #[arg(long)]
574        translate: bool,
575        /// Give up on a connection that sends nothing for this many
576        /// seconds, during the handshake or after. 0 waits forever.
577        #[arg(long, default_value_t = 30)]
578        timeout: u64,
579        /// Serve over a plain socket: no encryption, and whoever connects
580        /// is served. Required when no TLS options are given.
581        #[arg(long, conflicts_with = "tls_cert")]
582        insecure_plain: bool,
583        /// Refuse a message that decodes to more than this many units.
584        #[arg(long, default_value_t = 268_435_456)]
585        max_units: u64,
586        /// Write each decoded message and each vocabulary received here.
587        #[arg(long)]
588        output_dir: Option<PathBuf>,
589        /// This side's certificate chain (PEM). With --tls-key,
590        /// --tls-client-ca and --allow, the connection is TLS 1.3 with a
591        /// certificate on both sides. A connection that fails the
592        /// handshake or is not allowed is refused and the next one awaited.
593        #[arg(long, requires_all = ["tls_key", "tls_client_ca"])]
594        tls_cert: Option<PathBuf>,
595        /// This side's private key (PEM).
596        #[arg(long, requires = "tls_cert")]
597        tls_key: Option<PathBuf>,
598        /// Authorities whose client certificates are accepted (PEM).
599        #[arg(long, requires = "tls_cert")]
600        tls_client_ca: Option<PathBuf>,
601        /// A peer that may connect, by certificate fingerprint as printed
602        /// by `kute peer fingerprint`. Repeatable. Anyone else is refused,
603        /// even with a certificate from an accepted authority. The
604        /// fingerprint is of the certificate, not the key: a renewed
605        /// certificate has to be allowed again, and removing a fingerprint
606        /// is the only revocation.
607        #[arg(long, value_name = "SHA256", requires = "tls_cert")]
608        allow: Vec<String>,
609    },
610    /// Connect, make sure the other side holds the vocabulary, and send files.
611    Send {
612        /// Address to connect to.
613        #[arg(long)]
614        connect: String,
615        #[arg(long)]
616        vocab: PathBuf,
617        /// Files to encode and send. Repeatable.
618        #[arg(long, num_args = 0..)]
619        input: Vec<PathBuf>,
620        /// strict or escape; see `kute encode --unknown`.
621        #[arg(long, default_value = "strict")]
622        unknown: String,
623        /// Before sending, propose these additions (as in `kute evolve --add`).
624        #[arg(long = "propose", value_name = "SYMBOLS", requires = "new_version")]
625        additions: Vec<String>,
626        #[arg(long)]
627        new_version: Option<String>,
628        /// Sign the vocabulary the proposal derives with this private key
629        /// (as `kute sign` would), and send the signature with the
630        /// proposal. For a peer that requires signatures.
631        #[arg(long, value_name = "KEY", requires = "new_version")]
632        sign_with: Option<PathBuf>,
633        /// This side's certificate chain (PEM); with --tls-key and --tls-ca
634        /// the connection is TLS 1.3 with a certificate on both sides.
635        #[arg(long, requires_all = ["tls_key", "tls_ca"])]
636        tls_cert: Option<PathBuf>,
637        /// This side's private key (PEM).
638        #[arg(long, requires = "tls_cert")]
639        tls_key: Option<PathBuf>,
640        /// Authorities whose server certificates are accepted (PEM).
641        #[arg(long, requires = "tls_cert")]
642        tls_ca: Option<PathBuf>,
643        /// The name the server's certificate must carry. Default: the host
644        /// part of --connect.
645        #[arg(long, requires = "tls_cert")]
646        server_name: Option<String>,
647        /// Talk only to the server with this certificate fingerprint.
648        /// Without it, any server the authority issued a certificate for
649        /// the name is accepted, which is less than the server asks of you.
650        #[arg(long, value_name = "SHA256", requires = "tls_cert")]
651        server_fingerprint: Option<String>,
652        /// Connect over a plain socket: no encryption and no check of who
653        /// answers. Required when no TLS options are given.
654        #[arg(long, conflicts_with = "tls_cert")]
655        insecure_plain: bool,
656    },
657    /// Print the fingerprint that identifies a certificate to `--allow`.
658    Fingerprint {
659        /// A certificate (PEM). The first one in the file is used.
660        #[arg(long)]
661        cert: PathBuf,
662    },
663}
664
665const NO_TRANSPORT: &str = "give the TLS options (--tls-cert, --tls-key and an authority file), or --insecure-plain for a socket with no encryption and no authentication";
666
667/// A plain or an encrypted connection.
668trait Stream: std::io::Read + std::io::Write {}
669impl<T: std::io::Read + std::io::Write> Stream for T {}
670
671fn split_additions(additions: &[String]) -> Vec<Vec<String>> {
672    additions.iter().map(|a| a.split_whitespace().map(str::to_string).collect()).collect()
673}
674
675fn peer(engine: Engine, action: PeerAction) -> kute::Result<()> {
676    use kute_protocol::{tls, Framed, Peer, Policy, Session, DEFAULT_MAX_FRAME};
677    match action {
678        PeerAction::Fingerprint { cert } => {
679            let chain = tls::load_certificates(&cert)?;
680            print(&json!({ "certificate": cert, "fingerprint": tls::fingerprint(&chain[0]) }))
681        }
682        PeerAction::Serve {
683            listen,
684            vocab: held,
685            accept_vocabularies,
686            accept_proposals,
687            require_signature_from,
688            give_vocabularies,
689            answer_queries,
690            translate,
691            timeout,
692            insecure_plain,
693            max_units,
694            output_dir,
695            tls_cert,
696            tls_key,
697            tls_client_ca,
698            allow,
699        } => {
700            let policy = Policy { accept_vocabularies, accept_proposals, give_vocabularies, answer_queries, translate, max_decoded_units: max_units, ..Policy::default() };
701            if tls_cert.is_none() && !insecure_plain {
702                return Err(KuteError::InvalidConfig(NO_TRANSPORT.into()));
703            }
704            // Read the trusted keys before listening: a key that cannot be
705            // read is the operator's mistake, to be told now and not to
706            // whoever connects first.
707            let gate = if require_signature_from.is_empty() { None } else { Some(sign::gate(&require_signature_from)?) };
708            let timeout = (timeout > 0).then(|| std::time::Duration::from_secs(timeout));
709            let secured = match (&tls_cert, &tls_key, &tls_client_ca) {
710                (Some(cert), Some(key), Some(ca)) => {
711                    if allow.is_empty() {
712                        return Err(KuteError::InvalidConfig("with TLS, name at least one peer with --allow; nobody is allowed otherwise".into()));
713                    }
714                    let mut access = tls::Access::new();
715                    for fingerprint in &allow {
716                        access.allow(fingerprint, policy.clone())?;
717                    }
718                    Some((tls::server_config(tls::load_certificates(cert)?, tls::load_private_key(key)?, tls::load_certificates(ca)?)?, access))
719                }
720                _ => None,
721            };
722            let listener = std::net::TcpListener::bind(&listen)?;
723            // Lines to standard error are written without `eprintln!`, which
724            // panics when the stream is closed: a parent that stopped reading
725            // would otherwise let the next refused connection end the server.
726            let _ = writeln!(std::io::stderr(), "listening on {}", listener.local_addr()?);
727            if secured.is_none() {
728                let _ = writeln!(std::io::stderr(), "warning: no TLS. The connection is not encrypted and whoever connects is served.");
729            }
730            // With TLS, a connection that fails the handshake, stalls in
731            // it, or is not allowed does not end the listener: whoever can
732            // reach the port could otherwise stop it before the allowed peer
733            // arrives.
734            let (stream, identity, policy, from): (Box<dyn Stream>, Option<String>, Policy, std::net::SocketAddr) = loop {
735                let (tcp, from) = listener.accept()?;
736                tcp.set_read_timeout(timeout)?;
737                tcp.set_write_timeout(timeout)?;
738                let Some((config, access)) = &secured else { break (Box::new(tcp), None, policy, from) };
739                match tls::accept(config, tcp).and_then(|(stream, who)| Ok((stream, access.policy_for(&who)?, who))) {
740                    Ok((stream, policy, who)) => break (Box::new(stream), Some(who.fingerprint), policy, from),
741                    Err(e) => {
742                        let _ = writeln!(std::io::stderr(), "refused {from}: {e}");
743                    }
744                }
745            };
746            let mut peer = Peer::new("kute", engine, policy);
747            if let Some(gate) = gate {
748                peer.require_vocabulary_check(Box::new(gate));
749            }
750            for path in &held {
751                peer.add_vocabulary(vocab::load(path)?)?;
752            }
753            let before = peer.digests();
754            let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
755            let handled = session.serve()?;
756            let inbox = session.peer.take_inbox();
757            let new: Vec<String> = session.peer.digests().into_iter().filter(|d| !before.contains(d)).collect();
758            // Nothing received, nothing created.
759            if let Some(dir) = output_dir.as_ref().filter(|_| !inbox.is_empty() || !new.is_empty()) {
760                std::fs::create_dir_all(dir)?;
761                for message in &inbox {
762                    std::fs::write(dir.join(format!("message-{}.bin", message.id)), &message.bytes)?;
763                }
764                for digest in &new {
765                    if let Some(v) = session.peer.vocabulary(digest) {
766                        let name = format!("{}-{}.kvf", v.id().as_str().replace(':', "_"), v.version());
767                        vocab::save(v, dir.join(name), true)?;
768                    }
769                }
770            }
771            print(&json!({
772                "from": from.to_string(),
773                "peer_identity": identity,
774                "messages_handled": handled,
775                "vocabularies_received": new,
776                "received": inbox.iter().map(|m| json!({
777                    "id": m.id,
778                    "bytes": m.bytes.len(),
779                    "tokens": m.sequence.ids.len(),
780                    "escaped_symbols": m.sequence.escapes.len(),
781                    "vocabulary": format!("{} {}", m.sequence.vocabulary_id, m.sequence.vocabulary_version),
782                })).collect::<Vec<_>>(),
783            }))
784        }
785        PeerAction::Send { connect, vocab: vocab_path, input, unknown, additions, new_version, sign_with, tls_cert, tls_key, tls_ca, server_name, server_fingerprint, insecure_plain } => {
786            // Read the key before connecting: one that cannot be read
787            // is this side's mistake, to be told before anything is sent.
788            let signer = sign_with.as_deref().map(sign::signer).transpose()?;
789            if tls_cert.is_none() && !insecure_plain {
790                return Err(KuteError::InvalidConfig(NO_TRANSPORT.into()));
791            }
792            let policy = kute::UnknownPolicy::parse(&unknown)?;
793            let mut peer = Peer::new("kute", engine, Policy::default());
794            let mut digest = peer.add_vocabulary(vocab::load(&vocab_path)?)?;
795            let tcp = std::net::TcpStream::connect(&connect)?;
796            let (stream, server_identity): (Box<dyn Stream>, Option<String>) = match (&tls_cert, &tls_key, &tls_ca) {
797                (Some(cert), Some(key), Some(ca)) => {
798                    let config = tls::client_config(tls::load_certificates(cert)?, tls::load_private_key(key)?, tls::load_certificates(ca)?)?;
799                    let host = connect.rsplit_once(':').map_or(connect.as_str(), |(host, _)| host);
800                    let (stream, who) = tls::connect(&config, server_name.as_deref().unwrap_or(host), tcp)?;
801                    if server_fingerprint.as_ref().is_some_and(|wanted| *wanted != who.fingerprint) {
802                        return Err(KuteError::Integrity(format!("the server is {}, not the one named by --server-fingerprint", who.fingerprint)));
803                    }
804                    (Box::new(stream), Some(who.fingerprint))
805                }
806                _ => (Box::new(tcp), None),
807            };
808            let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
809            let remote = session.connect()?;
810            let transferred = session.share(&digest)?;
811            let mut proposed = None;
812            if let Some(version) = &new_version {
813                digest = match &signer {
814                    Some(signer) => session.propose_signed(&digest, &split_additions(&additions), version, signer)?,
815                    None => session.propose(&digest, &split_additions(&additions), version)?,
816                };
817                proposed = Some(digest.clone());
818            }
819            let mut sent = Vec::new();
820            for path in &input {
821                let raw = std::fs::read(path)?;
822                let units = session.send(&digest, &raw, policy)?;
823                sent.push(json!({ "input": path, "bytes": raw.len(), "units_decoded_by_peer": units, "receipt_matches": true }));
824            }
825            print(&json!({
826                "peer": remote.peer,
827                "peer_software": remote.software,
828                "server_identity": server_identity,
829                "vocabulary_transferred": transferred,
830                "vocabulary_after_proposal": proposed,
831                "proposal_signed": proposed.is_some() && sign_with.is_some(),
832                "sent": sent,
833            }))
834        }
835    }
836}
837
838#[derive(clap::Args)]
839struct DiscoverArgs {
840    /// Files or directories to look for patterns in.
841    #[arg(long, required = true, num_args = 1..)]
842    input: Vec<PathBuf>,
843    /// Adapter that turns each file into one record of symbols.
844    #[arg(long, default_value = "jsonl-events")]
845    adapter: String,
846    /// Adapter option as key=value. Repeatable.
847    #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
848    adapter_options: Vec<String>,
849    /// Read plain text instead of using an adapter: every line is one
850    /// record, symbols separated by whitespace.
851    #[arg(long, conflicts_with_all = ["adapter", "adapter_options"])]
852    lines: bool,
853    /// Read typed events instead: JSON Lines with one event per line, the
854    /// event name in this field. Keeps time and grouping; see the other
855    /// --*-field options.
856    #[arg(long, value_name = "FIELD", conflicts_with_all = ["adapter", "adapter_options", "lines"])]
857    symbol_field: Option<String>,
858    /// Field with the event time, a whole number of --time-unit. With it,
859    /// the report says how long each pattern takes.
860    #[arg(long, value_name = "FIELD", requires = "symbol_field")]
861    time_field: Option<String>,
862    /// Unit of the time field: s, ms, us or ns.
863    #[arg(long, default_value = "s", requires = "time_field")]
864    time_unit: String,
865    /// Field naming what an event belongs to (a device, a block, a session).
866    /// Events with the same value form one record.
867    #[arg(long, value_name = "FIELD", requires = "symbol_field")]
868    group_field: Option<String>,
869    /// Name recorded for this way of reading the events.
870    #[arg(long, default_value = "kute:events:unnamed", requires = "symbol_field")]
871    schema_id: String,
872    /// Files with held-out data to check the patterns against.
873    #[arg(long, num_args = 1.., conflicts_with = "holdout_fraction")]
874    holdout: Vec<PathBuf>,
875    /// Hold out this share of the input instead. With --lines the last
876    /// records are held out; otherwise the end of each record.
877    #[arg(long)]
878    holdout_fraction: Option<f64>,
879    #[arg(long, default_value_t = 5)]
880    min_support: u64,
881    /// Longest contiguous pattern, in symbols.
882    #[arg(long, default_value_t = 8)]
883    max_length: usize,
884    /// Minimum cohesion in bits: how much more often than chance.
885    #[arg(long, default_value_t = 1.0)]
886    min_cohesion: f64,
887    /// Gapped pairs look this many symbols ahead; 0 turns them off.
888    #[arg(long, default_value_t = 8)]
889    window: usize,
890    /// Report at most this many patterns of each kind.
891    #[arg(long, default_value_t = 50)]
892    top: usize,
893    /// Also run on a shuffled copy of the input (same symbol counts, no
894    /// order) and report how much the method finds there.
895    #[arg(long)]
896    control: bool,
897    /// Also write the JSON report to this file.
898    #[arg(long)]
899    output: Option<PathBuf>,
900}
901
902fn read_records(engine: &Engine, args: &DiscoverArgs, paths: &[PathBuf]) -> kute::Result<Vec<Vec<String>>> {
903    let mut adapter_config = AdapterConfig::default();
904    for option in &args.adapter_options {
905        let (key, value) = option
906            .split_once('=')
907            .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
908        adapter_config = adapter_config.with(key, value);
909    }
910    let mut records = Vec::new();
911    for path in paths {
912        for file in kute::collect_files(path)? {
913            let raw = std::fs::read(&file)?;
914            if args.lines {
915                let text = String::from_utf8(raw).map_err(|_| KuteError::InvalidInput(format!("{}: not UTF-8", file.display())))?;
916                records.extend(text.lines().map(|l| l.split_whitespace().map(str::to_string).collect::<Vec<_>>()).filter(|r| !r.is_empty()));
917            } else {
918                let input = engine.registry().adapter(&args.adapter)?.ingest(&raw, &adapter_config)?;
919                records.extend(kute_discover::records_of(&[input])?);
920            }
921        }
922    }
923    if records.is_empty() {
924        return Err(KuteError::InvalidInput("no records found in the input".into()));
925    }
926    Ok(records)
927}
928
929fn read_events(args: &DiscoverArgs, symbol_field: &str, paths: &[PathBuf]) -> kute::Result<kute::EventStream> {
930    let schema = kute::EventSchema {
931        id: args.schema_id.clone(),
932        version: 1,
933        symbol_field: symbol_field.to_string(),
934        time_unit: args.time_field.as_ref().map(|_| kute::TimeUnit::parse(&args.time_unit)).transpose()?,
935        time_field: args.time_field.clone(),
936        group_field: args.group_field.clone(),
937    };
938    let mut stream = kute::EventStream::new(schema)?;
939    for path in paths {
940        for file in kute::collect_files(path)? {
941            let reader = std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(&file)?);
942            stream.read_jsonl(reader, &file.display().to_string())?;
943        }
944    }
945    if stream.records.is_empty() {
946        return Err(KuteError::InvalidInput("no events found in the input".into()));
947    }
948    Ok(stream)
949}
950
951/// Lend a stream's symbols out as plain records, and give them back.
952fn take_symbols(stream: &mut kute::EventStream) -> Vec<Vec<String>> {
953    stream.records.iter_mut().map(|r| std::mem::take(&mut r.symbols)).collect()
954}
955
956fn give_symbols(stream: &mut kute::EventStream, records: Vec<Vec<String>>) {
957    for (r, symbols) in stream.records.iter_mut().zip(records) {
958        r.symbols = symbols;
959    }
960}
961
962fn describe(stream: &kute::EventStream) -> kute::Result<serde_json::Value> {
963    Ok(json!({ "records": stream.records.len(), "events": stream.events(), "fingerprint": stream.fingerprint()? }))
964}
965
966fn discover(engine: &Engine, args: DiscoverArgs) -> kute::Result<()> {
967    use kute_discover as kd;
968    let params = kd::Params {
969        min_support: args.min_support,
970        max_length: args.max_length,
971        min_cohesion_bits: args.min_cohesion,
972        window: args.window,
973        max_patterns: args.top,
974        ..kd::Params::default()
975    };
976    // Typed events: the symbols go through discovery like any others, and
977    // the streams keep their times for the timing pass afterwards.
978    let mut streams: Option<(kute::EventStream, Option<kute::EventStream>)> = match &args.symbol_field {
979        None => None,
980        Some(field) => {
981            let stream = read_events(&args, field, &args.input)?;
982            Some(if !args.holdout.is_empty() {
983                (stream, Some(read_events(&args, field, &args.holdout)?))
984            } else if let Some(fraction) = args.holdout_fraction {
985                let (head, tail) = stream.split_last(fraction)?;
986                (head, Some(tail))
987            } else {
988                (stream, None)
989            })
990        }
991    };
992    let typed = streams.is_some();
993    let mut records = match &mut streams {
994        Some((stream, _)) => take_symbols(stream),
995        None => read_records(engine, &args, &args.input)?,
996    };
997    let mut held_out = match &mut streams {
998        Some((_, held)) => held.as_mut().map(take_symbols),
999        None if args.holdout.is_empty() => None,
1000        None => Some(read_records(engine, &args, &args.holdout)?),
1001    };
1002    if let Some(fraction) = args.holdout_fraction.filter(|_| !typed) {
1003        if args.lines {
1004            if !(fraction > 0.0 && fraction < 1.0) {
1005                return Err(KuteError::InvalidConfig("the held-out fraction must be between 0 and 1".into()));
1006            }
1007            let cut = ((records.len() as f64) * (1.0 - fraction)).round() as usize;
1008            held_out = Some(records.split_off(cut.clamp(1, records.len())));
1009        } else {
1010            let (head, tail) = kd::split_holdout(&records, fraction)?;
1011            records = head;
1012            held_out = Some(tail);
1013        }
1014    }
1015    let start = std::time::Instant::now();
1016    let found = kd::discover(&records, &params)?;
1017    let seconds = start.elapsed().as_secs_f64();
1018    let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
1019    let control = if args.control {
1020        let found = kd::discover(&kd::shuffled(&records, 0), &params)?;
1021        let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
1022        Some(json!({
1023            "what": "the same run on a shuffled copy of the input: same symbol counts, no order",
1024            "patterns": found.patterns.len(),
1025            "strongest_evidence_bits": found.patterns.iter().map(|p| p.evidence_bits).fold(0.0, f64::max),
1026            "coverage": found.coverage,
1027            "held_out_confirmed": evaluation.as_ref().map(|e| e.confirmed),
1028            "held_out_coverage": evaluation.as_ref().map(|e| e.coverage),
1029        }))
1030    } else {
1031        None
1032    };
1033    let events = match streams {
1034        None => None,
1035        Some((mut stream, mut held)) => {
1036            give_symbols(&mut stream, records);
1037            if let (Some(h), Some(symbols)) = (held.as_mut(), held_out) {
1038                give_symbols(h, symbols);
1039            }
1040            let timing = if stream.timed() { Some(kd::timing(&found, &stream)?) } else { None };
1041            let held_timing = match &held {
1042                Some(h) if h.timed() => Some(kd::timing(&found, h)?),
1043                _ => None,
1044            };
1045            Some(json!({
1046                "schema": stream.schema,
1047                "searched": describe(&stream)?,
1048                "held_out": held.as_ref().map(describe).transpose()?,
1049                "timing_what": "per pattern, in the schema's time unit: time from the first event of an occurrence to its last; for a gapped pair, from the first symbol to the nearest second symbol within the window",
1050                "timing": timing,
1051                "held_out_timing": held_timing,
1052            }))
1053        }
1054    };
1055    let report = json!({
1056        "kute_version": kute::KUTE_VERSION,
1057        "discover_seconds": seconds,
1058        "peak_memory_bytes": kute_bench::peak_memory_bytes(),
1059        "discovery": found,
1060        "held_out": evaluation,
1061        "control": control,
1062        "events": events,
1063    });
1064    if let Some(path) = &args.output {
1065        std::fs::write(path, serde_json::to_vec_pretty(&report)?)?;
1066    }
1067    print(&report)
1068}
1069
1070#[derive(clap::Args)]
1071struct TrainArgs {
1072    /// Files or directories to train on. Directories are read recursively.
1073    #[arg(long, required = true, num_args = 1..)]
1074    input: Vec<PathBuf>,
1075    /// Vocabulary identifier, e.g. kute:industrial:events.
1076    #[arg(long)]
1077    id: String,
1078    /// Vocabulary version (semantic versioning).
1079    #[arg(long, default_value = "0.1.0")]
1080    vocab_version: String,
1081    #[arg(long, default_value = "bpe")]
1082    algorithm: String,
1083    #[arg(long, default_value = "text")]
1084    adapter: String,
1085    /// Adapter option as key=value. Repeatable.
1086    #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
1087    adapter_options: Vec<String>,
1088    #[arg(long, default_value_t = 4096)]
1089    vocab_size: u32,
1090    /// none, gpt4, or regex:<pattern>. Default: gpt4 for the text adapter, none otherwise.
1091    #[arg(long)]
1092    pretokenizer: Option<String>,
1093    #[arg(long, default_value_t = 1)]
1094    min_frequency: u64,
1095    #[arg(long)]
1096    max_token_length: Option<usize>,
1097    /// Reserved (special) token. Repeatable.
1098    #[arg(long = "reserved")]
1099    reserved: Vec<String>,
1100    /// File with one dictionary entry per line, for the dictionary algorithm.
1101    #[arg(long)]
1102    dictionary_file: Option<PathBuf>,
1103    #[arg(long)]
1104    description: Option<String>,
1105    /// License of the vocabulary, e.g. an SPDX identifier.
1106    #[arg(long)]
1107    license: Option<String>,
1108    /// Read input files in pieces of about this many bytes, cut at line
1109    /// breaks, so memory does not grow with file size. Recorded in the
1110    /// vocabulary, because it decides where records end.
1111    #[arg(long, value_name = "BYTES")]
1112    stream_bytes: Option<usize>,
1113    /// Continue from a vocabulary trained earlier on the same input with the
1114    /// same settings and a smaller --vocab-size. The result is the same as
1115    /// one run to the new size. bpe and sequence-bpe. Its merges are taken
1116    /// as given: resume only from a vocabulary you trained or trust.
1117    #[arg(long, value_name = "VOCAB")]
1118    resume_from: Option<PathBuf>,
1119    /// Store the start of the first training records in the vocabulary as
1120    /// self-test vectors, so anyone holding the file can check it. They are
1121    /// verbatim excerpts: leave this off when the corpus is private.
1122    #[arg(long, conflicts_with = "no_test_vectors")]
1123    embed_test_vectors: bool,
1124    /// Accepted for compatibility; this is the default since v0.4.0.
1125    #[arg(long, hide = true)]
1126    no_test_vectors: bool,
1127    #[arg(long)]
1128    output: PathBuf,
1129    /// Replace an existing output file even if its content differs.
1130    #[arg(long)]
1131    force: bool,
1132}
1133
1134fn print(value: &impl serde::Serialize) -> kute::Result<()> {
1135    let text = serde_json::to_string_pretty(value)?;
1136    let mut out = std::io::stdout().lock();
1137    writeln!(out, "{text}")?;
1138    Ok(())
1139}
1140
1141fn parse_pretokenizer(spec: Option<&str>, adapter: &str) -> kute::Result<Pretokenizer> {
1142    match spec {
1143        None => Ok(if adapter == "text" { Pretokenizer::Gpt4 } else { Pretokenizer::None }),
1144        Some("none") => Ok(Pretokenizer::None),
1145        Some("gpt4") => Ok(Pretokenizer::Gpt4),
1146        Some(s) => match s.strip_prefix("regex:") {
1147            Some(p) if !p.is_empty() => Ok(Pretokenizer::Regex(p.to_string())),
1148            _ => Err(KuteError::InvalidConfig(format!("pretokenizer {s:?}: expected none, gpt4 or regex:<pattern>"))),
1149        },
1150    }
1151}
1152
1153fn train(engine: &Engine, args: TrainArgs) -> kute::Result<()> {
1154    let mut config = TrainingConfig::new(VocabularyId::parse(&args.id)?, args.vocab_size);
1155    config.vocabulary_version = Version::parse(&args.vocab_version)
1156        .map_err(|e| KuteError::InvalidIdentifier(format!("version {:?}: {e}", args.vocab_version)))?;
1157    let symbol_algorithm = args.algorithm == "sequence-bpe";
1158    config.pretokenizer = if symbol_algorithm && args.pretokenizer.is_none() {
1159        Pretokenizer::None
1160    } else {
1161        parse_pretokenizer(args.pretokenizer.as_deref(), &args.adapter)?
1162    };
1163    config.min_frequency = args.min_frequency;
1164    config.max_token_length = args.max_token_length;
1165    config.reserved_tokens = args.reserved;
1166    config.description = args.description;
1167    config.license = args.license;
1168    config.embed_test_vectors = args.embed_test_vectors;
1169    config.stream_bytes = args.stream_bytes;
1170    if let Some(path) = &args.resume_from {
1171        config.resume_from = Some(Box::new(vocab::load(path)?));
1172    }
1173    if let Some(path) = &args.dictionary_file {
1174        let text = std::fs::read_to_string(path)?;
1175        config.dictionary = text.lines().map(|l| l.trim_end_matches('\r')).filter(|l| !l.is_empty()).map(str::to_string).collect();
1176    }
1177    let mut adapter_config = AdapterConfig::default();
1178    for option in &args.adapter_options {
1179        let (key, value) = option
1180            .split_once('=')
1181            .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
1182        adapter_config = adapter_config.with(key, value);
1183    }
1184    let start = std::time::Instant::now();
1185    let vocabulary = engine.train_paths(&args.algorithm, &args.adapter, &adapter_config, &args.input, &config)?;
1186    let seconds = start.elapsed().as_secs_f64();
1187    vocab::save(&vocabulary, &args.output, args.force)?;
1188    eprintln!("trained {} {} in {seconds:.2} s -> {}", vocabulary.id(), vocabulary.version(), args.output.display());
1189    print(&json!({
1190        "output": args.output,
1191        "train_seconds": seconds,
1192        "peak_memory_bytes": kute_bench::peak_memory_bytes(),
1193        "resumed_from": args.resume_from,
1194        "summary": vocab::summarize(&vocabulary)?,
1195    }))
1196}
1197
1198fn run(engine: Engine, cli: Cli) -> kute::Result<()> {
1199    match cli.command {
1200        Command::Train(args) => train(&engine, *args),
1201        Command::Encode { vocab: vocab_path, input, output, compress, unknown } => {
1202            let policy = kute::UnknownPolicy::parse(&unknown)?;
1203            let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
1204            let raw = std::fs::read(&input)?;
1205            let sequence = engine.encode_raw_open(tokenizer.as_ref(), &raw, policy)?;
1206            match output {
1207                Some(path) => {
1208                    let bytes = if compress { sequence.to_bytes_compressed()? } else { sequence.to_bytes()? };
1209                    std::fs::write(&path, &bytes)?;
1210                    print(&json!({
1211                        "output": path,
1212                        "input_bytes": raw.len(),
1213                        "tokens": sequence.ids.len(),
1214                        "escaped_symbols": sequence.escapes.len(),
1215                        "serialized_bytes": bytes.len(),
1216                        "vocabulary": format!("{} {}", sequence.vocabulary_id, sequence.vocabulary_version),
1217                    }))
1218                }
1219                None => print(&sequence),
1220            }
1221        }
1222        Command::Decode { vocab: vocab_path, input, output, max_units } => {
1223            let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
1224            let sequence = TokenSequence::from_bytes(&std::fs::read(&input)?)?;
1225            let bytes = engine.decode_raw_bounded(tokenizer.as_ref(), &sequence, max_units.unwrap_or(u64::MAX))?;
1226            match output {
1227                Some(path) => {
1228                    std::fs::write(&path, &bytes)?;
1229                    print(&json!({ "output": path, "bytes": bytes.len(), "tokens": sequence.ids.len() }))
1230                }
1231                None => {
1232                    let mut out = std::io::stdout().lock();
1233                    out.write_all(&bytes)?;
1234                    out.flush()?;
1235                    Ok(())
1236                }
1237            }
1238        }
1239        Command::Inspect { vocab: vocab_path, token, longest } => {
1240            let vocabulary = vocab::load(&vocab_path)?;
1241            if let Some(id) = token {
1242                return print(&vocabulary.record(id)?);
1243            }
1244            let mut report = json!({ "summary": vocab::summarize(&vocabulary)? });
1245            if longest > 0 {
1246                let mut learned: Vec<&kute::TokenEntry> = vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
1247                learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
1248                let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| vocabulary.record(t.id)).collect::<kute::Result<_>>()?;
1249                report["longest_learned_tokens"] = serde_json::to_value(rows)?;
1250            }
1251            print(&report)
1252        }
1253        Command::Keygen { output } => print(&sign::keygen(&output)?),
1254        Command::Sign { vocab: vocab_path, key, output, force } => print(&sign::sign(&vocab_path, &key, &output, force)?),
1255        Command::Verify { vocab: vocab_path, trusted_keys } => {
1256            let (report, verified) = sign::verify(&vocab_path, &trusted_keys)?;
1257            print(&report)?;
1258            if !verified {
1259                return Err(KuteError::Integrity("no trusted key has signed this vocabulary".into()));
1260            }
1261            Ok(())
1262        }
1263        Command::Validate { vocab: vocab_path } => {
1264            let vocabulary = vocab::load(&vocab_path)?;
1265            let report = engine.verify(&vocabulary)?;
1266            print(&report)?;
1267            if report.ok() {
1268                Ok(())
1269            } else {
1270                Err(KuteError::InvalidVocabulary(format!("{} of {} test vectors failed", report.failures.len(), report.vectors)))
1271            }
1272        }
1273        Command::Compare { a, b } => print(&vocab::compare(&vocab::load(&a)?, &vocab::load(&b)?)?),
1274        Command::Convert { input, output, force } => {
1275            let vocabulary = vocab::load(&input)?;
1276            vocab::save(&vocabulary, &output, force)?;
1277            // Read the new file back: the report describes what is on disk.
1278            let written = vocab::load(&output)?;
1279            if written != vocabulary {
1280                return Err(KuteError::Integrity("the converted file does not read back as the same vocabulary".into()));
1281            }
1282            let median_ms = |path: &PathBuf| -> kute::Result<f64> {
1283                let bytes = std::fs::read(path)?;
1284                let mut times = Vec::new();
1285                for _ in 0..5 {
1286                    let start = std::time::Instant::now();
1287                    vocab::from_slice(&bytes)?;
1288                    times.push(start.elapsed().as_secs_f64() * 1000.0);
1289                }
1290                times.sort_by(|a, b| a.total_cmp(b));
1291                Ok((times[2] * 1000.0).round() / 1000.0)
1292            };
1293            print(&json!({
1294                "input": { "path": input, "bytes": std::fs::metadata(&input)?.len(), "load_ms_median": median_ms(&input)? },
1295                "output": { "path": output, "bytes": std::fs::metadata(&output)?.len(), "load_ms_median": median_ms(&output)? },
1296                "digest": written.digest()?,
1297                "tokens": written.len(),
1298                "identical": true,
1299            }))
1300        }
1301        Command::Export { vocab: vocab_path, format: ExportFormat::Tiktoken, output } => {
1302            let vocabulary = vocab::load(&vocab_path)?;
1303            let export = vocab::export_tiktoken(&vocabulary)?;
1304            std::fs::write(&output, &export.bpe_file)?;
1305            let mut sidecar = output.clone().into_os_string();
1306            sidecar.push(".json");
1307            let sidecar = PathBuf::from(sidecar);
1308            let meta = json!({
1309                "name": vocabulary.id().as_str().replace(':', "_"),
1310                "pat_str": export.pat_str,
1311                "special_tokens": export.special_tokens,
1312                "explicit_n_vocab": export.n_vocab,
1313                "source_vocabulary": format!("{} {}", vocabulary.id(), vocabulary.version()),
1314                "source_digest": vocabulary.digest()?,
1315            });
1316            std::fs::write(&sidecar, serde_json::to_vec_pretty(&meta)?)?;
1317            print(&json!({ "bpe_file": output, "metadata": sidecar, "tokens": export.n_vocab }))
1318        }
1319        Command::Benchmark { vocab: vocab_path, dataset, suite, repo_root, large_text, iterations, output } => {
1320            let report = if suite {
1321                serde_json::to_value(kute_bench::suite::run(&engine, &kute_bench::suite::Options { repo_root, iterations, large_text })?)?
1322            } else {
1323                let (Some(vocab_path), Some(dataset)) = (vocab_path, dataset) else {
1324                    return Err(KuteError::InvalidConfig("benchmark needs --vocab and --dataset, or --suite".into()));
1325                };
1326                let vocabulary = vocab::load(&vocab_path)?;
1327                let documents = kute_bench::read_dataset(&dataset)?;
1328                json!({
1329                    "environment": kute_bench::Environment::detect(),
1330                    "dataset": dataset,
1331                    "evaluation": kute_bench::evaluate(&engine, &vocabulary, &documents, iterations)?,
1332                })
1333            };
1334            if let Some(path) = output {
1335                let mut text = serde_json::to_string_pretty(&report)?;
1336                text.push('\n');
1337                std::fs::write(&path, text)?;
1338                eprintln!("report written to {}", path.display());
1339            }
1340            print(&report)
1341        }
1342        Command::SampleData { output } => {
1343            use kute_bench::data;
1344            std::fs::create_dir_all(&output)?;
1345            let files: Vec<(&str, Vec<u8>, &str)> = vec![
1346                ("alarms-train.jsonl", data::alarm_log(51, 4000), "plant alarm log, 4000 episodes"),
1347                ("alarms-eval.jsonl", data::alarm_log(52, 1000), "plant alarm log, 1000 episodes, different seed"),
1348                ("messages-train.jsonl", data::agent_messages(61, 4000), "agent messages, 4000 records"),
1349                ("messages-eval.jsonl", data::agent_messages(62, 1000), "agent messages, 1000 records, different seed"),
1350                ("frames-train.bin", data::binary_records(31, 6000), "binary telemetry frames, 6000 records"),
1351                ("frames-eval.bin", data::binary_records(32, 2000), "binary telemetry frames, 2000 records, different seed"),
1352                ("words-train.txt", data::invented_words(81, 60_000), "invented-word text, 60000 words"),
1353                ("words-eval.txt", data::invented_words(82, 15_000), "invented-word text, 15000 words, different seed"),
1354            ];
1355            let mut written = Vec::new();
1356            for (name, bytes, what) in files {
1357                std::fs::write(output.join(name), &bytes)?;
1358                written.push(json!({ "file": name, "bytes": bytes.len(), "sha256": kute::sha256_tagged(&bytes), "content": what }));
1359            }
1360            print(&json!({ "output": output, "synthetic": true, "files": written }))
1361        }
1362        Command::Discover(args) => discover(&engine, *args),
1363        Command::Evolve { vocab: vocab_path, additions, new_version, output, force } => {
1364            let version = Version::parse(&new_version).map_err(|e| KuteError::InvalidIdentifier(format!("version {new_version:?}: {e}")))?;
1365            let parent = vocab::load(&vocab_path)?;
1366            let child = kute::bpe::sequence::evolve(&parent, &split_additions(&additions), version)?;
1367            let report = engine.verify(&child)?;
1368            if !report.ok() {
1369                return Err(KuteError::Backend(format!("the evolved vocabulary fails its test vectors: {}", report.failures.join("; "))));
1370            }
1371            vocab::save(&child, &output, force)?;
1372            // A container writes every id in as many bytes as the largest
1373            // id of the vocabulary needs. A step across one of these sizes
1374            // makes every token cost more, which can outweigh what the new
1375            // tokens save (measured: benchmarks/README.md, drifting data).
1376            let mut warnings = Vec::new();
1377            for (limit, bytes) in [(256usize, "one byte"), (65_536, "two bytes")] {
1378                if parent.len() <= limit && child.len() > limit {
1379                    warnings.push(format!(
1380                        "the vocabulary grew from {} to {} tokens, past {limit}: a token id no longer fits {bytes}, so sequences can come out larger than under the parent even with fewer tokens. Measure on your data before adopting it.",
1381                        parent.len(),
1382                        child.len()
1383                    ));
1384                }
1385            }
1386            for warning in &warnings {
1387                eprintln!("warning: {warning}");
1388            }
1389            print(&json!({
1390                "output": output,
1391                "parent": { "version": parent.version().to_string(), "digest": parent.digest()?, "tokens": parent.len() },
1392                "summary": vocab::summarize(&child)?,
1393                "warnings": warnings,
1394            }))
1395        }
1396        Command::Peer { action } => peer(engine, action),
1397        Command::Mcp { vocab: paths, max_input_bytes, max_output_bytes } => {
1398            let vocabularies = paths.iter().map(vocab::load).collect::<kute::Result<Vec<_>>>()?;
1399            let limits = mcp::Limits { max_input_bytes, max_output_bytes, max_request_bytes: max_input_bytes.saturating_mul(2).saturating_add(1 << 20), ..Default::default() };
1400            let server = mcp::Server::new(engine, vocabularies, limits)?;
1401            server.serve(std::io::stdin().lock(), std::io::stdout().lock())?;
1402            Ok(())
1403        }
1404        Command::Live {
1405            input,
1406            symbol_field,
1407            time_field,
1408            group_field,
1409            pane,
1410            panes,
1411            lateness,
1412            end_on,
1413            idle,
1414            max_buffered,
1415            max_length,
1416            max_symbols,
1417            max_candidates,
1418            max_entities,
1419            min_support,
1420            min_cohesion_bits,
1421            max_patterns,
1422            checkpoint,
1423            checkpoint_every,
1424            resume,
1425            skip_bad_lines,
1426        } => {
1427            let bounds = kute_discover::live::LiveParams { max_length, max_symbols, max_candidates, max_entities, ..Default::default() };
1428            let params = kute_discover::watch::WatchParams { live: bounds, pane_ticks: pane, panes, lateness, max_buffered, min_support, min_cohesion_bits, max_patterns, end_symbols: end_on, idle_ticks: idle };
1429            live::run(live::Options { input, symbol_field, time_field, group_field, params, checkpoint, checkpoint_every, resume, skip_bad_lines })
1430        }
1431        Command::Predict { input, symbol_field, time_field, time_unit, group_field, holdout_fraction, max_context, min_count, windows, resamples, seed, output } => {
1432            let schema = kute::EventSchema {
1433                id: "kute:events:unnamed".into(),
1434                version: 1,
1435                symbol_field,
1436                time_unit: Some(kute::TimeUnit::parse(&time_unit)?),
1437                time_field: Some(time_field),
1438                group_field,
1439            };
1440            let mut stream = kute::EventStream::new(schema)?;
1441            for path in &input {
1442                for file in kute::collect_files(path)? {
1443                    let reader = std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(&file)?);
1444                    stream.read_jsonl(reader, &file.display().to_string())?;
1445                }
1446            }
1447            let params = kute_discover::predict::PredictParams { holdout_fraction, max_context, min_count, windows, resamples, seed };
1448            let report = kute_discover::predict::evaluate(&stream, &params)?;
1449            if let Some(path) = output {
1450                std::fs::write(&path, serde_json::to_vec_pretty(&report)?)?;
1451            }
1452            print(&report)
1453        }
1454        Command::Shadow { parent, candidate, input, unknown, min_improvement, horizon, distributions, max_slowdown, passes, fail_on_reject } => {
1455            let (report, approved) = shadow::run(&engine, &shadow::Options { parent, candidate, inputs: input, unknown, min_improvement, horizon, distributions, max_slowdown, passes })?;
1456            print(&report)?;
1457            if fail_on_reject && !approved {
1458                return Err(KuteError::Backend("the candidate was rejected".into()));
1459            }
1460            Ok(())
1461        }
1462        Command::Events { action } => match action {
1463            EventsAction::Pack { input, output, symbol_field, time_field, group_field, codec } => {
1464                let layout = kute_events::Layout { symbol_field, time_field, group_field };
1465                let (container, report) = kute_events::pack_with(&std::fs::read(&input)?, &layout, codec.as_deref().map_or(Ok(kute_events::Codec::preferred()), kute_events::Codec::parse)?)?;
1466                std::fs::write(&output, &container)?;
1467                print(&json!({ "output": output, "report": report }))
1468            }
1469            EventsAction::Unpack { input, output, max_bytes } => {
1470                let bytes = kute_events::unpack(&std::fs::read(&input)?, max_bytes)?;
1471                match output {
1472                    Some(path) => {
1473                        std::fs::write(&path, &bytes)?;
1474                        print(&json!({ "output": path, "bytes": bytes.len() }))
1475                    }
1476                    None => {
1477                        let mut out = std::io::stdout().lock();
1478                        out.write_all(&bytes)?;
1479                        out.flush()?;
1480                        Ok(())
1481                    }
1482                }
1483            }
1484            EventsAction::Inspect { input } => print(&kute_events::header(&std::fs::read(&input)?)?.0),
1485        },
1486        Command::Signals { action } => match action {
1487            SignalsAction::Pack { input, output, max_error, codec, column, delimiter, skip_lines } => {
1488                let text = std::fs::read_to_string(&input)?;
1489                let mut values = Vec::new();
1490                let mut missing = 0u64;
1491                for (number, line) in text.lines().enumerate().skip(skip_lines) {
1492                    let field = match (column, delimiter) {
1493                        (Some(column), Some(delimiter)) => line.split(delimiter).nth(column.saturating_sub(1)).ok_or_else(|| KuteError::InvalidInput(format!("line {} has no column {column}", number + 1)))?,
1494                        _ => line,
1495                    }
1496                    .trim();
1497                    if field.is_empty() || field == "?" || field.eq_ignore_ascii_case("na") || field.eq_ignore_ascii_case("nan") {
1498                        missing += 1;
1499                        values.push(f64::NAN);
1500                    } else {
1501                        values.push(field.parse::<f64>().map_err(|_| KuteError::InvalidInput(format!("line {}: {field:?} is not a number", number + 1)))?);
1502                    }
1503                }
1504                let mode = max_error.map_or(kute_signals::Mode::Exact, |max_error| kute_signals::Mode::Bounded { max_error });
1505                let (container, report) = kute_signals::pack_with(&values, mode, codec.as_deref().map_or(Ok(kute_signals::Codec::preferred()), kute_signals::Codec::parse)?)?;
1506                std::fs::write(&output, &container)?;
1507                print(&json!({ "output": output, "input_bytes": text.len(), "missing_values": missing, "report": report }))
1508            }
1509            SignalsAction::Unpack { input, output, max_values } => {
1510                let values = kute_signals::unpack(&std::fs::read(&input)?, max_values)?;
1511                let mut text = String::with_capacity(values.len() * 8);
1512                for value in &values {
1513                    // The plain form never uses an exponent, so 1e300 is
1514                    // 301 characters. Past a width the exponent form is
1515                    // written; both read back as the same number.
1516                    let plain = value.to_string();
1517                    if plain.len() > 24 {
1518                        text.push_str(&format!("{value:e}"));
1519                    } else {
1520                        text.push_str(&plain);
1521                    }
1522                    text.push('\n');
1523                }
1524                match output {
1525                    Some(path) => {
1526                        std::fs::write(&path, &text)?;
1527                        print(&json!({ "output": path, "values": values.len() }))
1528                    }
1529                    None => {
1530                        let mut out = std::io::stdout().lock();
1531                        out.write_all(text.as_bytes())?;
1532                        out.flush()?;
1533                        Ok(())
1534                    }
1535                }
1536            }
1537            SignalsAction::Inspect { input } => print(&kute_signals::header(&std::fs::read(&input)?)?),
1538        },
1539        Command::Fetch { from, digest, output, trusted_keys, force, list, max_bytes, timeout } => {
1540            let timeout = std::time::Duration::from_secs(timeout.max(1));
1541            match (list, digest, output) {
1542                (true, _, _) => print(&registry::list(&from, timeout)?),
1543                (false, Some(digest), Some(output)) => print(&registry::fetch(&engine, &from, &digest, &output, &trusted_keys, force, max_bytes, timeout)?),
1544                _ => Err(KuteError::InvalidConfig("give --digest and --output, or --list".into())),
1545            }
1546        }
1547        Command::Serve { vocab: paths, listen, insecure_remote, studio, registry, registry_only, upstream, upstream_trusted_key, upstream_timeout, upstream_max_bytes, upstream_cache_bytes, max_input_bytes, max_output_bytes, workers, timeout } => {
1548            let registry = registry || registry_only;
1549            if !upstream.is_empty() && !registry {
1550                return Err(KuteError::InvalidConfig("--upstream is for a registry: add --registry or --registry-only".into()));
1551            }
1552            // Read the addresses before listening: one that cannot be read
1553            // is the operator's mistake, to be told now.
1554            if upstream.is_empty() && !upstream_trusted_key.is_empty() {
1555                return Err(KuteError::InvalidConfig("--upstream-trusted-key is about files from an --upstream, and none was named".into()));
1556            }
1557            let federation = if upstream.is_empty() {
1558                None
1559            } else {
1560                let check: Option<http::UpstreamCheck> = if upstream_trusted_key.is_empty() { None } else { Some(Box::new(sign::gate(&upstream_trusted_key)?)) };
1561                Some(std::sync::Arc::new(http::Federation::new(upstream.clone(), std::time::Duration::from_secs(upstream_timeout.max(1)), upstream_max_bytes, upstream_cache_bytes, check)?))
1562            };
1563            let vocabularies = paths.iter().map(vocab::load).collect::<kute::Result<Vec<_>>>()?;
1564            let max_body_bytes = max_input_bytes.saturating_mul(2).saturating_add(1 << 20);
1565            let limits = mcp::Limits { max_input_bytes, max_output_bytes, max_request_bytes: max_body_bytes, ..Default::default() };
1566            let server = mcp::Server::new(engine, vocabularies, limits)?;
1567            let listener = std::net::TcpListener::bind(&listen)?;
1568            let address = listener.local_addr()?;
1569            if !http::is_loopback(&address) && !insecure_remote {
1570                return Err(KuteError::InvalidConfig(format!(
1571                    "{address} is not a loopback address, and this service has no TLS and no authentication; pass --insecure-remote to serve it anyway"
1572                )));
1573            }
1574            if studio && !http::is_loopback(&address) {
1575                return Err(KuteError::InvalidConfig("Studio is served on a loopback address only: it is a page for the person at this machine".into()));
1576            }
1577            print(&json!({ "listening": address.to_string(), "api": "v1", "loopback_only": http::is_loopback(&address), "studio": studio.then(|| format!("http://{address}/studio")), "registry": registry.then(|| format!("http://{address}")), "upstreams": upstream, "upstream_files_need_a_trusted_signature": !upstream_trusted_key.is_empty(), "operations": !registry_only }))?;
1578            let options = http::Options { workers, timeout: std::time::Duration::from_secs(timeout.max(1)), max_body_bytes, any_host: !http::is_loopback(&address), studio, registry, operations: !registry_only, federation, ..Default::default() };
1579            http::serve(server, listener, options)
1580        }
1581        Command::Capabilities => {
1582            let registry = engine.registry();
1583            let algorithms: Vec<kute::TokenizerCapabilities> =
1584                registry.algorithm_names().iter().map(|n| registry.tokenizer(n).map(|t| t.capabilities())).collect::<kute::Result<_>>()?;
1585            let adapters: Vec<serde_json::Value> = registry
1586                .adapter_names()
1587                .iter()
1588                .map(|n| {
1589                    registry.adapter(n).map(|a| {
1590                        let c = a.capabilities();
1591                        json!({ "name": c.name, "modality": c.modality, "lossless": c.lossless, "notes": c.notes })
1592                    })
1593                })
1594                .collect::<kute::Result<_>>()?;
1595            print(&json!({
1596                "kute_version": kute::KUTE_VERSION,
1597                "kvf_version": kute::KVF_VERSION,
1598                "algorithms": algorithms,
1599                "adapters": adapters,
1600            }))
1601        }
1602    }
1603}
1604
1605/// Parse the command line and run it on `engine`. The `kute` binary passes
1606/// the default engine; other front ends can register more algorithms first.
1607pub fn main_with(engine: Engine) -> ExitCode {
1608    match run(engine, Cli::parse()) {
1609        Ok(()) => ExitCode::SUCCESS,
1610        Err(e) => {
1611            eprintln!("kute: {e}");
1612            ExitCode::FAILURE
1613        }
1614    }
1615}