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