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