kute-cli 0.4.0

Command line interface for the Kannaka Universal Tokenization Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//! `kute`: train, encode, decode, inspect, validate, compare, export, benchmark.
//!
//! Results go to stdout as JSON (or raw bytes for `decode`), messages to
//! stderr. Exit status is 0 on success and 1 on any error.

use clap::{Parser, Subcommand, ValueEnum};
use kute::{vocab, AdapterConfig, Engine, KuteError, Pretokenizer, TokenSequence, TrainingConfig, Version, VocabularyId};
use serde_json::json;
use std::io::Write;
use std::path::PathBuf;
use std::process::ExitCode;

#[derive(Parser)]
#[command(name = "kute", version, about = "Kannaka Universal Tokenization Engine", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Learn a vocabulary from files and write it as KVF.
    Train(Box<TrainArgs>),
    /// Encode a file to a .kute token sequence.
    Encode {
        #[arg(long)]
        vocab: PathBuf,
        #[arg(long)]
        input: PathBuf,
        /// Where to write the .kute container. Without it, token ids are printed as JSON.
        #[arg(long)]
        output: Option<PathBuf>,
        /// Write the compressed container (format 2) instead of plain varint ids.
        #[arg(long, requires = "output")]
        compress: bool,
        /// What to do with a symbol the vocabulary does not contain:
        /// `strict` refuses the input, `escape` carries the symbol literally
        /// in the sequence so it still decodes exactly.
        #[arg(long, default_value = "strict")]
        unknown: String,
    },
    /// Decode a .kute token sequence back to bytes.
    Decode {
        #[arg(long)]
        vocab: PathBuf,
        #[arg(long)]
        input: PathBuf,
        /// Where to write the decoded bytes. Without it, they go to stdout.
        #[arg(long)]
        output: Option<PathBuf>,
        /// Refuse a sequence that would decode to more than this many bytes
        /// or symbols. Use it for sequences from an untrusted source.
        #[arg(long)]
        max_units: Option<u64>,
    },
    /// Summarize a vocabulary, or show tokens from it.
    Inspect {
        vocab: PathBuf,
        /// Show the full envelope of one token id.
        #[arg(long)]
        token: Option<u32>,
        /// Show the N longest learned tokens.
        #[arg(long, default_value_t = 0)]
        longest: usize,
    },
    /// Check structure, integrity and the embedded test vectors.
    Validate { vocab: PathBuf },
    /// Compare two vocabularies by token content.
    Compare { a: PathBuf, b: PathBuf },
    /// Rewrite a vocabulary in the other file form: compact binary when the
    /// output ends in .kvfb, JSON otherwise. The digest does not change.
    Convert {
        #[arg(long)]
        input: PathBuf,
        #[arg(long)]
        output: PathBuf,
        /// Replace an existing output file.
        #[arg(long)]
        force: bool,
    },
    /// Convert a vocabulary to another tool's format.
    Export {
        #[arg(long)]
        vocab: PathBuf,
        #[arg(long, value_enum, default_value_t = ExportFormat::Tiktoken)]
        format: ExportFormat,
        /// Output file, e.g. general.tiktoken. A `.json` sidecar with the
        /// pattern and special tokens is written next to it.
        #[arg(long)]
        output: PathBuf,
    },
    /// Measure a vocabulary on a dataset, or run the benchmark suite.
    Benchmark {
        #[arg(long, required_unless_present = "suite")]
        vocab: Option<PathBuf>,
        /// File or directory to evaluate on. Keep it separate from training data.
        #[arg(long, required_unless_present = "suite")]
        dataset: Option<PathBuf>,
        /// Run the built-in benchmark program instead.
        #[arg(long, conflicts_with_all = ["vocab", "dataset"])]
        suite: bool,
        /// Repository root for the suite's in-repo corpora.
        #[arg(long)]
        repo_root: Option<PathBuf>,
        /// A large UTF-8 text file for the suite's real-data case (for example enwik8).
        /// The first 90% trains a 32K vocabulary; the rest is the evaluation set.
        #[arg(long, requires = "suite")]
        large_text: Option<PathBuf>,
        #[arg(long, default_value_t = 5)]
        iterations: usize,
        /// Also write the JSON report to this file.
        #[arg(long)]
        output: Option<PathBuf>,
    },
    /// Find recurring patterns in symbol streams, without training a tokenizer.
    Discover(Box<DiscoverArgs>),
    /// Derive the next version of an event vocabulary by adding symbols or
    /// symbol sequences. Existing token ids do not change.
    Evolve {
        #[arg(long)]
        vocab: PathBuf,
        /// A symbol, or several separated by spaces for a sequence. Repeatable.
        #[arg(long = "add", required = true, value_name = "SYMBOLS")]
        additions: Vec<String>,
        /// Version of the new vocabulary; must be greater than the current one.
        #[arg(long)]
        new_version: String,
        #[arg(long)]
        output: PathBuf,
        #[arg(long)]
        force: bool,
    },
    /// Exchange vocabularies and encoded messages with another kute process.
    /// No encryption or authentication: use a trusted network.
    Peer {
        #[command(subcommand)]
        action: PeerAction,
    },
    /// List registered algorithms and adapters and what each declares.
    Capabilities,
    /// Write the seeded example datasets used by the documentation.
    SampleData {
        /// Directory to create the files in.
        #[arg(long)]
        output: PathBuf,
    },
}

#[derive(Clone, Copy, ValueEnum)]
enum ExportFormat {
    Tiktoken,
}

#[derive(Subcommand)]
enum PeerAction {
    /// Wait for one connection and answer it until it closes.
    Serve {
        /// Address to listen on, e.g. 127.0.0.1:7411.
        #[arg(long)]
        listen: String,
        /// Vocabularies this side already holds. Repeatable.
        #[arg(long)]
        vocab: Vec<PathBuf>,
        /// Refuse vocabularies this side does not already hold.
        #[arg(long)]
        no_new_vocabularies: bool,
        /// Let the other side extend vocabularies held here.
        #[arg(long)]
        accept_proposals: bool,
        /// Refuse a message that decodes to more than this many units.
        #[arg(long, default_value_t = 268_435_456)]
        max_units: u64,
        /// Write each decoded message and each vocabulary received here.
        #[arg(long)]
        output_dir: Option<PathBuf>,
    },
    /// Connect, make sure the other side holds the vocabulary, and send files.
    Send {
        /// Address to connect to.
        #[arg(long)]
        connect: String,
        #[arg(long)]
        vocab: PathBuf,
        /// Files to encode and send. Repeatable.
        #[arg(long, num_args = 0..)]
        input: Vec<PathBuf>,
        /// strict or escape; see `kute encode --unknown`.
        #[arg(long, default_value = "strict")]
        unknown: String,
        /// Before sending, propose these additions (as in `kute evolve --add`).
        #[arg(long = "propose", value_name = "SYMBOLS", requires = "new_version")]
        additions: Vec<String>,
        #[arg(long)]
        new_version: Option<String>,
    },
}

fn split_additions(additions: &[String]) -> Vec<Vec<String>> {
    additions.iter().map(|a| a.split_whitespace().map(str::to_string).collect()).collect()
}

fn peer(engine: Engine, action: PeerAction) -> kute::Result<()> {
    use kute_protocol::{Framed, Peer, Policy, Session, DEFAULT_MAX_FRAME};
    match action {
        PeerAction::Serve { listen, vocab: held, no_new_vocabularies, accept_proposals, max_units, output_dir } => {
            let policy = Policy { accept_vocabularies: !no_new_vocabularies, accept_proposals, max_decoded_units: max_units, ..Policy::default() };
            let mut peer = Peer::new("kute", engine, policy);
            for path in &held {
                peer.add_vocabulary(vocab::load(path)?)?;
            }
            let before = peer.digests();
            let listener = std::net::TcpListener::bind(&listen)?;
            eprintln!("listening on {}", listener.local_addr()?);
            let (stream, from) = listener.accept()?;
            let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
            let handled = session.serve()?;
            let inbox = session.peer.take_inbox();
            let new: Vec<String> = session.peer.digests().into_iter().filter(|d| !before.contains(d)).collect();
            if let Some(dir) = &output_dir {
                std::fs::create_dir_all(dir)?;
                for message in &inbox {
                    std::fs::write(dir.join(format!("message-{}.bin", message.id)), &message.bytes)?;
                }
                for digest in &new {
                    if let Some(v) = session.peer.vocabulary(digest) {
                        let name = format!("{}-{}.kvf", v.id().as_str().replace(':', "_"), v.version());
                        vocab::save(v, dir.join(name), true)?;
                    }
                }
            }
            print(&json!({
                "from": from.to_string(),
                "messages_handled": handled,
                "vocabularies_received": new,
                "received": inbox.iter().map(|m| json!({
                    "id": m.id,
                    "bytes": m.bytes.len(),
                    "tokens": m.sequence.ids.len(),
                    "escaped_symbols": m.sequence.escapes.len(),
                    "vocabulary": format!("{} {}", m.sequence.vocabulary_id, m.sequence.vocabulary_version),
                })).collect::<Vec<_>>(),
            }))
        }
        PeerAction::Send { connect, vocab: vocab_path, input, unknown, additions, new_version } => {
            let policy = kute::UnknownPolicy::parse(&unknown)?;
            let mut peer = Peer::new("kute", engine, Policy::default());
            let mut digest = peer.add_vocabulary(vocab::load(&vocab_path)?)?;
            let mut session = Session::new(peer, Framed::new(std::net::TcpStream::connect(&connect)?, DEFAULT_MAX_FRAME));
            let remote = session.connect()?;
            let transferred = session.share(&digest)?;
            let mut proposed = None;
            if let Some(version) = &new_version {
                digest = session.propose(&digest, &split_additions(&additions), version)?;
                proposed = Some(digest.clone());
            }
            let mut sent = Vec::new();
            for path in &input {
                let raw = std::fs::read(path)?;
                let units = session.send(&digest, &raw, policy)?;
                sent.push(json!({ "input": path, "bytes": raw.len(), "units_decoded_by_peer": units, "receipt_matches": true }));
            }
            print(&json!({
                "peer": remote.peer,
                "peer_software": remote.software,
                "vocabulary_transferred": transferred,
                "vocabulary_after_proposal": proposed,
                "sent": sent,
            }))
        }
    }
}

#[derive(clap::Args)]
struct DiscoverArgs {
    /// Files or directories to look for patterns in.
    #[arg(long, required = true, num_args = 1..)]
    input: Vec<PathBuf>,
    /// Adapter that turns each file into one record of symbols.
    #[arg(long, default_value = "jsonl-events")]
    adapter: String,
    /// Adapter option as key=value. Repeatable.
    #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
    adapter_options: Vec<String>,
    /// Read plain text instead of using an adapter: every line is one
    /// record, symbols separated by whitespace.
    #[arg(long, conflicts_with_all = ["adapter", "adapter_options"])]
    lines: bool,
    /// Read typed events instead: JSON Lines with one event per line, the
    /// event name in this field. Keeps time and grouping; see the other
    /// --*-field options.
    #[arg(long, value_name = "FIELD", conflicts_with_all = ["adapter", "adapter_options", "lines"])]
    symbol_field: Option<String>,
    /// Field with the event time, a whole number of --time-unit. With it,
    /// the report says how long each pattern takes.
    #[arg(long, value_name = "FIELD", requires = "symbol_field")]
    time_field: Option<String>,
    /// Unit of the time field: s, ms, us or ns.
    #[arg(long, default_value = "s", requires = "time_field")]
    time_unit: String,
    /// Field naming what an event belongs to (a device, a block, a session).
    /// Events with the same value form one record.
    #[arg(long, value_name = "FIELD", requires = "symbol_field")]
    group_field: Option<String>,
    /// Name recorded for this way of reading the events.
    #[arg(long, default_value = "kute:events:unnamed", requires = "symbol_field")]
    schema_id: String,
    /// Files with held-out data to check the patterns against.
    #[arg(long, num_args = 1.., conflicts_with = "holdout_fraction")]
    holdout: Vec<PathBuf>,
    /// Hold out this share of the input instead. With --lines the last
    /// records are held out; otherwise the end of each record.
    #[arg(long)]
    holdout_fraction: Option<f64>,
    #[arg(long, default_value_t = 5)]
    min_support: u64,
    /// Longest contiguous pattern, in symbols.
    #[arg(long, default_value_t = 8)]
    max_length: usize,
    /// Minimum cohesion in bits: how much more often than chance.
    #[arg(long, default_value_t = 1.0)]
    min_cohesion: f64,
    /// Gapped pairs look this many symbols ahead; 0 turns them off.
    #[arg(long, default_value_t = 8)]
    window: usize,
    /// Report at most this many patterns of each kind.
    #[arg(long, default_value_t = 50)]
    top: usize,
    /// Also run on a shuffled copy of the input (same symbol counts, no
    /// order) and report how much the method finds there.
    #[arg(long)]
    control: bool,
    /// Also write the JSON report to this file.
    #[arg(long)]
    output: Option<PathBuf>,
}

fn read_records(engine: &Engine, args: &DiscoverArgs, paths: &[PathBuf]) -> kute::Result<Vec<Vec<String>>> {
    let mut adapter_config = AdapterConfig::default();
    for option in &args.adapter_options {
        let (key, value) = option
            .split_once('=')
            .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
        adapter_config = adapter_config.with(key, value);
    }
    let mut records = Vec::new();
    for path in paths {
        for file in kute::collect_files(path)? {
            let raw = std::fs::read(&file)?;
            if args.lines {
                let text = String::from_utf8(raw).map_err(|_| KuteError::InvalidInput(format!("{}: not UTF-8", file.display())))?;
                records.extend(text.lines().map(|l| l.split_whitespace().map(str::to_string).collect::<Vec<_>>()).filter(|r| !r.is_empty()));
            } else {
                let input = engine.registry().adapter(&args.adapter)?.ingest(&raw, &adapter_config)?;
                records.extend(kute_discover::records_of(&[input])?);
            }
        }
    }
    if records.is_empty() {
        return Err(KuteError::InvalidInput("no records found in the input".into()));
    }
    Ok(records)
}

fn read_events(args: &DiscoverArgs, symbol_field: &str, paths: &[PathBuf]) -> kute::Result<kute::EventStream> {
    let schema = kute::EventSchema {
        id: args.schema_id.clone(),
        version: 1,
        symbol_field: symbol_field.to_string(),
        time_unit: args.time_field.as_ref().map(|_| kute::TimeUnit::parse(&args.time_unit)).transpose()?,
        time_field: args.time_field.clone(),
        group_field: args.group_field.clone(),
    };
    let mut stream = kute::EventStream::new(schema)?;
    for path in paths {
        for file in kute::collect_files(path)? {
            let reader = std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(&file)?);
            stream.read_jsonl(reader, &file.display().to_string())?;
        }
    }
    if stream.records.is_empty() {
        return Err(KuteError::InvalidInput("no events found in the input".into()));
    }
    Ok(stream)
}

/// Lend a stream's symbols out as plain records, and give them back.
fn take_symbols(stream: &mut kute::EventStream) -> Vec<Vec<String>> {
    stream.records.iter_mut().map(|r| std::mem::take(&mut r.symbols)).collect()
}

fn give_symbols(stream: &mut kute::EventStream, records: Vec<Vec<String>>) {
    for (r, symbols) in stream.records.iter_mut().zip(records) {
        r.symbols = symbols;
    }
}

fn describe(stream: &kute::EventStream) -> kute::Result<serde_json::Value> {
    Ok(json!({ "records": stream.records.len(), "events": stream.events(), "fingerprint": stream.fingerprint()? }))
}

fn discover(engine: &Engine, args: DiscoverArgs) -> kute::Result<()> {
    use kute_discover as kd;
    let params = kd::Params {
        min_support: args.min_support,
        max_length: args.max_length,
        min_cohesion_bits: args.min_cohesion,
        window: args.window,
        max_patterns: args.top,
        ..kd::Params::default()
    };
    // Typed events: the symbols go through discovery like any others, and
    // the streams keep their times for the timing pass afterwards.
    let mut streams: Option<(kute::EventStream, Option<kute::EventStream>)> = match &args.symbol_field {
        None => None,
        Some(field) => {
            let stream = read_events(&args, field, &args.input)?;
            Some(if !args.holdout.is_empty() {
                (stream, Some(read_events(&args, field, &args.holdout)?))
            } else if let Some(fraction) = args.holdout_fraction {
                let (head, tail) = stream.split_last(fraction)?;
                (head, Some(tail))
            } else {
                (stream, None)
            })
        }
    };
    let typed = streams.is_some();
    let mut records = match &mut streams {
        Some((stream, _)) => take_symbols(stream),
        None => read_records(engine, &args, &args.input)?,
    };
    let mut held_out = match &mut streams {
        Some((_, held)) => held.as_mut().map(take_symbols),
        None if args.holdout.is_empty() => None,
        None => Some(read_records(engine, &args, &args.holdout)?),
    };
    if let Some(fraction) = args.holdout_fraction.filter(|_| !typed) {
        if args.lines {
            if !(fraction > 0.0 && fraction < 1.0) {
                return Err(KuteError::InvalidConfig("the held-out fraction must be between 0 and 1".into()));
            }
            let cut = ((records.len() as f64) * (1.0 - fraction)).round() as usize;
            held_out = Some(records.split_off(cut.clamp(1, records.len())));
        } else {
            let (head, tail) = kd::split_holdout(&records, fraction)?;
            records = head;
            held_out = Some(tail);
        }
    }
    let start = std::time::Instant::now();
    let found = kd::discover(&records, &params)?;
    let seconds = start.elapsed().as_secs_f64();
    let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
    let control = if args.control {
        let found = kd::discover(&kd::shuffled(&records, 0), &params)?;
        let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
        Some(json!({
            "what": "the same run on a shuffled copy of the input: same symbol counts, no order",
            "patterns": found.patterns.len(),
            "strongest_evidence_bits": found.patterns.iter().map(|p| p.evidence_bits).fold(0.0, f64::max),
            "coverage": found.coverage,
            "held_out_confirmed": evaluation.as_ref().map(|e| e.confirmed),
            "held_out_coverage": evaluation.as_ref().map(|e| e.coverage),
        }))
    } else {
        None
    };
    let events = match streams {
        None => None,
        Some((mut stream, mut held)) => {
            give_symbols(&mut stream, records);
            if let (Some(h), Some(symbols)) = (held.as_mut(), held_out) {
                give_symbols(h, symbols);
            }
            let timing = if stream.timed() { Some(kd::timing(&found, &stream)?) } else { None };
            let held_timing = match &held {
                Some(h) if h.timed() => Some(kd::timing(&found, h)?),
                _ => None,
            };
            Some(json!({
                "schema": stream.schema,
                "searched": describe(&stream)?,
                "held_out": held.as_ref().map(describe).transpose()?,
                "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",
                "timing": timing,
                "held_out_timing": held_timing,
            }))
        }
    };
    let report = json!({
        "kute_version": kute::KUTE_VERSION,
        "discover_seconds": seconds,
        "peak_memory_bytes": kute_bench::peak_memory_bytes(),
        "discovery": found,
        "held_out": evaluation,
        "control": control,
        "events": events,
    });
    if let Some(path) = &args.output {
        std::fs::write(path, serde_json::to_vec_pretty(&report)?)?;
    }
    print(&report)
}

#[derive(clap::Args)]
struct TrainArgs {
    /// Files or directories to train on. Directories are read recursively.
    #[arg(long, required = true, num_args = 1..)]
    input: Vec<PathBuf>,
    /// Vocabulary identifier, e.g. kute:industrial:events.
    #[arg(long)]
    id: String,
    /// Vocabulary version (semantic versioning).
    #[arg(long, default_value = "0.1.0")]
    vocab_version: String,
    #[arg(long, default_value = "bpe")]
    algorithm: String,
    #[arg(long, default_value = "text")]
    adapter: String,
    /// Adapter option as key=value. Repeatable.
    #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
    adapter_options: Vec<String>,
    #[arg(long, default_value_t = 4096)]
    vocab_size: u32,
    /// none, gpt4, or regex:<pattern>. Default: gpt4 for the text adapter, none otherwise.
    #[arg(long)]
    pretokenizer: Option<String>,
    #[arg(long, default_value_t = 1)]
    min_frequency: u64,
    #[arg(long)]
    max_token_length: Option<usize>,
    /// Reserved (special) token. Repeatable.
    #[arg(long = "reserved")]
    reserved: Vec<String>,
    /// File with one dictionary entry per line, for the dictionary algorithm.
    #[arg(long)]
    dictionary_file: Option<PathBuf>,
    #[arg(long)]
    description: Option<String>,
    /// License of the vocabulary, e.g. an SPDX identifier.
    #[arg(long)]
    license: Option<String>,
    /// Read input files in pieces of about this many bytes, cut at line
    /// breaks, so memory does not grow with file size. Recorded in the
    /// vocabulary, because it decides where records end.
    #[arg(long, value_name = "BYTES")]
    stream_bytes: Option<usize>,
    /// Store the start of the first training records in the vocabulary as
    /// self-test vectors, so anyone holding the file can check it. They are
    /// verbatim excerpts: leave this off when the corpus is private.
    #[arg(long, conflicts_with = "no_test_vectors")]
    embed_test_vectors: bool,
    /// Accepted for compatibility; this is the default since v0.4.0.
    #[arg(long, hide = true)]
    no_test_vectors: bool,
    #[arg(long)]
    output: PathBuf,
    /// Replace an existing output file even if its content differs.
    #[arg(long)]
    force: bool,
}

fn print(value: &impl serde::Serialize) -> kute::Result<()> {
    let text = serde_json::to_string_pretty(value)?;
    let mut out = std::io::stdout().lock();
    writeln!(out, "{text}")?;
    Ok(())
}

fn parse_pretokenizer(spec: Option<&str>, adapter: &str) -> kute::Result<Pretokenizer> {
    match spec {
        None => Ok(if adapter == "text" { Pretokenizer::Gpt4 } else { Pretokenizer::None }),
        Some("none") => Ok(Pretokenizer::None),
        Some("gpt4") => Ok(Pretokenizer::Gpt4),
        Some(s) => match s.strip_prefix("regex:") {
            Some(p) if !p.is_empty() => Ok(Pretokenizer::Regex(p.to_string())),
            _ => Err(KuteError::InvalidConfig(format!("pretokenizer {s:?}: expected none, gpt4 or regex:<pattern>"))),
        },
    }
}

fn train(engine: &Engine, args: TrainArgs) -> kute::Result<()> {
    let mut config = TrainingConfig::new(VocabularyId::parse(&args.id)?, args.vocab_size);
    config.vocabulary_version = Version::parse(&args.vocab_version)
        .map_err(|e| KuteError::InvalidIdentifier(format!("version {:?}: {e}", args.vocab_version)))?;
    let symbol_algorithm = args.algorithm == "sequence-bpe";
    config.pretokenizer = if symbol_algorithm && args.pretokenizer.is_none() {
        Pretokenizer::None
    } else {
        parse_pretokenizer(args.pretokenizer.as_deref(), &args.adapter)?
    };
    config.min_frequency = args.min_frequency;
    config.max_token_length = args.max_token_length;
    config.reserved_tokens = args.reserved;
    config.description = args.description;
    config.license = args.license;
    config.embed_test_vectors = args.embed_test_vectors;
    config.stream_bytes = args.stream_bytes;
    if let Some(path) = &args.dictionary_file {
        let text = std::fs::read_to_string(path)?;
        config.dictionary = text.lines().map(|l| l.trim_end_matches('\r')).filter(|l| !l.is_empty()).map(str::to_string).collect();
    }
    let mut adapter_config = AdapterConfig::default();
    for option in &args.adapter_options {
        let (key, value) = option
            .split_once('=')
            .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
        adapter_config = adapter_config.with(key, value);
    }
    let start = std::time::Instant::now();
    let vocabulary = engine.train_paths(&args.algorithm, &args.adapter, &adapter_config, &args.input, &config)?;
    let seconds = start.elapsed().as_secs_f64();
    vocab::save(&vocabulary, &args.output, args.force)?;
    eprintln!("trained {} {} in {seconds:.2} s -> {}", vocabulary.id(), vocabulary.version(), args.output.display());
    print(&json!({
        "output": args.output,
        "train_seconds": seconds,
        "peak_memory_bytes": kute_bench::peak_memory_bytes(),
        "summary": vocab::summarize(&vocabulary)?,
    }))
}

fn run(engine: Engine, cli: Cli) -> kute::Result<()> {
    match cli.command {
        Command::Train(args) => train(&engine, *args),
        Command::Encode { vocab: vocab_path, input, output, compress, unknown } => {
            let policy = kute::UnknownPolicy::parse(&unknown)?;
            let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
            let raw = std::fs::read(&input)?;
            let sequence = engine.encode_raw_open(tokenizer.as_ref(), &raw, policy)?;
            match output {
                Some(path) => {
                    let bytes = if compress { sequence.to_bytes_compressed()? } else { sequence.to_bytes()? };
                    std::fs::write(&path, &bytes)?;
                    print(&json!({
                        "output": path,
                        "input_bytes": raw.len(),
                        "tokens": sequence.ids.len(),
                        "escaped_symbols": sequence.escapes.len(),
                        "serialized_bytes": bytes.len(),
                        "vocabulary": format!("{} {}", sequence.vocabulary_id, sequence.vocabulary_version),
                    }))
                }
                None => print(&sequence),
            }
        }
        Command::Decode { vocab: vocab_path, input, output, max_units } => {
            let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
            let sequence = TokenSequence::from_bytes(&std::fs::read(&input)?)?;
            let bytes = engine.decode_raw_bounded(tokenizer.as_ref(), &sequence, max_units.unwrap_or(u64::MAX))?;
            match output {
                Some(path) => {
                    std::fs::write(&path, &bytes)?;
                    print(&json!({ "output": path, "bytes": bytes.len(), "tokens": sequence.ids.len() }))
                }
                None => {
                    let mut out = std::io::stdout().lock();
                    out.write_all(&bytes)?;
                    out.flush()?;
                    Ok(())
                }
            }
        }
        Command::Inspect { vocab: vocab_path, token, longest } => {
            let vocabulary = vocab::load(&vocab_path)?;
            if let Some(id) = token {
                return print(&vocabulary.record(id)?);
            }
            let mut report = json!({ "summary": vocab::summarize(&vocabulary)? });
            if longest > 0 {
                let mut learned: Vec<&kute::TokenEntry> = vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
                learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
                let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| vocabulary.record(t.id)).collect::<kute::Result<_>>()?;
                report["longest_learned_tokens"] = serde_json::to_value(rows)?;
            }
            print(&report)
        }
        Command::Validate { vocab: vocab_path } => {
            let vocabulary = vocab::load(&vocab_path)?;
            let report = engine.verify(&vocabulary)?;
            print(&report)?;
            if report.ok() {
                Ok(())
            } else {
                Err(KuteError::InvalidVocabulary(format!("{} of {} test vectors failed", report.failures.len(), report.vectors)))
            }
        }
        Command::Compare { a, b } => print(&vocab::compare(&vocab::load(&a)?, &vocab::load(&b)?)?),
        Command::Convert { input, output, force } => {
            let vocabulary = vocab::load(&input)?;
            vocab::save(&vocabulary, &output, force)?;
            // Read the new file back: the report describes what is on disk.
            let written = vocab::load(&output)?;
            if written != vocabulary {
                return Err(KuteError::Integrity("the converted file does not read back as the same vocabulary".into()));
            }
            let median_ms = |path: &PathBuf| -> kute::Result<f64> {
                let bytes = std::fs::read(path)?;
                let mut times = Vec::new();
                for _ in 0..5 {
                    let start = std::time::Instant::now();
                    vocab::from_slice(&bytes)?;
                    times.push(start.elapsed().as_secs_f64() * 1000.0);
                }
                times.sort_by(|a, b| a.total_cmp(b));
                Ok((times[2] * 1000.0).round() / 1000.0)
            };
            print(&json!({
                "input": { "path": input, "bytes": std::fs::metadata(&input)?.len(), "load_ms_median": median_ms(&input)? },
                "output": { "path": output, "bytes": std::fs::metadata(&output)?.len(), "load_ms_median": median_ms(&output)? },
                "digest": written.digest()?,
                "tokens": written.len(),
                "identical": true,
            }))
        }
        Command::Export { vocab: vocab_path, format: ExportFormat::Tiktoken, output } => {
            let vocabulary = vocab::load(&vocab_path)?;
            let export = vocab::export_tiktoken(&vocabulary)?;
            std::fs::write(&output, &export.bpe_file)?;
            let mut sidecar = output.clone().into_os_string();
            sidecar.push(".json");
            let sidecar = PathBuf::from(sidecar);
            let meta = json!({
                "name": vocabulary.id().as_str().replace(':', "_"),
                "pat_str": export.pat_str,
                "special_tokens": export.special_tokens,
                "explicit_n_vocab": export.n_vocab,
                "source_vocabulary": format!("{} {}", vocabulary.id(), vocabulary.version()),
                "source_digest": vocabulary.digest()?,
            });
            std::fs::write(&sidecar, serde_json::to_vec_pretty(&meta)?)?;
            print(&json!({ "bpe_file": output, "metadata": sidecar, "tokens": export.n_vocab }))
        }
        Command::Benchmark { vocab: vocab_path, dataset, suite, repo_root, large_text, iterations, output } => {
            let report = if suite {
                serde_json::to_value(kute_bench::suite::run(&engine, &kute_bench::suite::Options { repo_root, iterations, large_text })?)?
            } else {
                let (Some(vocab_path), Some(dataset)) = (vocab_path, dataset) else {
                    return Err(KuteError::InvalidConfig("benchmark needs --vocab and --dataset, or --suite".into()));
                };
                let vocabulary = vocab::load(&vocab_path)?;
                let documents = kute_bench::read_dataset(&dataset)?;
                json!({
                    "environment": kute_bench::Environment::detect(),
                    "dataset": dataset,
                    "evaluation": kute_bench::evaluate(&engine, &vocabulary, &documents, iterations)?,
                })
            };
            if let Some(path) = output {
                let mut text = serde_json::to_string_pretty(&report)?;
                text.push('\n');
                std::fs::write(&path, text)?;
                eprintln!("report written to {}", path.display());
            }
            print(&report)
        }
        Command::SampleData { output } => {
            use kute_bench::data;
            std::fs::create_dir_all(&output)?;
            let files: Vec<(&str, Vec<u8>, &str)> = vec![
                ("alarms-train.jsonl", data::alarm_log(51, 4000), "plant alarm log, 4000 episodes"),
                ("alarms-eval.jsonl", data::alarm_log(52, 1000), "plant alarm log, 1000 episodes, different seed"),
                ("messages-train.jsonl", data::agent_messages(61, 4000), "agent messages, 4000 records"),
                ("messages-eval.jsonl", data::agent_messages(62, 1000), "agent messages, 1000 records, different seed"),
                ("frames-train.bin", data::binary_records(31, 6000), "binary telemetry frames, 6000 records"),
                ("frames-eval.bin", data::binary_records(32, 2000), "binary telemetry frames, 2000 records, different seed"),
                ("words-train.txt", data::invented_words(81, 60_000), "invented-word text, 60000 words"),
                ("words-eval.txt", data::invented_words(82, 15_000), "invented-word text, 15000 words, different seed"),
            ];
            let mut written = Vec::new();
            for (name, bytes, what) in files {
                std::fs::write(output.join(name), &bytes)?;
                written.push(json!({ "file": name, "bytes": bytes.len(), "sha256": kute::sha256_tagged(&bytes), "content": what }));
            }
            print(&json!({ "output": output, "synthetic": true, "files": written }))
        }
        Command::Discover(args) => discover(&engine, *args),
        Command::Evolve { vocab: vocab_path, additions, new_version, output, force } => {
            let version = Version::parse(&new_version).map_err(|e| KuteError::InvalidIdentifier(format!("version {new_version:?}: {e}")))?;
            let parent = vocab::load(&vocab_path)?;
            let child = kute::bpe::sequence::evolve(&parent, &split_additions(&additions), version)?;
            let report = engine.verify(&child)?;
            if !report.ok() {
                return Err(KuteError::Backend(format!("the evolved vocabulary fails its test vectors: {}", report.failures.join("; "))));
            }
            vocab::save(&child, &output, force)?;
            print(&json!({
                "output": output,
                "parent": { "version": parent.version().to_string(), "digest": parent.digest()?, "tokens": parent.len() },
                "summary": vocab::summarize(&child)?,
            }))
        }
        Command::Peer { action } => peer(engine, action),
        Command::Capabilities => {
            let registry = engine.registry();
            let algorithms: Vec<kute::TokenizerCapabilities> =
                registry.algorithm_names().iter().map(|n| registry.tokenizer(n).map(|t| t.capabilities())).collect::<kute::Result<_>>()?;
            let adapters: Vec<serde_json::Value> = registry
                .adapter_names()
                .iter()
                .map(|n| {
                    registry.adapter(n).map(|a| {
                        let c = a.capabilities();
                        json!({ "name": c.name, "modality": c.modality, "lossless": c.lossless, "notes": c.notes })
                    })
                })
                .collect::<kute::Result<_>>()?;
            print(&json!({
                "kute_version": kute::KUTE_VERSION,
                "kvf_version": kute::KVF_VERSION,
                "algorithms": algorithms,
                "adapters": adapters,
            }))
        }
    }
}

/// Parse the command line and run it on `engine`. The `kute` binary passes
/// the default engine; other front ends can register more algorithms first.
pub fn main_with(engine: Engine) -> ExitCode {
    match run(engine, Cli::parse()) {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("kute: {e}");
            ExitCode::FAILURE
        }
    }
}