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