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 mcp;
7
8use clap::{Parser, Subcommand, ValueEnum};
9use kute::{vocab, AdapterConfig, Engine, KuteError, Pretokenizer, TokenSequence, TrainingConfig, Version, VocabularyId};
10use serde_json::json;
11use std::io::Write;
12use std::path::PathBuf;
13use std::process::ExitCode;
14
15#[derive(Parser)]
16#[command(name = "kute", version, about = "Kannaka Universal Tokenization Engine", long_about = None)]
17struct Cli {
18    #[command(subcommand)]
19    command: Command,
20}
21
22#[derive(Subcommand)]
23enum Command {
24    /// Learn a vocabulary from files and write it as KVF.
25    Train(Box<TrainArgs>),
26    /// Encode a file to a .kute token sequence.
27    Encode {
28        #[arg(long)]
29        vocab: PathBuf,
30        #[arg(long)]
31        input: PathBuf,
32        /// Where to write the .kute container. Without it, token ids are printed as JSON.
33        #[arg(long)]
34        output: Option<PathBuf>,
35        /// Write the compressed container (format 2) instead of plain varint ids.
36        #[arg(long, requires = "output")]
37        compress: bool,
38        /// What to do with a symbol the vocabulary does not contain:
39        /// `strict` refuses the input, `escape` carries the symbol literally
40        /// in the sequence so it still decodes exactly.
41        #[arg(long, default_value = "strict")]
42        unknown: String,
43    },
44    /// Decode a .kute token sequence back to bytes.
45    Decode {
46        #[arg(long)]
47        vocab: PathBuf,
48        #[arg(long)]
49        input: PathBuf,
50        /// Where to write the decoded bytes. Without it, they go to stdout.
51        #[arg(long)]
52        output: Option<PathBuf>,
53        /// Refuse a sequence that would decode to more than this many bytes
54        /// or symbols. Use it for sequences from an untrusted source.
55        #[arg(long)]
56        max_units: Option<u64>,
57    },
58    /// Summarize a vocabulary, or show tokens from it.
59    Inspect {
60        vocab: PathBuf,
61        /// Show the full envelope of one token id.
62        #[arg(long)]
63        token: Option<u32>,
64        /// Show the N longest learned tokens.
65        #[arg(long, default_value_t = 0)]
66        longest: usize,
67    },
68    /// Check structure, integrity and the embedded test vectors.
69    Validate { vocab: PathBuf },
70    /// Compare two vocabularies by token content.
71    Compare { a: PathBuf, b: PathBuf },
72    /// Rewrite a vocabulary in the other file form: compact binary when the
73    /// output ends in .kvfb, JSON otherwise. The digest does not change.
74    Convert {
75        #[arg(long)]
76        input: PathBuf,
77        #[arg(long)]
78        output: PathBuf,
79        /// Replace an existing output file.
80        #[arg(long)]
81        force: bool,
82    },
83    /// Convert a vocabulary to another tool's format.
84    Export {
85        #[arg(long)]
86        vocab: PathBuf,
87        #[arg(long, value_enum, default_value_t = ExportFormat::Tiktoken)]
88        format: ExportFormat,
89        /// Output file, e.g. general.tiktoken. A `.json` sidecar with the
90        /// pattern and special tokens is written next to it.
91        #[arg(long)]
92        output: PathBuf,
93    },
94    /// Measure a vocabulary on a dataset, or run the benchmark suite.
95    Benchmark {
96        #[arg(long, required_unless_present = "suite")]
97        vocab: Option<PathBuf>,
98        /// File or directory to evaluate on. Keep it separate from training data.
99        #[arg(long, required_unless_present = "suite")]
100        dataset: Option<PathBuf>,
101        /// Run the built-in benchmark program instead.
102        #[arg(long, conflicts_with_all = ["vocab", "dataset"])]
103        suite: bool,
104        /// Repository root for the suite's in-repo corpora.
105        #[arg(long)]
106        repo_root: Option<PathBuf>,
107        /// A large UTF-8 text file for the suite's real-data case (for example enwik8).
108        /// The first 90% trains a 32K vocabulary; the rest is the evaluation set.
109        #[arg(long, requires = "suite")]
110        large_text: Option<PathBuf>,
111        #[arg(long, default_value_t = 5)]
112        iterations: usize,
113        /// Also write the JSON report to this file.
114        #[arg(long)]
115        output: Option<PathBuf>,
116    },
117    /// Find recurring patterns in symbol streams, without training a tokenizer.
118    Discover(Box<DiscoverArgs>),
119    /// Derive the next version of an event vocabulary by adding symbols or
120    /// symbol sequences. Existing token ids do not change.
121    Evolve {
122        #[arg(long)]
123        vocab: PathBuf,
124        /// A symbol, or several separated by spaces for a sequence. Repeatable.
125        #[arg(long = "add", required = true, value_name = "SYMBOLS")]
126        additions: Vec<String>,
127        /// Version of the new vocabulary; must be greater than the current one.
128        #[arg(long)]
129        new_version: String,
130        #[arg(long)]
131        output: PathBuf,
132        #[arg(long)]
133        force: bool,
134    },
135    /// Exchange vocabularies and encoded messages with another kute process,
136    /// over TLS with a certificate on both sides.
137    Peer {
138        #[command(subcommand)]
139        action: PeerAction,
140    },
141    /// Serve encode, decode, inspect, compare and discover as Model Context
142    /// Protocol tools on standard input and output. Works only on the
143    /// vocabularies named here and on data passed in each call: no file is
144    /// read or written by a tool, nothing is trained, stored or published.
145    Mcp {
146        /// Vocabularies the tools may use. Repeatable.
147        #[arg(long)]
148        vocab: Vec<PathBuf>,
149        /// Most bytes of input in one encode or discover call.
150        #[arg(long, default_value_t = 1_048_576)]
151        max_input_bytes: u64,
152        /// Most bytes one decode call gives back.
153        #[arg(long, default_value_t = 4_194_304)]
154        max_output_bytes: u64,
155    },
156    /// List registered algorithms and adapters and what each declares.
157    Capabilities,
158    /// Write the seeded example datasets used by the documentation.
159    SampleData {
160        /// Directory to create the files in.
161        #[arg(long)]
162        output: PathBuf,
163    },
164}
165
166#[derive(Clone, Copy, ValueEnum)]
167enum ExportFormat {
168    Tiktoken,
169}
170
171#[derive(Subcommand)]
172enum PeerAction {
173    /// Wait for one connection and answer it until it closes.
174    Serve {
175        /// Address to listen on, e.g. 127.0.0.1:7411.
176        #[arg(long)]
177        listen: String,
178        /// Vocabularies this side already holds. Repeatable.
179        #[arg(long)]
180        vocab: Vec<PathBuf>,
181        /// Take vocabularies this side does not already hold. Off by
182        /// default: the other side can add nothing unless told it may.
183        #[arg(long)]
184        accept_vocabularies: bool,
185        /// Let the other side extend vocabularies held here.
186        #[arg(long)]
187        accept_proposals: bool,
188        /// Send a held vocabulary's file to the other side when it asks.
189        #[arg(long)]
190        give_vocabularies: bool,
191        /// Answer whether a held vocabulary has a token for given symbols.
192        #[arg(long)]
193        answer_queries: bool,
194        /// Re-encode the other side's sequences under another held vocabulary.
195        #[arg(long)]
196        translate: bool,
197        /// Give up on a connection that sends nothing for this many
198        /// seconds, during the handshake or after. 0 waits forever.
199        #[arg(long, default_value_t = 30)]
200        timeout: u64,
201        /// Serve over a plain socket: no encryption, and whoever connects
202        /// is served. Required when no TLS options are given.
203        #[arg(long, conflicts_with = "tls_cert")]
204        insecure_plain: bool,
205        /// Refuse a message that decodes to more than this many units.
206        #[arg(long, default_value_t = 268_435_456)]
207        max_units: u64,
208        /// Write each decoded message and each vocabulary received here.
209        #[arg(long)]
210        output_dir: Option<PathBuf>,
211        /// This side's certificate chain (PEM). With --tls-key,
212        /// --tls-client-ca and --allow, the connection is TLS 1.3 with a
213        /// certificate on both sides. A connection that fails the
214        /// handshake or is not allowed is refused and the next one awaited.
215        #[arg(long, requires_all = ["tls_key", "tls_client_ca"])]
216        tls_cert: Option<PathBuf>,
217        /// This side's private key (PEM).
218        #[arg(long, requires = "tls_cert")]
219        tls_key: Option<PathBuf>,
220        /// Authorities whose client certificates are accepted (PEM).
221        #[arg(long, requires = "tls_cert")]
222        tls_client_ca: Option<PathBuf>,
223        /// A peer that may connect, by certificate fingerprint as printed
224        /// by `kute peer fingerprint`. Repeatable. Anyone else is refused,
225        /// even with a certificate from an accepted authority. The
226        /// fingerprint is of the certificate, not the key: a renewed
227        /// certificate has to be allowed again, and removing a fingerprint
228        /// is the only revocation.
229        #[arg(long, value_name = "SHA256", requires = "tls_cert")]
230        allow: Vec<String>,
231    },
232    /// Connect, make sure the other side holds the vocabulary, and send files.
233    Send {
234        /// Address to connect to.
235        #[arg(long)]
236        connect: String,
237        #[arg(long)]
238        vocab: PathBuf,
239        /// Files to encode and send. Repeatable.
240        #[arg(long, num_args = 0..)]
241        input: Vec<PathBuf>,
242        /// strict or escape; see `kute encode --unknown`.
243        #[arg(long, default_value = "strict")]
244        unknown: String,
245        /// Before sending, propose these additions (as in `kute evolve --add`).
246        #[arg(long = "propose", value_name = "SYMBOLS", requires = "new_version")]
247        additions: Vec<String>,
248        #[arg(long)]
249        new_version: Option<String>,
250        /// This side's certificate chain (PEM); with --tls-key and --tls-ca
251        /// the connection is TLS 1.3 with a certificate on both sides.
252        #[arg(long, requires_all = ["tls_key", "tls_ca"])]
253        tls_cert: Option<PathBuf>,
254        /// This side's private key (PEM).
255        #[arg(long, requires = "tls_cert")]
256        tls_key: Option<PathBuf>,
257        /// Authorities whose server certificates are accepted (PEM).
258        #[arg(long, requires = "tls_cert")]
259        tls_ca: Option<PathBuf>,
260        /// The name the server's certificate must carry. Default: the host
261        /// part of --connect.
262        #[arg(long, requires = "tls_cert")]
263        server_name: Option<String>,
264        /// Talk only to the server with this certificate fingerprint.
265        /// Without it, any server the authority issued a certificate for
266        /// the name is accepted, which is less than the server asks of you.
267        #[arg(long, value_name = "SHA256", requires = "tls_cert")]
268        server_fingerprint: Option<String>,
269        /// Connect over a plain socket: no encryption and no check of who
270        /// answers. Required when no TLS options are given.
271        #[arg(long, conflicts_with = "tls_cert")]
272        insecure_plain: bool,
273    },
274    /// Print the fingerprint that identifies a certificate to `--allow`.
275    Fingerprint {
276        /// A certificate (PEM). The first one in the file is used.
277        #[arg(long)]
278        cert: PathBuf,
279    },
280}
281
282const 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";
283
284/// A plain or an encrypted connection.
285trait Stream: std::io::Read + std::io::Write {}
286impl<T: std::io::Read + std::io::Write> Stream for T {}
287
288fn split_additions(additions: &[String]) -> Vec<Vec<String>> {
289    additions.iter().map(|a| a.split_whitespace().map(str::to_string).collect()).collect()
290}
291
292fn peer(engine: Engine, action: PeerAction) -> kute::Result<()> {
293    use kute_protocol::{tls, Framed, Peer, Policy, Session, DEFAULT_MAX_FRAME};
294    match action {
295        PeerAction::Fingerprint { cert } => {
296            let chain = tls::load_certificates(&cert)?;
297            print(&json!({ "certificate": cert, "fingerprint": tls::fingerprint(&chain[0]) }))
298        }
299        PeerAction::Serve {
300            listen,
301            vocab: held,
302            accept_vocabularies,
303            accept_proposals,
304            give_vocabularies,
305            answer_queries,
306            translate,
307            timeout,
308            insecure_plain,
309            max_units,
310            output_dir,
311            tls_cert,
312            tls_key,
313            tls_client_ca,
314            allow,
315        } => {
316            let policy = Policy { accept_vocabularies, accept_proposals, give_vocabularies, answer_queries, translate, max_decoded_units: max_units, ..Policy::default() };
317            if tls_cert.is_none() && !insecure_plain {
318                return Err(KuteError::InvalidConfig(NO_TRANSPORT.into()));
319            }
320            let timeout = (timeout > 0).then(|| std::time::Duration::from_secs(timeout));
321            let secured = match (&tls_cert, &tls_key, &tls_client_ca) {
322                (Some(cert), Some(key), Some(ca)) => {
323                    if allow.is_empty() {
324                        return Err(KuteError::InvalidConfig("with TLS, name at least one peer with --allow; nobody is allowed otherwise".into()));
325                    }
326                    let mut access = tls::Access::new();
327                    for fingerprint in &allow {
328                        access.allow(fingerprint, policy.clone())?;
329                    }
330                    Some((tls::server_config(tls::load_certificates(cert)?, tls::load_private_key(key)?, tls::load_certificates(ca)?)?, access))
331                }
332                _ => None,
333            };
334            let listener = std::net::TcpListener::bind(&listen)?;
335            eprintln!("listening on {}", listener.local_addr()?);
336            if secured.is_none() {
337                eprintln!("warning: no TLS. The connection is not encrypted and whoever connects is served.");
338            }
339            // With TLS, a connection that fails the handshake, stalls in
340            // it, or is not allowed does not end the listener: whoever can
341            // reach the port could otherwise stop it before the allowed peer
342            // arrives.
343            let (stream, identity, policy, from): (Box<dyn Stream>, Option<String>, Policy, std::net::SocketAddr) = loop {
344                let (tcp, from) = listener.accept()?;
345                tcp.set_read_timeout(timeout)?;
346                tcp.set_write_timeout(timeout)?;
347                let Some((config, access)) = &secured else { break (Box::new(tcp), None, policy, from) };
348                match tls::accept(config, tcp).and_then(|(stream, who)| Ok((stream, access.policy_for(&who)?, who))) {
349                    Ok((stream, policy, who)) => break (Box::new(stream), Some(who.fingerprint), policy, from),
350                    Err(e) => eprintln!("refused {from}: {e}"),
351                }
352            };
353            let mut peer = Peer::new("kute", engine, policy);
354            for path in &held {
355                peer.add_vocabulary(vocab::load(path)?)?;
356            }
357            let before = peer.digests();
358            let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
359            let handled = session.serve()?;
360            let inbox = session.peer.take_inbox();
361            let new: Vec<String> = session.peer.digests().into_iter().filter(|d| !before.contains(d)).collect();
362            // Nothing received, nothing created.
363            if let Some(dir) = output_dir.as_ref().filter(|_| !inbox.is_empty() || !new.is_empty()) {
364                std::fs::create_dir_all(dir)?;
365                for message in &inbox {
366                    std::fs::write(dir.join(format!("message-{}.bin", message.id)), &message.bytes)?;
367                }
368                for digest in &new {
369                    if let Some(v) = session.peer.vocabulary(digest) {
370                        let name = format!("{}-{}.kvf", v.id().as_str().replace(':', "_"), v.version());
371                        vocab::save(v, dir.join(name), true)?;
372                    }
373                }
374            }
375            print(&json!({
376                "from": from.to_string(),
377                "peer_identity": identity,
378                "messages_handled": handled,
379                "vocabularies_received": new,
380                "received": inbox.iter().map(|m| json!({
381                    "id": m.id,
382                    "bytes": m.bytes.len(),
383                    "tokens": m.sequence.ids.len(),
384                    "escaped_symbols": m.sequence.escapes.len(),
385                    "vocabulary": format!("{} {}", m.sequence.vocabulary_id, m.sequence.vocabulary_version),
386                })).collect::<Vec<_>>(),
387            }))
388        }
389        PeerAction::Send { connect, vocab: vocab_path, input, unknown, additions, new_version, tls_cert, tls_key, tls_ca, server_name, server_fingerprint, insecure_plain } => {
390            if tls_cert.is_none() && !insecure_plain {
391                return Err(KuteError::InvalidConfig(NO_TRANSPORT.into()));
392            }
393            let policy = kute::UnknownPolicy::parse(&unknown)?;
394            let mut peer = Peer::new("kute", engine, Policy::default());
395            let mut digest = peer.add_vocabulary(vocab::load(&vocab_path)?)?;
396            let tcp = std::net::TcpStream::connect(&connect)?;
397            let (stream, server_identity): (Box<dyn Stream>, Option<String>) = match (&tls_cert, &tls_key, &tls_ca) {
398                (Some(cert), Some(key), Some(ca)) => {
399                    let config = tls::client_config(tls::load_certificates(cert)?, tls::load_private_key(key)?, tls::load_certificates(ca)?)?;
400                    let host = connect.rsplit_once(':').map_or(connect.as_str(), |(host, _)| host);
401                    let (stream, who) = tls::connect(&config, server_name.as_deref().unwrap_or(host), tcp)?;
402                    if server_fingerprint.as_ref().is_some_and(|wanted| *wanted != who.fingerprint) {
403                        return Err(KuteError::Integrity(format!("the server is {}, not the one named by --server-fingerprint", who.fingerprint)));
404                    }
405                    (Box::new(stream), Some(who.fingerprint))
406                }
407                _ => (Box::new(tcp), None),
408            };
409            let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
410            let remote = session.connect()?;
411            let transferred = session.share(&digest)?;
412            let mut proposed = None;
413            if let Some(version) = &new_version {
414                digest = session.propose(&digest, &split_additions(&additions), version)?;
415                proposed = Some(digest.clone());
416            }
417            let mut sent = Vec::new();
418            for path in &input {
419                let raw = std::fs::read(path)?;
420                let units = session.send(&digest, &raw, policy)?;
421                sent.push(json!({ "input": path, "bytes": raw.len(), "units_decoded_by_peer": units, "receipt_matches": true }));
422            }
423            print(&json!({
424                "peer": remote.peer,
425                "peer_software": remote.software,
426                "server_identity": server_identity,
427                "vocabulary_transferred": transferred,
428                "vocabulary_after_proposal": proposed,
429                "sent": sent,
430            }))
431        }
432    }
433}
434
435#[derive(clap::Args)]
436struct DiscoverArgs {
437    /// Files or directories to look for patterns in.
438    #[arg(long, required = true, num_args = 1..)]
439    input: Vec<PathBuf>,
440    /// Adapter that turns each file into one record of symbols.
441    #[arg(long, default_value = "jsonl-events")]
442    adapter: String,
443    /// Adapter option as key=value. Repeatable.
444    #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
445    adapter_options: Vec<String>,
446    /// Read plain text instead of using an adapter: every line is one
447    /// record, symbols separated by whitespace.
448    #[arg(long, conflicts_with_all = ["adapter", "adapter_options"])]
449    lines: bool,
450    /// Read typed events instead: JSON Lines with one event per line, the
451    /// event name in this field. Keeps time and grouping; see the other
452    /// --*-field options.
453    #[arg(long, value_name = "FIELD", conflicts_with_all = ["adapter", "adapter_options", "lines"])]
454    symbol_field: Option<String>,
455    /// Field with the event time, a whole number of --time-unit. With it,
456    /// the report says how long each pattern takes.
457    #[arg(long, value_name = "FIELD", requires = "symbol_field")]
458    time_field: Option<String>,
459    /// Unit of the time field: s, ms, us or ns.
460    #[arg(long, default_value = "s", requires = "time_field")]
461    time_unit: String,
462    /// Field naming what an event belongs to (a device, a block, a session).
463    /// Events with the same value form one record.
464    #[arg(long, value_name = "FIELD", requires = "symbol_field")]
465    group_field: Option<String>,
466    /// Name recorded for this way of reading the events.
467    #[arg(long, default_value = "kute:events:unnamed", requires = "symbol_field")]
468    schema_id: String,
469    /// Files with held-out data to check the patterns against.
470    #[arg(long, num_args = 1.., conflicts_with = "holdout_fraction")]
471    holdout: Vec<PathBuf>,
472    /// Hold out this share of the input instead. With --lines the last
473    /// records are held out; otherwise the end of each record.
474    #[arg(long)]
475    holdout_fraction: Option<f64>,
476    #[arg(long, default_value_t = 5)]
477    min_support: u64,
478    /// Longest contiguous pattern, in symbols.
479    #[arg(long, default_value_t = 8)]
480    max_length: usize,
481    /// Minimum cohesion in bits: how much more often than chance.
482    #[arg(long, default_value_t = 1.0)]
483    min_cohesion: f64,
484    /// Gapped pairs look this many symbols ahead; 0 turns them off.
485    #[arg(long, default_value_t = 8)]
486    window: usize,
487    /// Report at most this many patterns of each kind.
488    #[arg(long, default_value_t = 50)]
489    top: usize,
490    /// Also run on a shuffled copy of the input (same symbol counts, no
491    /// order) and report how much the method finds there.
492    #[arg(long)]
493    control: bool,
494    /// Also write the JSON report to this file.
495    #[arg(long)]
496    output: Option<PathBuf>,
497}
498
499fn read_records(engine: &Engine, args: &DiscoverArgs, paths: &[PathBuf]) -> kute::Result<Vec<Vec<String>>> {
500    let mut adapter_config = AdapterConfig::default();
501    for option in &args.adapter_options {
502        let (key, value) = option
503            .split_once('=')
504            .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
505        adapter_config = adapter_config.with(key, value);
506    }
507    let mut records = Vec::new();
508    for path in paths {
509        for file in kute::collect_files(path)? {
510            let raw = std::fs::read(&file)?;
511            if args.lines {
512                let text = String::from_utf8(raw).map_err(|_| KuteError::InvalidInput(format!("{}: not UTF-8", file.display())))?;
513                records.extend(text.lines().map(|l| l.split_whitespace().map(str::to_string).collect::<Vec<_>>()).filter(|r| !r.is_empty()));
514            } else {
515                let input = engine.registry().adapter(&args.adapter)?.ingest(&raw, &adapter_config)?;
516                records.extend(kute_discover::records_of(&[input])?);
517            }
518        }
519    }
520    if records.is_empty() {
521        return Err(KuteError::InvalidInput("no records found in the input".into()));
522    }
523    Ok(records)
524}
525
526fn read_events(args: &DiscoverArgs, symbol_field: &str, paths: &[PathBuf]) -> kute::Result<kute::EventStream> {
527    let schema = kute::EventSchema {
528        id: args.schema_id.clone(),
529        version: 1,
530        symbol_field: symbol_field.to_string(),
531        time_unit: args.time_field.as_ref().map(|_| kute::TimeUnit::parse(&args.time_unit)).transpose()?,
532        time_field: args.time_field.clone(),
533        group_field: args.group_field.clone(),
534    };
535    let mut stream = kute::EventStream::new(schema)?;
536    for path in paths {
537        for file in kute::collect_files(path)? {
538            let reader = std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(&file)?);
539            stream.read_jsonl(reader, &file.display().to_string())?;
540        }
541    }
542    if stream.records.is_empty() {
543        return Err(KuteError::InvalidInput("no events found in the input".into()));
544    }
545    Ok(stream)
546}
547
548/// Lend a stream's symbols out as plain records, and give them back.
549fn take_symbols(stream: &mut kute::EventStream) -> Vec<Vec<String>> {
550    stream.records.iter_mut().map(|r| std::mem::take(&mut r.symbols)).collect()
551}
552
553fn give_symbols(stream: &mut kute::EventStream, records: Vec<Vec<String>>) {
554    for (r, symbols) in stream.records.iter_mut().zip(records) {
555        r.symbols = symbols;
556    }
557}
558
559fn describe(stream: &kute::EventStream) -> kute::Result<serde_json::Value> {
560    Ok(json!({ "records": stream.records.len(), "events": stream.events(), "fingerprint": stream.fingerprint()? }))
561}
562
563fn discover(engine: &Engine, args: DiscoverArgs) -> kute::Result<()> {
564    use kute_discover as kd;
565    let params = kd::Params {
566        min_support: args.min_support,
567        max_length: args.max_length,
568        min_cohesion_bits: args.min_cohesion,
569        window: args.window,
570        max_patterns: args.top,
571        ..kd::Params::default()
572    };
573    // Typed events: the symbols go through discovery like any others, and
574    // the streams keep their times for the timing pass afterwards.
575    let mut streams: Option<(kute::EventStream, Option<kute::EventStream>)> = match &args.symbol_field {
576        None => None,
577        Some(field) => {
578            let stream = read_events(&args, field, &args.input)?;
579            Some(if !args.holdout.is_empty() {
580                (stream, Some(read_events(&args, field, &args.holdout)?))
581            } else if let Some(fraction) = args.holdout_fraction {
582                let (head, tail) = stream.split_last(fraction)?;
583                (head, Some(tail))
584            } else {
585                (stream, None)
586            })
587        }
588    };
589    let typed = streams.is_some();
590    let mut records = match &mut streams {
591        Some((stream, _)) => take_symbols(stream),
592        None => read_records(engine, &args, &args.input)?,
593    };
594    let mut held_out = match &mut streams {
595        Some((_, held)) => held.as_mut().map(take_symbols),
596        None if args.holdout.is_empty() => None,
597        None => Some(read_records(engine, &args, &args.holdout)?),
598    };
599    if let Some(fraction) = args.holdout_fraction.filter(|_| !typed) {
600        if args.lines {
601            if !(fraction > 0.0 && fraction < 1.0) {
602                return Err(KuteError::InvalidConfig("the held-out fraction must be between 0 and 1".into()));
603            }
604            let cut = ((records.len() as f64) * (1.0 - fraction)).round() as usize;
605            held_out = Some(records.split_off(cut.clamp(1, records.len())));
606        } else {
607            let (head, tail) = kd::split_holdout(&records, fraction)?;
608            records = head;
609            held_out = Some(tail);
610        }
611    }
612    let start = std::time::Instant::now();
613    let found = kd::discover(&records, &params)?;
614    let seconds = start.elapsed().as_secs_f64();
615    let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
616    let control = if args.control {
617        let found = kd::discover(&kd::shuffled(&records, 0), &params)?;
618        let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
619        Some(json!({
620            "what": "the same run on a shuffled copy of the input: same symbol counts, no order",
621            "patterns": found.patterns.len(),
622            "strongest_evidence_bits": found.patterns.iter().map(|p| p.evidence_bits).fold(0.0, f64::max),
623            "coverage": found.coverage,
624            "held_out_confirmed": evaluation.as_ref().map(|e| e.confirmed),
625            "held_out_coverage": evaluation.as_ref().map(|e| e.coverage),
626        }))
627    } else {
628        None
629    };
630    let events = match streams {
631        None => None,
632        Some((mut stream, mut held)) => {
633            give_symbols(&mut stream, records);
634            if let (Some(h), Some(symbols)) = (held.as_mut(), held_out) {
635                give_symbols(h, symbols);
636            }
637            let timing = if stream.timed() { Some(kd::timing(&found, &stream)?) } else { None };
638            let held_timing = match &held {
639                Some(h) if h.timed() => Some(kd::timing(&found, h)?),
640                _ => None,
641            };
642            Some(json!({
643                "schema": stream.schema,
644                "searched": describe(&stream)?,
645                "held_out": held.as_ref().map(describe).transpose()?,
646                "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",
647                "timing": timing,
648                "held_out_timing": held_timing,
649            }))
650        }
651    };
652    let report = json!({
653        "kute_version": kute::KUTE_VERSION,
654        "discover_seconds": seconds,
655        "peak_memory_bytes": kute_bench::peak_memory_bytes(),
656        "discovery": found,
657        "held_out": evaluation,
658        "control": control,
659        "events": events,
660    });
661    if let Some(path) = &args.output {
662        std::fs::write(path, serde_json::to_vec_pretty(&report)?)?;
663    }
664    print(&report)
665}
666
667#[derive(clap::Args)]
668struct TrainArgs {
669    /// Files or directories to train on. Directories are read recursively.
670    #[arg(long, required = true, num_args = 1..)]
671    input: Vec<PathBuf>,
672    /// Vocabulary identifier, e.g. kute:industrial:events.
673    #[arg(long)]
674    id: String,
675    /// Vocabulary version (semantic versioning).
676    #[arg(long, default_value = "0.1.0")]
677    vocab_version: String,
678    #[arg(long, default_value = "bpe")]
679    algorithm: String,
680    #[arg(long, default_value = "text")]
681    adapter: String,
682    /// Adapter option as key=value. Repeatable.
683    #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
684    adapter_options: Vec<String>,
685    #[arg(long, default_value_t = 4096)]
686    vocab_size: u32,
687    /// none, gpt4, or regex:<pattern>. Default: gpt4 for the text adapter, none otherwise.
688    #[arg(long)]
689    pretokenizer: Option<String>,
690    #[arg(long, default_value_t = 1)]
691    min_frequency: u64,
692    #[arg(long)]
693    max_token_length: Option<usize>,
694    /// Reserved (special) token. Repeatable.
695    #[arg(long = "reserved")]
696    reserved: Vec<String>,
697    /// File with one dictionary entry per line, for the dictionary algorithm.
698    #[arg(long)]
699    dictionary_file: Option<PathBuf>,
700    #[arg(long)]
701    description: Option<String>,
702    /// License of the vocabulary, e.g. an SPDX identifier.
703    #[arg(long)]
704    license: Option<String>,
705    /// Read input files in pieces of about this many bytes, cut at line
706    /// breaks, so memory does not grow with file size. Recorded in the
707    /// vocabulary, because it decides where records end.
708    #[arg(long, value_name = "BYTES")]
709    stream_bytes: Option<usize>,
710    /// Continue from a vocabulary trained earlier on the same input with the
711    /// same settings and a smaller --vocab-size. The result is the same as
712    /// one run to the new size. bpe and sequence-bpe. Its merges are taken
713    /// as given: resume only from a vocabulary you trained or trust.
714    #[arg(long, value_name = "VOCAB")]
715    resume_from: Option<PathBuf>,
716    /// Store the start of the first training records in the vocabulary as
717    /// self-test vectors, so anyone holding the file can check it. They are
718    /// verbatim excerpts: leave this off when the corpus is private.
719    #[arg(long, conflicts_with = "no_test_vectors")]
720    embed_test_vectors: bool,
721    /// Accepted for compatibility; this is the default since v0.4.0.
722    #[arg(long, hide = true)]
723    no_test_vectors: bool,
724    #[arg(long)]
725    output: PathBuf,
726    /// Replace an existing output file even if its content differs.
727    #[arg(long)]
728    force: bool,
729}
730
731fn print(value: &impl serde::Serialize) -> kute::Result<()> {
732    let text = serde_json::to_string_pretty(value)?;
733    let mut out = std::io::stdout().lock();
734    writeln!(out, "{text}")?;
735    Ok(())
736}
737
738fn parse_pretokenizer(spec: Option<&str>, adapter: &str) -> kute::Result<Pretokenizer> {
739    match spec {
740        None => Ok(if adapter == "text" { Pretokenizer::Gpt4 } else { Pretokenizer::None }),
741        Some("none") => Ok(Pretokenizer::None),
742        Some("gpt4") => Ok(Pretokenizer::Gpt4),
743        Some(s) => match s.strip_prefix("regex:") {
744            Some(p) if !p.is_empty() => Ok(Pretokenizer::Regex(p.to_string())),
745            _ => Err(KuteError::InvalidConfig(format!("pretokenizer {s:?}: expected none, gpt4 or regex:<pattern>"))),
746        },
747    }
748}
749
750fn train(engine: &Engine, args: TrainArgs) -> kute::Result<()> {
751    let mut config = TrainingConfig::new(VocabularyId::parse(&args.id)?, args.vocab_size);
752    config.vocabulary_version = Version::parse(&args.vocab_version)
753        .map_err(|e| KuteError::InvalidIdentifier(format!("version {:?}: {e}", args.vocab_version)))?;
754    let symbol_algorithm = args.algorithm == "sequence-bpe";
755    config.pretokenizer = if symbol_algorithm && args.pretokenizer.is_none() {
756        Pretokenizer::None
757    } else {
758        parse_pretokenizer(args.pretokenizer.as_deref(), &args.adapter)?
759    };
760    config.min_frequency = args.min_frequency;
761    config.max_token_length = args.max_token_length;
762    config.reserved_tokens = args.reserved;
763    config.description = args.description;
764    config.license = args.license;
765    config.embed_test_vectors = args.embed_test_vectors;
766    config.stream_bytes = args.stream_bytes;
767    if let Some(path) = &args.resume_from {
768        config.resume_from = Some(Box::new(vocab::load(path)?));
769    }
770    if let Some(path) = &args.dictionary_file {
771        let text = std::fs::read_to_string(path)?;
772        config.dictionary = text.lines().map(|l| l.trim_end_matches('\r')).filter(|l| !l.is_empty()).map(str::to_string).collect();
773    }
774    let mut adapter_config = AdapterConfig::default();
775    for option in &args.adapter_options {
776        let (key, value) = option
777            .split_once('=')
778            .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
779        adapter_config = adapter_config.with(key, value);
780    }
781    let start = std::time::Instant::now();
782    let vocabulary = engine.train_paths(&args.algorithm, &args.adapter, &adapter_config, &args.input, &config)?;
783    let seconds = start.elapsed().as_secs_f64();
784    vocab::save(&vocabulary, &args.output, args.force)?;
785    eprintln!("trained {} {} in {seconds:.2} s -> {}", vocabulary.id(), vocabulary.version(), args.output.display());
786    print(&json!({
787        "output": args.output,
788        "train_seconds": seconds,
789        "peak_memory_bytes": kute_bench::peak_memory_bytes(),
790        "resumed_from": args.resume_from,
791        "summary": vocab::summarize(&vocabulary)?,
792    }))
793}
794
795fn run(engine: Engine, cli: Cli) -> kute::Result<()> {
796    match cli.command {
797        Command::Train(args) => train(&engine, *args),
798        Command::Encode { vocab: vocab_path, input, output, compress, unknown } => {
799            let policy = kute::UnknownPolicy::parse(&unknown)?;
800            let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
801            let raw = std::fs::read(&input)?;
802            let sequence = engine.encode_raw_open(tokenizer.as_ref(), &raw, policy)?;
803            match output {
804                Some(path) => {
805                    let bytes = if compress { sequence.to_bytes_compressed()? } else { sequence.to_bytes()? };
806                    std::fs::write(&path, &bytes)?;
807                    print(&json!({
808                        "output": path,
809                        "input_bytes": raw.len(),
810                        "tokens": sequence.ids.len(),
811                        "escaped_symbols": sequence.escapes.len(),
812                        "serialized_bytes": bytes.len(),
813                        "vocabulary": format!("{} {}", sequence.vocabulary_id, sequence.vocabulary_version),
814                    }))
815                }
816                None => print(&sequence),
817            }
818        }
819        Command::Decode { vocab: vocab_path, input, output, max_units } => {
820            let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
821            let sequence = TokenSequence::from_bytes(&std::fs::read(&input)?)?;
822            let bytes = engine.decode_raw_bounded(tokenizer.as_ref(), &sequence, max_units.unwrap_or(u64::MAX))?;
823            match output {
824                Some(path) => {
825                    std::fs::write(&path, &bytes)?;
826                    print(&json!({ "output": path, "bytes": bytes.len(), "tokens": sequence.ids.len() }))
827                }
828                None => {
829                    let mut out = std::io::stdout().lock();
830                    out.write_all(&bytes)?;
831                    out.flush()?;
832                    Ok(())
833                }
834            }
835        }
836        Command::Inspect { vocab: vocab_path, token, longest } => {
837            let vocabulary = vocab::load(&vocab_path)?;
838            if let Some(id) = token {
839                return print(&vocabulary.record(id)?);
840            }
841            let mut report = json!({ "summary": vocab::summarize(&vocabulary)? });
842            if longest > 0 {
843                let mut learned: Vec<&kute::TokenEntry> = vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
844                learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
845                let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| vocabulary.record(t.id)).collect::<kute::Result<_>>()?;
846                report["longest_learned_tokens"] = serde_json::to_value(rows)?;
847            }
848            print(&report)
849        }
850        Command::Validate { vocab: vocab_path } => {
851            let vocabulary = vocab::load(&vocab_path)?;
852            let report = engine.verify(&vocabulary)?;
853            print(&report)?;
854            if report.ok() {
855                Ok(())
856            } else {
857                Err(KuteError::InvalidVocabulary(format!("{} of {} test vectors failed", report.failures.len(), report.vectors)))
858            }
859        }
860        Command::Compare { a, b } => print(&vocab::compare(&vocab::load(&a)?, &vocab::load(&b)?)?),
861        Command::Convert { input, output, force } => {
862            let vocabulary = vocab::load(&input)?;
863            vocab::save(&vocabulary, &output, force)?;
864            // Read the new file back: the report describes what is on disk.
865            let written = vocab::load(&output)?;
866            if written != vocabulary {
867                return Err(KuteError::Integrity("the converted file does not read back as the same vocabulary".into()));
868            }
869            let median_ms = |path: &PathBuf| -> kute::Result<f64> {
870                let bytes = std::fs::read(path)?;
871                let mut times = Vec::new();
872                for _ in 0..5 {
873                    let start = std::time::Instant::now();
874                    vocab::from_slice(&bytes)?;
875                    times.push(start.elapsed().as_secs_f64() * 1000.0);
876                }
877                times.sort_by(|a, b| a.total_cmp(b));
878                Ok((times[2] * 1000.0).round() / 1000.0)
879            };
880            print(&json!({
881                "input": { "path": input, "bytes": std::fs::metadata(&input)?.len(), "load_ms_median": median_ms(&input)? },
882                "output": { "path": output, "bytes": std::fs::metadata(&output)?.len(), "load_ms_median": median_ms(&output)? },
883                "digest": written.digest()?,
884                "tokens": written.len(),
885                "identical": true,
886            }))
887        }
888        Command::Export { vocab: vocab_path, format: ExportFormat::Tiktoken, output } => {
889            let vocabulary = vocab::load(&vocab_path)?;
890            let export = vocab::export_tiktoken(&vocabulary)?;
891            std::fs::write(&output, &export.bpe_file)?;
892            let mut sidecar = output.clone().into_os_string();
893            sidecar.push(".json");
894            let sidecar = PathBuf::from(sidecar);
895            let meta = json!({
896                "name": vocabulary.id().as_str().replace(':', "_"),
897                "pat_str": export.pat_str,
898                "special_tokens": export.special_tokens,
899                "explicit_n_vocab": export.n_vocab,
900                "source_vocabulary": format!("{} {}", vocabulary.id(), vocabulary.version()),
901                "source_digest": vocabulary.digest()?,
902            });
903            std::fs::write(&sidecar, serde_json::to_vec_pretty(&meta)?)?;
904            print(&json!({ "bpe_file": output, "metadata": sidecar, "tokens": export.n_vocab }))
905        }
906        Command::Benchmark { vocab: vocab_path, dataset, suite, repo_root, large_text, iterations, output } => {
907            let report = if suite {
908                serde_json::to_value(kute_bench::suite::run(&engine, &kute_bench::suite::Options { repo_root, iterations, large_text })?)?
909            } else {
910                let (Some(vocab_path), Some(dataset)) = (vocab_path, dataset) else {
911                    return Err(KuteError::InvalidConfig("benchmark needs --vocab and --dataset, or --suite".into()));
912                };
913                let vocabulary = vocab::load(&vocab_path)?;
914                let documents = kute_bench::read_dataset(&dataset)?;
915                json!({
916                    "environment": kute_bench::Environment::detect(),
917                    "dataset": dataset,
918                    "evaluation": kute_bench::evaluate(&engine, &vocabulary, &documents, iterations)?,
919                })
920            };
921            if let Some(path) = output {
922                let mut text = serde_json::to_string_pretty(&report)?;
923                text.push('\n');
924                std::fs::write(&path, text)?;
925                eprintln!("report written to {}", path.display());
926            }
927            print(&report)
928        }
929        Command::SampleData { output } => {
930            use kute_bench::data;
931            std::fs::create_dir_all(&output)?;
932            let files: Vec<(&str, Vec<u8>, &str)> = vec![
933                ("alarms-train.jsonl", data::alarm_log(51, 4000), "plant alarm log, 4000 episodes"),
934                ("alarms-eval.jsonl", data::alarm_log(52, 1000), "plant alarm log, 1000 episodes, different seed"),
935                ("messages-train.jsonl", data::agent_messages(61, 4000), "agent messages, 4000 records"),
936                ("messages-eval.jsonl", data::agent_messages(62, 1000), "agent messages, 1000 records, different seed"),
937                ("frames-train.bin", data::binary_records(31, 6000), "binary telemetry frames, 6000 records"),
938                ("frames-eval.bin", data::binary_records(32, 2000), "binary telemetry frames, 2000 records, different seed"),
939                ("words-train.txt", data::invented_words(81, 60_000), "invented-word text, 60000 words"),
940                ("words-eval.txt", data::invented_words(82, 15_000), "invented-word text, 15000 words, different seed"),
941            ];
942            let mut written = Vec::new();
943            for (name, bytes, what) in files {
944                std::fs::write(output.join(name), &bytes)?;
945                written.push(json!({ "file": name, "bytes": bytes.len(), "sha256": kute::sha256_tagged(&bytes), "content": what }));
946            }
947            print(&json!({ "output": output, "synthetic": true, "files": written }))
948        }
949        Command::Discover(args) => discover(&engine, *args),
950        Command::Evolve { vocab: vocab_path, additions, new_version, output, force } => {
951            let version = Version::parse(&new_version).map_err(|e| KuteError::InvalidIdentifier(format!("version {new_version:?}: {e}")))?;
952            let parent = vocab::load(&vocab_path)?;
953            let child = kute::bpe::sequence::evolve(&parent, &split_additions(&additions), version)?;
954            let report = engine.verify(&child)?;
955            if !report.ok() {
956                return Err(KuteError::Backend(format!("the evolved vocabulary fails its test vectors: {}", report.failures.join("; "))));
957            }
958            vocab::save(&child, &output, force)?;
959            // A container writes every id in as many bytes as the largest
960            // id of the vocabulary needs. A step across one of these sizes
961            // makes every token cost more, which can outweigh what the new
962            // tokens save (measured: benchmarks/README.md, drifting data).
963            let mut warnings = Vec::new();
964            for (limit, bytes) in [(256usize, "one byte"), (65_536, "two bytes")] {
965                if parent.len() <= limit && child.len() > limit {
966                    warnings.push(format!(
967                        "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.",
968                        parent.len(),
969                        child.len()
970                    ));
971                }
972            }
973            for warning in &warnings {
974                eprintln!("warning: {warning}");
975            }
976            print(&json!({
977                "output": output,
978                "parent": { "version": parent.version().to_string(), "digest": parent.digest()?, "tokens": parent.len() },
979                "summary": vocab::summarize(&child)?,
980                "warnings": warnings,
981            }))
982        }
983        Command::Peer { action } => peer(engine, action),
984        Command::Mcp { vocab: paths, max_input_bytes, max_output_bytes } => {
985            let vocabularies = paths.iter().map(vocab::load).collect::<kute::Result<Vec<_>>>()?;
986            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() };
987            let server = mcp::Server::new(engine, vocabularies, limits)?;
988            server.serve(std::io::stdin().lock(), std::io::stdout().lock())?;
989            Ok(())
990        }
991        Command::Capabilities => {
992            let registry = engine.registry();
993            let algorithms: Vec<kute::TokenizerCapabilities> =
994                registry.algorithm_names().iter().map(|n| registry.tokenizer(n).map(|t| t.capabilities())).collect::<kute::Result<_>>()?;
995            let adapters: Vec<serde_json::Value> = registry
996                .adapter_names()
997                .iter()
998                .map(|n| {
999                    registry.adapter(n).map(|a| {
1000                        let c = a.capabilities();
1001                        json!({ "name": c.name, "modality": c.modality, "lossless": c.lossless, "notes": c.notes })
1002                    })
1003                })
1004                .collect::<kute::Result<_>>()?;
1005            print(&json!({
1006                "kute_version": kute::KUTE_VERSION,
1007                "kvf_version": kute::KVF_VERSION,
1008                "algorithms": algorithms,
1009                "adapters": adapters,
1010            }))
1011        }
1012    }
1013}
1014
1015/// Parse the command line and run it on `engine`. The `kute` binary passes
1016/// the default engine; other front ends can register more algorithms first.
1017pub fn main_with(engine: Engine) -> ExitCode {
1018    match run(engine, Cli::parse()) {
1019        Ok(()) => ExitCode::SUCCESS,
1020        Err(e) => {
1021            eprintln!("kute: {e}");
1022            ExitCode::FAILURE
1023        }
1024    }
1025}