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