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        /// Most bytes of input in one encode or discover call.
374        #[arg(long, default_value_t = 1_048_576)]
375        max_input_bytes: u64,
376        /// Most bytes one decode call gives back.
377        #[arg(long, default_value_t = 4_194_304)]
378        max_output_bytes: u64,
379        /// Requests handled at once.
380        #[arg(long, default_value_t = 4)]
381        workers: usize,
382        /// Seconds a request may take to arrive.
383        #[arg(long, default_value_t = 10)]
384        timeout: u64,
385    },
386    /// Take a vocabulary from a registry (`kute serve --registry`) by its
387    /// digest. The digest is recomputed from what arrives and the file is
388    /// written only if it matches; with --trusted-key, only if one of
389    /// those keys signed it. Plain HTTP: the registry and the network are
390    /// not trusted with the content, and can see it.
391    Fetch {
392        /// The registry, as http://host:port.
393        #[arg(long)]
394        from: String,
395        /// The vocabulary wanted: sha256: and 64 hex digits.
396        #[arg(long, required_unless_present = "list", conflicts_with = "list")]
397        digest: Option<String>,
398        /// Where to write it.
399        #[arg(long, required_unless_present = "list")]
400        output: Option<PathBuf>,
401        /// Keep the vocabulary only if one of these keys signed it (the
402        /// base64 public key `kute keygen` prints). Repeatable.
403        #[arg(long = "trusted-key", value_name = "BASE64")]
404        trusted_keys: Vec<String>,
405        /// Replace the output if it exists.
406        #[arg(long)]
407        force: bool,
408        /// Print what the registry says it holds, and fetch nothing.
409        #[arg(long)]
410        list: bool,
411        /// Largest file taken.
412        #[arg(long, default_value_t = 268_435_456)]
413        max_bytes: u64,
414        /// Seconds the whole exchange may take.
415        #[arg(long, default_value_t = 60)]
416        timeout: u64,
417    },
418    /// List registered algorithms and adapters and what each declares.
419    Capabilities,
420    /// Write the seeded example datasets used by the documentation.
421    SampleData {
422        /// Directory to create the files in.
423        #[arg(long)]
424        output: PathBuf,
425    },
426}
427
428#[derive(Clone, Copy, ValueEnum)]
429enum ExportFormat {
430    Tiktoken,
431}
432
433#[derive(Subcommand)]
434enum EventsAction {
435    /// Pack JSON Lines, one object per event, keeping every field.
436    Pack {
437        /// JSON Lines to read.
438        input: PathBuf,
439        /// Container to write.
440        #[arg(long)]
441        output: PathBuf,
442        /// Field holding the event name.
443        #[arg(long, value_name = "FIELD")]
444        symbol_field: String,
445        /// Field holding the time, a whole number.
446        #[arg(long, value_name = "FIELD")]
447        time_field: Option<String>,
448        /// Field naming the entity an event belongs to.
449        #[arg(long, value_name = "FIELD")]
450        group_field: Option<String>,
451        /// How columns are compressed: zstd, or zlib for a container that
452        /// needs only a zlib reader. The default is zstd when this build
453        /// has it (the `zstd` feature, on unless turned off) and zlib
454        /// when it does not.
455        #[arg(long)]
456        codec: Option<String>,
457    },
458    /// Write the records back as canonical JSON Lines, in source order.
459    Unpack {
460        input: PathBuf,
461        /// File to write; standard output when absent.
462        #[arg(long)]
463        output: Option<PathBuf>,
464        /// Refuse a container that unpacks to more bytes than this.
465        #[arg(long, default_value_t = 1 << 32)]
466        max_bytes: u64,
467    },
468    /// Show a container's header: layout, counts, digest and columns.
469    Inspect { input: PathBuf },
470}
471
472#[derive(Subcommand)]
473enum SignalsAction {
474    /// Pack one number per line (or one column of a delimited file).
475    Pack {
476        /// Text, one value per line. An empty value, `?`, `NA` or `NaN`
477        /// is a missing value and comes back as NaN.
478        input: PathBuf,
479        #[arg(long)]
480        output: PathBuf,
481        /// Keep every finite value within this absolute error instead of
482        /// exactly. Values that are not finite are still kept exactly.
483        #[arg(long, value_name = "ERROR")]
484        max_error: Option<f64>,
485        /// How the parts are compressed: zstd or zlib. The default is
486        /// zstd when this build has it and zlib when it does not.
487        #[arg(long)]
488        codec: Option<String>,
489        /// Take this column of each line, counting from 1.
490        #[arg(long, requires = "delimiter")]
491        column: Option<usize>,
492        /// The character between columns.
493        #[arg(long, requires = "column")]
494        delimiter: Option<char>,
495        /// Lines to pass over at the top, such as a header.
496        #[arg(long, default_value_t = 0)]
497        skip_lines: usize,
498    },
499    /// Write the values, one per line, in the shortest form that reads
500    /// back as the same number.
501    Unpack {
502        input: PathBuf,
503        /// Where to write; standard output when absent.
504        #[arg(long)]
505        output: Option<PathBuf>,
506        /// Refuse a container holding more values than this. Reading can
507        /// take about 44 bytes of memory a value, so the default allows
508        /// about 740 MB.
509        #[arg(long, default_value_t = 1 << 24)]
510        max_values: u64,
511    },
512    /// Print the container's header: the contract and what it measured.
513    Inspect { input: PathBuf },
514}
515
516#[derive(Subcommand)]
517enum PeerAction {
518    /// Wait for one connection and answer it until it closes.
519    Serve {
520        /// Address to listen on, e.g. 127.0.0.1:7411.
521        #[arg(long)]
522        listen: String,
523        /// Vocabularies this side already holds. Repeatable.
524        #[arg(long)]
525        vocab: Vec<PathBuf>,
526        /// Take vocabularies this side does not already hold. Off by
527        /// default: the other side can add nothing unless told it may.
528        #[arg(long)]
529        accept_vocabularies: bool,
530        /// Let the other side extend vocabularies held here.
531        #[arg(long)]
532        accept_proposals: bool,
533        /// Take a vocabulary from the other side only if it carries a
534        /// valid signature from one of these keys (the base64 public key
535        /// `kute keygen` prints). Repeatable. Vocabularies given with
536        /// --vocab are yours and are not checked. With --accept-proposals,
537        /// a proposal is taken only if it carries such a signature of the
538        /// vocabulary it derives (`kute peer send --sign-with`).
539        #[arg(long, value_name = "PUBLIC_KEY", requires = "accept_vocabularies")]
540        require_signature_from: Vec<String>,
541        /// Send a held vocabulary's file to the other side when it asks.
542        #[arg(long)]
543        give_vocabularies: bool,
544        /// Answer whether a held vocabulary has a token for given symbols.
545        #[arg(long)]
546        answer_queries: bool,
547        /// Re-encode the other side's sequences under another held vocabulary.
548        #[arg(long)]
549        translate: bool,
550        /// Give up on a connection that sends nothing for this many
551        /// seconds, during the handshake or after. 0 waits forever.
552        #[arg(long, default_value_t = 30)]
553        timeout: u64,
554        /// Serve over a plain socket: no encryption, and whoever connects
555        /// is served. Required when no TLS options are given.
556        #[arg(long, conflicts_with = "tls_cert")]
557        insecure_plain: bool,
558        /// Refuse a message that decodes to more than this many units.
559        #[arg(long, default_value_t = 268_435_456)]
560        max_units: u64,
561        /// Write each decoded message and each vocabulary received here.
562        #[arg(long)]
563        output_dir: Option<PathBuf>,
564        /// This side's certificate chain (PEM). With --tls-key,
565        /// --tls-client-ca and --allow, the connection is TLS 1.3 with a
566        /// certificate on both sides. A connection that fails the
567        /// handshake or is not allowed is refused and the next one awaited.
568        #[arg(long, requires_all = ["tls_key", "tls_client_ca"])]
569        tls_cert: Option<PathBuf>,
570        /// This side's private key (PEM).
571        #[arg(long, requires = "tls_cert")]
572        tls_key: Option<PathBuf>,
573        /// Authorities whose client certificates are accepted (PEM).
574        #[arg(long, requires = "tls_cert")]
575        tls_client_ca: Option<PathBuf>,
576        /// A peer that may connect, by certificate fingerprint as printed
577        /// by `kute peer fingerprint`. Repeatable. Anyone else is refused,
578        /// even with a certificate from an accepted authority. The
579        /// fingerprint is of the certificate, not the key: a renewed
580        /// certificate has to be allowed again, and removing a fingerprint
581        /// is the only revocation.
582        #[arg(long, value_name = "SHA256", requires = "tls_cert")]
583        allow: Vec<String>,
584    },
585    /// Connect, make sure the other side holds the vocabulary, and send files.
586    Send {
587        /// Address to connect to.
588        #[arg(long)]
589        connect: String,
590        #[arg(long)]
591        vocab: PathBuf,
592        /// Files to encode and send. Repeatable.
593        #[arg(long, num_args = 0..)]
594        input: Vec<PathBuf>,
595        /// strict or escape; see `kute encode --unknown`.
596        #[arg(long, default_value = "strict")]
597        unknown: String,
598        /// Before sending, propose these additions (as in `kute evolve --add`).
599        #[arg(long = "propose", value_name = "SYMBOLS", requires = "new_version")]
600        additions: Vec<String>,
601        #[arg(long)]
602        new_version: Option<String>,
603        /// Sign the vocabulary the proposal derives with this private key
604        /// (as `kute sign` would), and send the signature with the
605        /// proposal. For a peer that requires signatures.
606        #[arg(long, value_name = "KEY", requires = "new_version")]
607        sign_with: Option<PathBuf>,
608        /// This side's certificate chain (PEM); with --tls-key and --tls-ca
609        /// the connection is TLS 1.3 with a certificate on both sides.
610        #[arg(long, requires_all = ["tls_key", "tls_ca"])]
611        tls_cert: Option<PathBuf>,
612        /// This side's private key (PEM).
613        #[arg(long, requires = "tls_cert")]
614        tls_key: Option<PathBuf>,
615        /// Authorities whose server certificates are accepted (PEM).
616        #[arg(long, requires = "tls_cert")]
617        tls_ca: Option<PathBuf>,
618        /// The name the server's certificate must carry. Default: the host
619        /// part of --connect.
620        #[arg(long, requires = "tls_cert")]
621        server_name: Option<String>,
622        /// Talk only to the server with this certificate fingerprint.
623        /// Without it, any server the authority issued a certificate for
624        /// the name is accepted, which is less than the server asks of you.
625        #[arg(long, value_name = "SHA256", requires = "tls_cert")]
626        server_fingerprint: Option<String>,
627        /// Connect over a plain socket: no encryption and no check of who
628        /// answers. Required when no TLS options are given.
629        #[arg(long, conflicts_with = "tls_cert")]
630        insecure_plain: bool,
631    },
632    /// Print the fingerprint that identifies a certificate to `--allow`.
633    Fingerprint {
634        /// A certificate (PEM). The first one in the file is used.
635        #[arg(long)]
636        cert: PathBuf,
637    },
638}
639
640const 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";
641
642/// A plain or an encrypted connection.
643trait Stream: std::io::Read + std::io::Write {}
644impl<T: std::io::Read + std::io::Write> Stream for T {}
645
646fn split_additions(additions: &[String]) -> Vec<Vec<String>> {
647    additions.iter().map(|a| a.split_whitespace().map(str::to_string).collect()).collect()
648}
649
650fn peer(engine: Engine, action: PeerAction) -> kute::Result<()> {
651    use kute_protocol::{tls, Framed, Peer, Policy, Session, DEFAULT_MAX_FRAME};
652    match action {
653        PeerAction::Fingerprint { cert } => {
654            let chain = tls::load_certificates(&cert)?;
655            print(&json!({ "certificate": cert, "fingerprint": tls::fingerprint(&chain[0]) }))
656        }
657        PeerAction::Serve {
658            listen,
659            vocab: held,
660            accept_vocabularies,
661            accept_proposals,
662            require_signature_from,
663            give_vocabularies,
664            answer_queries,
665            translate,
666            timeout,
667            insecure_plain,
668            max_units,
669            output_dir,
670            tls_cert,
671            tls_key,
672            tls_client_ca,
673            allow,
674        } => {
675            let policy = Policy { accept_vocabularies, accept_proposals, give_vocabularies, answer_queries, translate, max_decoded_units: max_units, ..Policy::default() };
676            if tls_cert.is_none() && !insecure_plain {
677                return Err(KuteError::InvalidConfig(NO_TRANSPORT.into()));
678            }
679            // Read the trusted keys before listening: a key that cannot be
680            // read is the operator's mistake, to be told now and not to
681            // whoever connects first.
682            let gate = if require_signature_from.is_empty() { None } else { Some(sign::gate(&require_signature_from)?) };
683            let timeout = (timeout > 0).then(|| std::time::Duration::from_secs(timeout));
684            let secured = match (&tls_cert, &tls_key, &tls_client_ca) {
685                (Some(cert), Some(key), Some(ca)) => {
686                    if allow.is_empty() {
687                        return Err(KuteError::InvalidConfig("with TLS, name at least one peer with --allow; nobody is allowed otherwise".into()));
688                    }
689                    let mut access = tls::Access::new();
690                    for fingerprint in &allow {
691                        access.allow(fingerprint, policy.clone())?;
692                    }
693                    Some((tls::server_config(tls::load_certificates(cert)?, tls::load_private_key(key)?, tls::load_certificates(ca)?)?, access))
694                }
695                _ => None,
696            };
697            let listener = std::net::TcpListener::bind(&listen)?;
698            // Lines to standard error are written without `eprintln!`, which
699            // panics when the stream is closed: a parent that stopped reading
700            // would otherwise let the next refused connection end the server.
701            let _ = writeln!(std::io::stderr(), "listening on {}", listener.local_addr()?);
702            if secured.is_none() {
703                let _ = writeln!(std::io::stderr(), "warning: no TLS. The connection is not encrypted and whoever connects is served.");
704            }
705            // With TLS, a connection that fails the handshake, stalls in
706            // it, or is not allowed does not end the listener: whoever can
707            // reach the port could otherwise stop it before the allowed peer
708            // arrives.
709            let (stream, identity, policy, from): (Box<dyn Stream>, Option<String>, Policy, std::net::SocketAddr) = loop {
710                let (tcp, from) = listener.accept()?;
711                tcp.set_read_timeout(timeout)?;
712                tcp.set_write_timeout(timeout)?;
713                let Some((config, access)) = &secured else { break (Box::new(tcp), None, policy, from) };
714                match tls::accept(config, tcp).and_then(|(stream, who)| Ok((stream, access.policy_for(&who)?, who))) {
715                    Ok((stream, policy, who)) => break (Box::new(stream), Some(who.fingerprint), policy, from),
716                    Err(e) => {
717                        let _ = writeln!(std::io::stderr(), "refused {from}: {e}");
718                    }
719                }
720            };
721            let mut peer = Peer::new("kute", engine, policy);
722            if let Some(gate) = gate {
723                peer.require_vocabulary_check(Box::new(gate));
724            }
725            for path in &held {
726                peer.add_vocabulary(vocab::load(path)?)?;
727            }
728            let before = peer.digests();
729            let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
730            let handled = session.serve()?;
731            let inbox = session.peer.take_inbox();
732            let new: Vec<String> = session.peer.digests().into_iter().filter(|d| !before.contains(d)).collect();
733            // Nothing received, nothing created.
734            if let Some(dir) = output_dir.as_ref().filter(|_| !inbox.is_empty() || !new.is_empty()) {
735                std::fs::create_dir_all(dir)?;
736                for message in &inbox {
737                    std::fs::write(dir.join(format!("message-{}.bin", message.id)), &message.bytes)?;
738                }
739                for digest in &new {
740                    if let Some(v) = session.peer.vocabulary(digest) {
741                        let name = format!("{}-{}.kvf", v.id().as_str().replace(':', "_"), v.version());
742                        vocab::save(v, dir.join(name), true)?;
743                    }
744                }
745            }
746            print(&json!({
747                "from": from.to_string(),
748                "peer_identity": identity,
749                "messages_handled": handled,
750                "vocabularies_received": new,
751                "received": inbox.iter().map(|m| json!({
752                    "id": m.id,
753                    "bytes": m.bytes.len(),
754                    "tokens": m.sequence.ids.len(),
755                    "escaped_symbols": m.sequence.escapes.len(),
756                    "vocabulary": format!("{} {}", m.sequence.vocabulary_id, m.sequence.vocabulary_version),
757                })).collect::<Vec<_>>(),
758            }))
759        }
760        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 } => {
761            // Read the key before connecting: one that cannot be read
762            // is this side's mistake, to be told before anything is sent.
763            let signer = sign_with.as_deref().map(sign::signer).transpose()?;
764            if tls_cert.is_none() && !insecure_plain {
765                return Err(KuteError::InvalidConfig(NO_TRANSPORT.into()));
766            }
767            let policy = kute::UnknownPolicy::parse(&unknown)?;
768            let mut peer = Peer::new("kute", engine, Policy::default());
769            let mut digest = peer.add_vocabulary(vocab::load(&vocab_path)?)?;
770            let tcp = std::net::TcpStream::connect(&connect)?;
771            let (stream, server_identity): (Box<dyn Stream>, Option<String>) = match (&tls_cert, &tls_key, &tls_ca) {
772                (Some(cert), Some(key), Some(ca)) => {
773                    let config = tls::client_config(tls::load_certificates(cert)?, tls::load_private_key(key)?, tls::load_certificates(ca)?)?;
774                    let host = connect.rsplit_once(':').map_or(connect.as_str(), |(host, _)| host);
775                    let (stream, who) = tls::connect(&config, server_name.as_deref().unwrap_or(host), tcp)?;
776                    if server_fingerprint.as_ref().is_some_and(|wanted| *wanted != who.fingerprint) {
777                        return Err(KuteError::Integrity(format!("the server is {}, not the one named by --server-fingerprint", who.fingerprint)));
778                    }
779                    (Box::new(stream), Some(who.fingerprint))
780                }
781                _ => (Box::new(tcp), None),
782            };
783            let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
784            let remote = session.connect()?;
785            let transferred = session.share(&digest)?;
786            let mut proposed = None;
787            if let Some(version) = &new_version {
788                digest = match &signer {
789                    Some(signer) => session.propose_signed(&digest, &split_additions(&additions), version, signer)?,
790                    None => session.propose(&digest, &split_additions(&additions), version)?,
791                };
792                proposed = Some(digest.clone());
793            }
794            let mut sent = Vec::new();
795            for path in &input {
796                let raw = std::fs::read(path)?;
797                let units = session.send(&digest, &raw, policy)?;
798                sent.push(json!({ "input": path, "bytes": raw.len(), "units_decoded_by_peer": units, "receipt_matches": true }));
799            }
800            print(&json!({
801                "peer": remote.peer,
802                "peer_software": remote.software,
803                "server_identity": server_identity,
804                "vocabulary_transferred": transferred,
805                "vocabulary_after_proposal": proposed,
806                "proposal_signed": proposed.is_some() && sign_with.is_some(),
807                "sent": sent,
808            }))
809        }
810    }
811}
812
813#[derive(clap::Args)]
814struct DiscoverArgs {
815    /// Files or directories to look for patterns in.
816    #[arg(long, required = true, num_args = 1..)]
817    input: Vec<PathBuf>,
818    /// Adapter that turns each file into one record of symbols.
819    #[arg(long, default_value = "jsonl-events")]
820    adapter: String,
821    /// Adapter option as key=value. Repeatable.
822    #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
823    adapter_options: Vec<String>,
824    /// Read plain text instead of using an adapter: every line is one
825    /// record, symbols separated by whitespace.
826    #[arg(long, conflicts_with_all = ["adapter", "adapter_options"])]
827    lines: bool,
828    /// Read typed events instead: JSON Lines with one event per line, the
829    /// event name in this field. Keeps time and grouping; see the other
830    /// --*-field options.
831    #[arg(long, value_name = "FIELD", conflicts_with_all = ["adapter", "adapter_options", "lines"])]
832    symbol_field: Option<String>,
833    /// Field with the event time, a whole number of --time-unit. With it,
834    /// the report says how long each pattern takes.
835    #[arg(long, value_name = "FIELD", requires = "symbol_field")]
836    time_field: Option<String>,
837    /// Unit of the time field: s, ms, us or ns.
838    #[arg(long, default_value = "s", requires = "time_field")]
839    time_unit: String,
840    /// Field naming what an event belongs to (a device, a block, a session).
841    /// Events with the same value form one record.
842    #[arg(long, value_name = "FIELD", requires = "symbol_field")]
843    group_field: Option<String>,
844    /// Name recorded for this way of reading the events.
845    #[arg(long, default_value = "kute:events:unnamed", requires = "symbol_field")]
846    schema_id: String,
847    /// Files with held-out data to check the patterns against.
848    #[arg(long, num_args = 1.., conflicts_with = "holdout_fraction")]
849    holdout: Vec<PathBuf>,
850    /// Hold out this share of the input instead. With --lines the last
851    /// records are held out; otherwise the end of each record.
852    #[arg(long)]
853    holdout_fraction: Option<f64>,
854    #[arg(long, default_value_t = 5)]
855    min_support: u64,
856    /// Longest contiguous pattern, in symbols.
857    #[arg(long, default_value_t = 8)]
858    max_length: usize,
859    /// Minimum cohesion in bits: how much more often than chance.
860    #[arg(long, default_value_t = 1.0)]
861    min_cohesion: f64,
862    /// Gapped pairs look this many symbols ahead; 0 turns them off.
863    #[arg(long, default_value_t = 8)]
864    window: usize,
865    /// Report at most this many patterns of each kind.
866    #[arg(long, default_value_t = 50)]
867    top: usize,
868    /// Also run on a shuffled copy of the input (same symbol counts, no
869    /// order) and report how much the method finds there.
870    #[arg(long)]
871    control: bool,
872    /// Also write the JSON report to this file.
873    #[arg(long)]
874    output: Option<PathBuf>,
875}
876
877fn read_records(engine: &Engine, args: &DiscoverArgs, paths: &[PathBuf]) -> kute::Result<Vec<Vec<String>>> {
878    let mut adapter_config = AdapterConfig::default();
879    for option in &args.adapter_options {
880        let (key, value) = option
881            .split_once('=')
882            .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
883        adapter_config = adapter_config.with(key, value);
884    }
885    let mut records = Vec::new();
886    for path in paths {
887        for file in kute::collect_files(path)? {
888            let raw = std::fs::read(&file)?;
889            if args.lines {
890                let text = String::from_utf8(raw).map_err(|_| KuteError::InvalidInput(format!("{}: not UTF-8", file.display())))?;
891                records.extend(text.lines().map(|l| l.split_whitespace().map(str::to_string).collect::<Vec<_>>()).filter(|r| !r.is_empty()));
892            } else {
893                let input = engine.registry().adapter(&args.adapter)?.ingest(&raw, &adapter_config)?;
894                records.extend(kute_discover::records_of(&[input])?);
895            }
896        }
897    }
898    if records.is_empty() {
899        return Err(KuteError::InvalidInput("no records found in the input".into()));
900    }
901    Ok(records)
902}
903
904fn read_events(args: &DiscoverArgs, symbol_field: &str, paths: &[PathBuf]) -> kute::Result<kute::EventStream> {
905    let schema = kute::EventSchema {
906        id: args.schema_id.clone(),
907        version: 1,
908        symbol_field: symbol_field.to_string(),
909        time_unit: args.time_field.as_ref().map(|_| kute::TimeUnit::parse(&args.time_unit)).transpose()?,
910        time_field: args.time_field.clone(),
911        group_field: args.group_field.clone(),
912    };
913    let mut stream = kute::EventStream::new(schema)?;
914    for path in paths {
915        for file in kute::collect_files(path)? {
916            let reader = std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(&file)?);
917            stream.read_jsonl(reader, &file.display().to_string())?;
918        }
919    }
920    if stream.records.is_empty() {
921        return Err(KuteError::InvalidInput("no events found in the input".into()));
922    }
923    Ok(stream)
924}
925
926/// Lend a stream's symbols out as plain records, and give them back.
927fn take_symbols(stream: &mut kute::EventStream) -> Vec<Vec<String>> {
928    stream.records.iter_mut().map(|r| std::mem::take(&mut r.symbols)).collect()
929}
930
931fn give_symbols(stream: &mut kute::EventStream, records: Vec<Vec<String>>) {
932    for (r, symbols) in stream.records.iter_mut().zip(records) {
933        r.symbols = symbols;
934    }
935}
936
937fn describe(stream: &kute::EventStream) -> kute::Result<serde_json::Value> {
938    Ok(json!({ "records": stream.records.len(), "events": stream.events(), "fingerprint": stream.fingerprint()? }))
939}
940
941fn discover(engine: &Engine, args: DiscoverArgs) -> kute::Result<()> {
942    use kute_discover as kd;
943    let params = kd::Params {
944        min_support: args.min_support,
945        max_length: args.max_length,
946        min_cohesion_bits: args.min_cohesion,
947        window: args.window,
948        max_patterns: args.top,
949        ..kd::Params::default()
950    };
951    // Typed events: the symbols go through discovery like any others, and
952    // the streams keep their times for the timing pass afterwards.
953    let mut streams: Option<(kute::EventStream, Option<kute::EventStream>)> = match &args.symbol_field {
954        None => None,
955        Some(field) => {
956            let stream = read_events(&args, field, &args.input)?;
957            Some(if !args.holdout.is_empty() {
958                (stream, Some(read_events(&args, field, &args.holdout)?))
959            } else if let Some(fraction) = args.holdout_fraction {
960                let (head, tail) = stream.split_last(fraction)?;
961                (head, Some(tail))
962            } else {
963                (stream, None)
964            })
965        }
966    };
967    let typed = streams.is_some();
968    let mut records = match &mut streams {
969        Some((stream, _)) => take_symbols(stream),
970        None => read_records(engine, &args, &args.input)?,
971    };
972    let mut held_out = match &mut streams {
973        Some((_, held)) => held.as_mut().map(take_symbols),
974        None if args.holdout.is_empty() => None,
975        None => Some(read_records(engine, &args, &args.holdout)?),
976    };
977    if let Some(fraction) = args.holdout_fraction.filter(|_| !typed) {
978        if args.lines {
979            if !(fraction > 0.0 && fraction < 1.0) {
980                return Err(KuteError::InvalidConfig("the held-out fraction must be between 0 and 1".into()));
981            }
982            let cut = ((records.len() as f64) * (1.0 - fraction)).round() as usize;
983            held_out = Some(records.split_off(cut.clamp(1, records.len())));
984        } else {
985            let (head, tail) = kd::split_holdout(&records, fraction)?;
986            records = head;
987            held_out = Some(tail);
988        }
989    }
990    let start = std::time::Instant::now();
991    let found = kd::discover(&records, &params)?;
992    let seconds = start.elapsed().as_secs_f64();
993    let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
994    let control = if args.control {
995        let found = kd::discover(&kd::shuffled(&records, 0), &params)?;
996        let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
997        Some(json!({
998            "what": "the same run on a shuffled copy of the input: same symbol counts, no order",
999            "patterns": found.patterns.len(),
1000            "strongest_evidence_bits": found.patterns.iter().map(|p| p.evidence_bits).fold(0.0, f64::max),
1001            "coverage": found.coverage,
1002            "held_out_confirmed": evaluation.as_ref().map(|e| e.confirmed),
1003            "held_out_coverage": evaluation.as_ref().map(|e| e.coverage),
1004        }))
1005    } else {
1006        None
1007    };
1008    let events = match streams {
1009        None => None,
1010        Some((mut stream, mut held)) => {
1011            give_symbols(&mut stream, records);
1012            if let (Some(h), Some(symbols)) = (held.as_mut(), held_out) {
1013                give_symbols(h, symbols);
1014            }
1015            let timing = if stream.timed() { Some(kd::timing(&found, &stream)?) } else { None };
1016            let held_timing = match &held {
1017                Some(h) if h.timed() => Some(kd::timing(&found, h)?),
1018                _ => None,
1019            };
1020            Some(json!({
1021                "schema": stream.schema,
1022                "searched": describe(&stream)?,
1023                "held_out": held.as_ref().map(describe).transpose()?,
1024                "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",
1025                "timing": timing,
1026                "held_out_timing": held_timing,
1027            }))
1028        }
1029    };
1030    let report = json!({
1031        "kute_version": kute::KUTE_VERSION,
1032        "discover_seconds": seconds,
1033        "peak_memory_bytes": kute_bench::peak_memory_bytes(),
1034        "discovery": found,
1035        "held_out": evaluation,
1036        "control": control,
1037        "events": events,
1038    });
1039    if let Some(path) = &args.output {
1040        std::fs::write(path, serde_json::to_vec_pretty(&report)?)?;
1041    }
1042    print(&report)
1043}
1044
1045#[derive(clap::Args)]
1046struct TrainArgs {
1047    /// Files or directories to train on. Directories are read recursively.
1048    #[arg(long, required = true, num_args = 1..)]
1049    input: Vec<PathBuf>,
1050    /// Vocabulary identifier, e.g. kute:industrial:events.
1051    #[arg(long)]
1052    id: String,
1053    /// Vocabulary version (semantic versioning).
1054    #[arg(long, default_value = "0.1.0")]
1055    vocab_version: String,
1056    #[arg(long, default_value = "bpe")]
1057    algorithm: String,
1058    #[arg(long, default_value = "text")]
1059    adapter: String,
1060    /// Adapter option as key=value. Repeatable.
1061    #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
1062    adapter_options: Vec<String>,
1063    #[arg(long, default_value_t = 4096)]
1064    vocab_size: u32,
1065    /// none, gpt4, or regex:<pattern>. Default: gpt4 for the text adapter, none otherwise.
1066    #[arg(long)]
1067    pretokenizer: Option<String>,
1068    #[arg(long, default_value_t = 1)]
1069    min_frequency: u64,
1070    #[arg(long)]
1071    max_token_length: Option<usize>,
1072    /// Reserved (special) token. Repeatable.
1073    #[arg(long = "reserved")]
1074    reserved: Vec<String>,
1075    /// File with one dictionary entry per line, for the dictionary algorithm.
1076    #[arg(long)]
1077    dictionary_file: Option<PathBuf>,
1078    #[arg(long)]
1079    description: Option<String>,
1080    /// License of the vocabulary, e.g. an SPDX identifier.
1081    #[arg(long)]
1082    license: Option<String>,
1083    /// Read input files in pieces of about this many bytes, cut at line
1084    /// breaks, so memory does not grow with file size. Recorded in the
1085    /// vocabulary, because it decides where records end.
1086    #[arg(long, value_name = "BYTES")]
1087    stream_bytes: Option<usize>,
1088    /// Continue from a vocabulary trained earlier on the same input with the
1089    /// same settings and a smaller --vocab-size. The result is the same as
1090    /// one run to the new size. bpe and sequence-bpe. Its merges are taken
1091    /// as given: resume only from a vocabulary you trained or trust.
1092    #[arg(long, value_name = "VOCAB")]
1093    resume_from: Option<PathBuf>,
1094    /// Store the start of the first training records in the vocabulary as
1095    /// self-test vectors, so anyone holding the file can check it. They are
1096    /// verbatim excerpts: leave this off when the corpus is private.
1097    #[arg(long, conflicts_with = "no_test_vectors")]
1098    embed_test_vectors: bool,
1099    /// Accepted for compatibility; this is the default since v0.4.0.
1100    #[arg(long, hide = true)]
1101    no_test_vectors: bool,
1102    #[arg(long)]
1103    output: PathBuf,
1104    /// Replace an existing output file even if its content differs.
1105    #[arg(long)]
1106    force: bool,
1107}
1108
1109fn print(value: &impl serde::Serialize) -> kute::Result<()> {
1110    let text = serde_json::to_string_pretty(value)?;
1111    let mut out = std::io::stdout().lock();
1112    writeln!(out, "{text}")?;
1113    Ok(())
1114}
1115
1116fn parse_pretokenizer(spec: Option<&str>, adapter: &str) -> kute::Result<Pretokenizer> {
1117    match spec {
1118        None => Ok(if adapter == "text" { Pretokenizer::Gpt4 } else { Pretokenizer::None }),
1119        Some("none") => Ok(Pretokenizer::None),
1120        Some("gpt4") => Ok(Pretokenizer::Gpt4),
1121        Some(s) => match s.strip_prefix("regex:") {
1122            Some(p) if !p.is_empty() => Ok(Pretokenizer::Regex(p.to_string())),
1123            _ => Err(KuteError::InvalidConfig(format!("pretokenizer {s:?}: expected none, gpt4 or regex:<pattern>"))),
1124        },
1125    }
1126}
1127
1128fn train(engine: &Engine, args: TrainArgs) -> kute::Result<()> {
1129    let mut config = TrainingConfig::new(VocabularyId::parse(&args.id)?, args.vocab_size);
1130    config.vocabulary_version = Version::parse(&args.vocab_version)
1131        .map_err(|e| KuteError::InvalidIdentifier(format!("version {:?}: {e}", args.vocab_version)))?;
1132    let symbol_algorithm = args.algorithm == "sequence-bpe";
1133    config.pretokenizer = if symbol_algorithm && args.pretokenizer.is_none() {
1134        Pretokenizer::None
1135    } else {
1136        parse_pretokenizer(args.pretokenizer.as_deref(), &args.adapter)?
1137    };
1138    config.min_frequency = args.min_frequency;
1139    config.max_token_length = args.max_token_length;
1140    config.reserved_tokens = args.reserved;
1141    config.description = args.description;
1142    config.license = args.license;
1143    config.embed_test_vectors = args.embed_test_vectors;
1144    config.stream_bytes = args.stream_bytes;
1145    if let Some(path) = &args.resume_from {
1146        config.resume_from = Some(Box::new(vocab::load(path)?));
1147    }
1148    if let Some(path) = &args.dictionary_file {
1149        let text = std::fs::read_to_string(path)?;
1150        config.dictionary = text.lines().map(|l| l.trim_end_matches('\r')).filter(|l| !l.is_empty()).map(str::to_string).collect();
1151    }
1152    let mut adapter_config = AdapterConfig::default();
1153    for option in &args.adapter_options {
1154        let (key, value) = option
1155            .split_once('=')
1156            .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
1157        adapter_config = adapter_config.with(key, value);
1158    }
1159    let start = std::time::Instant::now();
1160    let vocabulary = engine.train_paths(&args.algorithm, &args.adapter, &adapter_config, &args.input, &config)?;
1161    let seconds = start.elapsed().as_secs_f64();
1162    vocab::save(&vocabulary, &args.output, args.force)?;
1163    eprintln!("trained {} {} in {seconds:.2} s -> {}", vocabulary.id(), vocabulary.version(), args.output.display());
1164    print(&json!({
1165        "output": args.output,
1166        "train_seconds": seconds,
1167        "peak_memory_bytes": kute_bench::peak_memory_bytes(),
1168        "resumed_from": args.resume_from,
1169        "summary": vocab::summarize(&vocabulary)?,
1170    }))
1171}
1172
1173fn run(engine: Engine, cli: Cli) -> kute::Result<()> {
1174    match cli.command {
1175        Command::Train(args) => train(&engine, *args),
1176        Command::Encode { vocab: vocab_path, input, output, compress, unknown } => {
1177            let policy = kute::UnknownPolicy::parse(&unknown)?;
1178            let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
1179            let raw = std::fs::read(&input)?;
1180            let sequence = engine.encode_raw_open(tokenizer.as_ref(), &raw, policy)?;
1181            match output {
1182                Some(path) => {
1183                    let bytes = if compress { sequence.to_bytes_compressed()? } else { sequence.to_bytes()? };
1184                    std::fs::write(&path, &bytes)?;
1185                    print(&json!({
1186                        "output": path,
1187                        "input_bytes": raw.len(),
1188                        "tokens": sequence.ids.len(),
1189                        "escaped_symbols": sequence.escapes.len(),
1190                        "serialized_bytes": bytes.len(),
1191                        "vocabulary": format!("{} {}", sequence.vocabulary_id, sequence.vocabulary_version),
1192                    }))
1193                }
1194                None => print(&sequence),
1195            }
1196        }
1197        Command::Decode { vocab: vocab_path, input, output, max_units } => {
1198            let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
1199            let sequence = TokenSequence::from_bytes(&std::fs::read(&input)?)?;
1200            let bytes = engine.decode_raw_bounded(tokenizer.as_ref(), &sequence, max_units.unwrap_or(u64::MAX))?;
1201            match output {
1202                Some(path) => {
1203                    std::fs::write(&path, &bytes)?;
1204                    print(&json!({ "output": path, "bytes": bytes.len(), "tokens": sequence.ids.len() }))
1205                }
1206                None => {
1207                    let mut out = std::io::stdout().lock();
1208                    out.write_all(&bytes)?;
1209                    out.flush()?;
1210                    Ok(())
1211                }
1212            }
1213        }
1214        Command::Inspect { vocab: vocab_path, token, longest } => {
1215            let vocabulary = vocab::load(&vocab_path)?;
1216            if let Some(id) = token {
1217                return print(&vocabulary.record(id)?);
1218            }
1219            let mut report = json!({ "summary": vocab::summarize(&vocabulary)? });
1220            if longest > 0 {
1221                let mut learned: Vec<&kute::TokenEntry> = vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
1222                learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
1223                let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| vocabulary.record(t.id)).collect::<kute::Result<_>>()?;
1224                report["longest_learned_tokens"] = serde_json::to_value(rows)?;
1225            }
1226            print(&report)
1227        }
1228        Command::Keygen { output } => print(&sign::keygen(&output)?),
1229        Command::Sign { vocab: vocab_path, key, output, force } => print(&sign::sign(&vocab_path, &key, &output, force)?),
1230        Command::Verify { vocab: vocab_path, trusted_keys } => {
1231            let (report, verified) = sign::verify(&vocab_path, &trusted_keys)?;
1232            print(&report)?;
1233            if !verified {
1234                return Err(KuteError::Integrity("no trusted key has signed this vocabulary".into()));
1235            }
1236            Ok(())
1237        }
1238        Command::Validate { vocab: vocab_path } => {
1239            let vocabulary = vocab::load(&vocab_path)?;
1240            let report = engine.verify(&vocabulary)?;
1241            print(&report)?;
1242            if report.ok() {
1243                Ok(())
1244            } else {
1245                Err(KuteError::InvalidVocabulary(format!("{} of {} test vectors failed", report.failures.len(), report.vectors)))
1246            }
1247        }
1248        Command::Compare { a, b } => print(&vocab::compare(&vocab::load(&a)?, &vocab::load(&b)?)?),
1249        Command::Convert { input, output, force } => {
1250            let vocabulary = vocab::load(&input)?;
1251            vocab::save(&vocabulary, &output, force)?;
1252            // Read the new file back: the report describes what is on disk.
1253            let written = vocab::load(&output)?;
1254            if written != vocabulary {
1255                return Err(KuteError::Integrity("the converted file does not read back as the same vocabulary".into()));
1256            }
1257            let median_ms = |path: &PathBuf| -> kute::Result<f64> {
1258                let bytes = std::fs::read(path)?;
1259                let mut times = Vec::new();
1260                for _ in 0..5 {
1261                    let start = std::time::Instant::now();
1262                    vocab::from_slice(&bytes)?;
1263                    times.push(start.elapsed().as_secs_f64() * 1000.0);
1264                }
1265                times.sort_by(|a, b| a.total_cmp(b));
1266                Ok((times[2] * 1000.0).round() / 1000.0)
1267            };
1268            print(&json!({
1269                "input": { "path": input, "bytes": std::fs::metadata(&input)?.len(), "load_ms_median": median_ms(&input)? },
1270                "output": { "path": output, "bytes": std::fs::metadata(&output)?.len(), "load_ms_median": median_ms(&output)? },
1271                "digest": written.digest()?,
1272                "tokens": written.len(),
1273                "identical": true,
1274            }))
1275        }
1276        Command::Export { vocab: vocab_path, format: ExportFormat::Tiktoken, output } => {
1277            let vocabulary = vocab::load(&vocab_path)?;
1278            let export = vocab::export_tiktoken(&vocabulary)?;
1279            std::fs::write(&output, &export.bpe_file)?;
1280            let mut sidecar = output.clone().into_os_string();
1281            sidecar.push(".json");
1282            let sidecar = PathBuf::from(sidecar);
1283            let meta = json!({
1284                "name": vocabulary.id().as_str().replace(':', "_"),
1285                "pat_str": export.pat_str,
1286                "special_tokens": export.special_tokens,
1287                "explicit_n_vocab": export.n_vocab,
1288                "source_vocabulary": format!("{} {}", vocabulary.id(), vocabulary.version()),
1289                "source_digest": vocabulary.digest()?,
1290            });
1291            std::fs::write(&sidecar, serde_json::to_vec_pretty(&meta)?)?;
1292            print(&json!({ "bpe_file": output, "metadata": sidecar, "tokens": export.n_vocab }))
1293        }
1294        Command::Benchmark { vocab: vocab_path, dataset, suite, repo_root, large_text, iterations, output } => {
1295            let report = if suite {
1296                serde_json::to_value(kute_bench::suite::run(&engine, &kute_bench::suite::Options { repo_root, iterations, large_text })?)?
1297            } else {
1298                let (Some(vocab_path), Some(dataset)) = (vocab_path, dataset) else {
1299                    return Err(KuteError::InvalidConfig("benchmark needs --vocab and --dataset, or --suite".into()));
1300                };
1301                let vocabulary = vocab::load(&vocab_path)?;
1302                let documents = kute_bench::read_dataset(&dataset)?;
1303                json!({
1304                    "environment": kute_bench::Environment::detect(),
1305                    "dataset": dataset,
1306                    "evaluation": kute_bench::evaluate(&engine, &vocabulary, &documents, iterations)?,
1307                })
1308            };
1309            if let Some(path) = output {
1310                let mut text = serde_json::to_string_pretty(&report)?;
1311                text.push('\n');
1312                std::fs::write(&path, text)?;
1313                eprintln!("report written to {}", path.display());
1314            }
1315            print(&report)
1316        }
1317        Command::SampleData { output } => {
1318            use kute_bench::data;
1319            std::fs::create_dir_all(&output)?;
1320            let files: Vec<(&str, Vec<u8>, &str)> = vec![
1321                ("alarms-train.jsonl", data::alarm_log(51, 4000), "plant alarm log, 4000 episodes"),
1322                ("alarms-eval.jsonl", data::alarm_log(52, 1000), "plant alarm log, 1000 episodes, different seed"),
1323                ("messages-train.jsonl", data::agent_messages(61, 4000), "agent messages, 4000 records"),
1324                ("messages-eval.jsonl", data::agent_messages(62, 1000), "agent messages, 1000 records, different seed"),
1325                ("frames-train.bin", data::binary_records(31, 6000), "binary telemetry frames, 6000 records"),
1326                ("frames-eval.bin", data::binary_records(32, 2000), "binary telemetry frames, 2000 records, different seed"),
1327                ("words-train.txt", data::invented_words(81, 60_000), "invented-word text, 60000 words"),
1328                ("words-eval.txt", data::invented_words(82, 15_000), "invented-word text, 15000 words, different seed"),
1329            ];
1330            let mut written = Vec::new();
1331            for (name, bytes, what) in files {
1332                std::fs::write(output.join(name), &bytes)?;
1333                written.push(json!({ "file": name, "bytes": bytes.len(), "sha256": kute::sha256_tagged(&bytes), "content": what }));
1334            }
1335            print(&json!({ "output": output, "synthetic": true, "files": written }))
1336        }
1337        Command::Discover(args) => discover(&engine, *args),
1338        Command::Evolve { vocab: vocab_path, additions, new_version, output, force } => {
1339            let version = Version::parse(&new_version).map_err(|e| KuteError::InvalidIdentifier(format!("version {new_version:?}: {e}")))?;
1340            let parent = vocab::load(&vocab_path)?;
1341            let child = kute::bpe::sequence::evolve(&parent, &split_additions(&additions), version)?;
1342            let report = engine.verify(&child)?;
1343            if !report.ok() {
1344                return Err(KuteError::Backend(format!("the evolved vocabulary fails its test vectors: {}", report.failures.join("; "))));
1345            }
1346            vocab::save(&child, &output, force)?;
1347            // A container writes every id in as many bytes as the largest
1348            // id of the vocabulary needs. A step across one of these sizes
1349            // makes every token cost more, which can outweigh what the new
1350            // tokens save (measured: benchmarks/README.md, drifting data).
1351            let mut warnings = Vec::new();
1352            for (limit, bytes) in [(256usize, "one byte"), (65_536, "two bytes")] {
1353                if parent.len() <= limit && child.len() > limit {
1354                    warnings.push(format!(
1355                        "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.",
1356                        parent.len(),
1357                        child.len()
1358                    ));
1359                }
1360            }
1361            for warning in &warnings {
1362                eprintln!("warning: {warning}");
1363            }
1364            print(&json!({
1365                "output": output,
1366                "parent": { "version": parent.version().to_string(), "digest": parent.digest()?, "tokens": parent.len() },
1367                "summary": vocab::summarize(&child)?,
1368                "warnings": warnings,
1369            }))
1370        }
1371        Command::Peer { action } => peer(engine, action),
1372        Command::Mcp { vocab: paths, max_input_bytes, max_output_bytes } => {
1373            let vocabularies = paths.iter().map(vocab::load).collect::<kute::Result<Vec<_>>>()?;
1374            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() };
1375            let server = mcp::Server::new(engine, vocabularies, limits)?;
1376            server.serve(std::io::stdin().lock(), std::io::stdout().lock())?;
1377            Ok(())
1378        }
1379        Command::Live {
1380            input,
1381            symbol_field,
1382            time_field,
1383            group_field,
1384            pane,
1385            panes,
1386            lateness,
1387            end_on,
1388            idle,
1389            max_buffered,
1390            max_length,
1391            max_symbols,
1392            max_candidates,
1393            max_entities,
1394            min_support,
1395            min_cohesion_bits,
1396            max_patterns,
1397            checkpoint,
1398            checkpoint_every,
1399            resume,
1400            skip_bad_lines,
1401        } => {
1402            let bounds = kute_discover::live::LiveParams { max_length, max_symbols, max_candidates, max_entities, ..Default::default() };
1403            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 };
1404            live::run(live::Options { input, symbol_field, time_field, group_field, params, checkpoint, checkpoint_every, resume, skip_bad_lines })
1405        }
1406        Command::Predict { input, symbol_field, time_field, time_unit, group_field, holdout_fraction, max_context, min_count, windows, resamples, seed, output } => {
1407            let schema = kute::EventSchema {
1408                id: "kute:events:unnamed".into(),
1409                version: 1,
1410                symbol_field,
1411                time_unit: Some(kute::TimeUnit::parse(&time_unit)?),
1412                time_field: Some(time_field),
1413                group_field,
1414            };
1415            let mut stream = kute::EventStream::new(schema)?;
1416            for path in &input {
1417                for file in kute::collect_files(path)? {
1418                    let reader = std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(&file)?);
1419                    stream.read_jsonl(reader, &file.display().to_string())?;
1420                }
1421            }
1422            let params = kute_discover::predict::PredictParams { holdout_fraction, max_context, min_count, windows, resamples, seed };
1423            let report = kute_discover::predict::evaluate(&stream, &params)?;
1424            if let Some(path) = output {
1425                std::fs::write(&path, serde_json::to_vec_pretty(&report)?)?;
1426            }
1427            print(&report)
1428        }
1429        Command::Shadow { parent, candidate, input, unknown, min_improvement, horizon, distributions, max_slowdown, passes, fail_on_reject } => {
1430            let (report, approved) = shadow::run(&engine, &shadow::Options { parent, candidate, inputs: input, unknown, min_improvement, horizon, distributions, max_slowdown, passes })?;
1431            print(&report)?;
1432            if fail_on_reject && !approved {
1433                return Err(KuteError::Backend("the candidate was rejected".into()));
1434            }
1435            Ok(())
1436        }
1437        Command::Events { action } => match action {
1438            EventsAction::Pack { input, output, symbol_field, time_field, group_field, codec } => {
1439                let layout = kute_events::Layout { symbol_field, time_field, group_field };
1440                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)?)?;
1441                std::fs::write(&output, &container)?;
1442                print(&json!({ "output": output, "report": report }))
1443            }
1444            EventsAction::Unpack { input, output, max_bytes } => {
1445                let bytes = kute_events::unpack(&std::fs::read(&input)?, max_bytes)?;
1446                match output {
1447                    Some(path) => {
1448                        std::fs::write(&path, &bytes)?;
1449                        print(&json!({ "output": path, "bytes": bytes.len() }))
1450                    }
1451                    None => {
1452                        let mut out = std::io::stdout().lock();
1453                        out.write_all(&bytes)?;
1454                        out.flush()?;
1455                        Ok(())
1456                    }
1457                }
1458            }
1459            EventsAction::Inspect { input } => print(&kute_events::header(&std::fs::read(&input)?)?.0),
1460        },
1461        Command::Signals { action } => match action {
1462            SignalsAction::Pack { input, output, max_error, codec, column, delimiter, skip_lines } => {
1463                let text = std::fs::read_to_string(&input)?;
1464                let mut values = Vec::new();
1465                let mut missing = 0u64;
1466                for (number, line) in text.lines().enumerate().skip(skip_lines) {
1467                    let field = match (column, delimiter) {
1468                        (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)))?,
1469                        _ => line,
1470                    }
1471                    .trim();
1472                    if field.is_empty() || field == "?" || field.eq_ignore_ascii_case("na") || field.eq_ignore_ascii_case("nan") {
1473                        missing += 1;
1474                        values.push(f64::NAN);
1475                    } else {
1476                        values.push(field.parse::<f64>().map_err(|_| KuteError::InvalidInput(format!("line {}: {field:?} is not a number", number + 1)))?);
1477                    }
1478                }
1479                let mode = max_error.map_or(kute_signals::Mode::Exact, |max_error| kute_signals::Mode::Bounded { max_error });
1480                let (container, report) = kute_signals::pack_with(&values, mode, codec.as_deref().map_or(Ok(kute_signals::Codec::preferred()), kute_signals::Codec::parse)?)?;
1481                std::fs::write(&output, &container)?;
1482                print(&json!({ "output": output, "input_bytes": text.len(), "missing_values": missing, "report": report }))
1483            }
1484            SignalsAction::Unpack { input, output, max_values } => {
1485                let values = kute_signals::unpack(&std::fs::read(&input)?, max_values)?;
1486                let mut text = String::with_capacity(values.len() * 8);
1487                for value in &values {
1488                    // The plain form never uses an exponent, so 1e300 is
1489                    // 301 characters. Past a width the exponent form is
1490                    // written; both read back as the same number.
1491                    let plain = value.to_string();
1492                    if plain.len() > 24 {
1493                        text.push_str(&format!("{value:e}"));
1494                    } else {
1495                        text.push_str(&plain);
1496                    }
1497                    text.push('\n');
1498                }
1499                match output {
1500                    Some(path) => {
1501                        std::fs::write(&path, &text)?;
1502                        print(&json!({ "output": path, "values": values.len() }))
1503                    }
1504                    None => {
1505                        let mut out = std::io::stdout().lock();
1506                        out.write_all(text.as_bytes())?;
1507                        out.flush()?;
1508                        Ok(())
1509                    }
1510                }
1511            }
1512            SignalsAction::Inspect { input } => print(&kute_signals::header(&std::fs::read(&input)?)?),
1513        },
1514        Command::Fetch { from, digest, output, trusted_keys, force, list, max_bytes, timeout } => {
1515            let timeout = std::time::Duration::from_secs(timeout.max(1));
1516            match (list, digest, output) {
1517                (true, _, _) => print(&registry::list(&from, timeout)?),
1518                (false, Some(digest), Some(output)) => print(&registry::fetch(&engine, &from, &digest, &output, &trusted_keys, force, max_bytes, timeout)?),
1519                _ => Err(KuteError::InvalidConfig("give --digest and --output, or --list".into())),
1520            }
1521        }
1522        Command::Serve { vocab: paths, listen, insecure_remote, studio, registry, registry_only, max_input_bytes, max_output_bytes, workers, timeout } => {
1523            let registry = registry || registry_only;
1524            let vocabularies = paths.iter().map(vocab::load).collect::<kute::Result<Vec<_>>>()?;
1525            let max_body_bytes = max_input_bytes.saturating_mul(2).saturating_add(1 << 20);
1526            let limits = mcp::Limits { max_input_bytes, max_output_bytes, max_request_bytes: max_body_bytes, ..Default::default() };
1527            let server = mcp::Server::new(engine, vocabularies, limits)?;
1528            let listener = std::net::TcpListener::bind(&listen)?;
1529            let address = listener.local_addr()?;
1530            if !http::is_loopback(&address) && !insecure_remote {
1531                return Err(KuteError::InvalidConfig(format!(
1532                    "{address} is not a loopback address, and this service has no TLS and no authentication; pass --insecure-remote to serve it anyway"
1533                )));
1534            }
1535            if studio && !http::is_loopback(&address) {
1536                return Err(KuteError::InvalidConfig("Studio is served on a loopback address only: it is a page for the person at this machine".into()));
1537            }
1538            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}")), "operations": !registry_only }))?;
1539            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, ..Default::default() };
1540            http::serve(server, listener, options)
1541        }
1542        Command::Capabilities => {
1543            let registry = engine.registry();
1544            let algorithms: Vec<kute::TokenizerCapabilities> =
1545                registry.algorithm_names().iter().map(|n| registry.tokenizer(n).map(|t| t.capabilities())).collect::<kute::Result<_>>()?;
1546            let adapters: Vec<serde_json::Value> = registry
1547                .adapter_names()
1548                .iter()
1549                .map(|n| {
1550                    registry.adapter(n).map(|a| {
1551                        let c = a.capabilities();
1552                        json!({ "name": c.name, "modality": c.modality, "lossless": c.lossless, "notes": c.notes })
1553                    })
1554                })
1555                .collect::<kute::Result<_>>()?;
1556            print(&json!({
1557                "kute_version": kute::KUTE_VERSION,
1558                "kvf_version": kute::KVF_VERSION,
1559                "algorithms": algorithms,
1560                "adapters": adapters,
1561            }))
1562        }
1563    }
1564}
1565
1566/// Parse the command line and run it on `engine`. The `kute` binary passes
1567/// the default engine; other front ends can register more algorithms first.
1568pub fn main_with(engine: Engine) -> ExitCode {
1569    match run(engine, Cli::parse()) {
1570        Ok(()) => ExitCode::SUCCESS,
1571        Err(e) => {
1572            eprintln!("kute: {e}");
1573            ExitCode::FAILURE
1574        }
1575    }
1576}