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