1pub mod http;
7pub mod live;
8pub mod registry;
9pub mod shadow;
10pub mod sign;
11pub mod mcp;
12
13use clap::{Parser, Subcommand, ValueEnum};
14use kute::{vocab, AdapterConfig, Engine, KuteError, Pretokenizer, TokenSequence, TrainingConfig, Version, VocabularyId};
15use serde_json::json;
16use std::io::Write;
17use std::path::PathBuf;
18use std::process::ExitCode;
19
20#[derive(Parser)]
21#[command(name = "kute", version, about = "Kannaka Universal Tokenization Engine", long_about = None)]
22struct Cli {
23 #[command(subcommand)]
24 command: Command,
25}
26
27#[derive(Subcommand)]
28enum Command {
29 Train(Box<TrainArgs>),
31 Encode {
33 #[arg(long)]
34 vocab: PathBuf,
35 #[arg(long)]
36 input: PathBuf,
37 #[arg(long)]
39 output: Option<PathBuf>,
40 #[arg(long, requires = "output")]
42 compress: bool,
43 #[arg(long, default_value = "strict")]
47 unknown: String,
48 },
49 Decode {
51 #[arg(long)]
52 vocab: PathBuf,
53 #[arg(long)]
54 input: PathBuf,
55 #[arg(long)]
57 output: Option<PathBuf>,
58 #[arg(long)]
61 max_units: Option<u64>,
62 },
63 Inspect {
65 vocab: PathBuf,
66 #[arg(long)]
68 token: Option<u32>,
69 #[arg(long, default_value_t = 0)]
71 longest: usize,
72 },
73 Validate { vocab: PathBuf },
75 Keygen {
78 #[arg(long)]
80 output: PathBuf,
81 },
82 Sign {
84 #[arg(long)]
85 vocab: PathBuf,
86 #[arg(long)]
88 key: PathBuf,
89 #[arg(long)]
90 output: PathBuf,
91 #[arg(long)]
92 force: bool,
93 },
94 Verify {
97 #[arg(long)]
98 vocab: PathBuf,
99 #[arg(long = "trusted-key", value_name = "BASE64", required = true)]
101 trusted_keys: Vec<String>,
102 },
103 Compare { a: PathBuf, b: PathBuf },
105 Convert {
108 #[arg(long)]
109 input: PathBuf,
110 #[arg(long)]
111 output: PathBuf,
112 #[arg(long)]
114 force: bool,
115 },
116 Export {
118 #[arg(long)]
119 vocab: PathBuf,
120 #[arg(long, value_enum, default_value_t = ExportFormat::Tiktoken)]
121 format: ExportFormat,
122 #[arg(long)]
125 output: PathBuf,
126 },
127 Benchmark {
129 #[arg(long, required_unless_present = "suite")]
130 vocab: Option<PathBuf>,
131 #[arg(long, required_unless_present = "suite")]
133 dataset: Option<PathBuf>,
134 #[arg(long, conflicts_with_all = ["vocab", "dataset"])]
136 suite: bool,
137 #[arg(long)]
139 repo_root: Option<PathBuf>,
140 #[arg(long, requires = "suite")]
143 large_text: Option<PathBuf>,
144 #[arg(long, default_value_t = 5)]
145 iterations: usize,
146 #[arg(long)]
148 output: Option<PathBuf>,
149 },
150 Discover(Box<DiscoverArgs>),
152 Evolve {
155 #[arg(long)]
156 vocab: PathBuf,
157 #[arg(long = "add", required = true, value_name = "SYMBOLS")]
159 additions: Vec<String>,
160 #[arg(long)]
162 new_version: String,
163 #[arg(long)]
164 output: PathBuf,
165 #[arg(long)]
166 force: bool,
167 },
168 Peer {
171 #[command(subcommand)]
172 action: PeerAction,
173 },
174 Mcp {
179 #[arg(long)]
181 vocab: Vec<PathBuf>,
182 #[arg(long, default_value_t = 1_048_576)]
184 max_input_bytes: u64,
185 #[arg(long, default_value_t = 4_194_304)]
187 max_output_bytes: u64,
188 },
189 Predict {
193 #[arg(long, required = true, num_args = 1..)]
195 input: Vec<PathBuf>,
196 #[arg(long, value_name = "FIELD")]
198 symbol_field: String,
199 #[arg(long, value_name = "FIELD")]
201 time_field: String,
202 #[arg(long, default_value = "s")]
204 time_unit: String,
205 #[arg(long, value_name = "FIELD")]
207 group_field: Option<String>,
208 #[arg(long, default_value_t = 0.25)]
210 holdout_fraction: f64,
211 #[arg(long, default_value_t = 3)]
213 max_context: usize,
214 #[arg(long, default_value_t = 5)]
216 min_count: u64,
217 #[arg(long, default_value_t = 4)]
219 windows: usize,
220 #[arg(long, default_value_t = 1000)]
222 resamples: usize,
223 #[arg(long, default_value_t = 1)]
224 seed: u64,
225 #[arg(long)]
227 output: Option<PathBuf>,
228 },
229 Shadow {
233 #[arg(long)]
235 parent: PathBuf,
236 #[arg(long)]
238 candidate: PathBuf,
239 #[arg(long, required = true, num_args = 1..)]
241 input: Vec<PathBuf>,
242 #[arg(long, default_value = "escape")]
244 unknown: String,
245 #[arg(long, default_value_t = 0.01)]
247 min_improvement: f64,
248 #[arg(long, default_value_t = 1.0)]
250 horizon: f64,
251 #[arg(long, default_value_t = 1)]
253 distributions: u64,
254 #[arg(long, default_value_t = 2.0)]
256 max_slowdown: f64,
257 #[arg(long, default_value_t = 3)]
259 passes: usize,
260 #[arg(long)]
262 fail_on_reject: bool,
263 },
264 Live {
268 input: Option<PathBuf>,
270 #[arg(long, value_name = "FIELD")]
272 symbol_field: String,
273 #[arg(long, value_name = "FIELD")]
275 time_field: String,
276 #[arg(long, value_name = "FIELD")]
278 group_field: Option<String>,
279 #[arg(long)]
281 pane: i64,
282 #[arg(long, default_value_t = 1)]
284 panes: usize,
285 #[arg(long, default_value_t = 0)]
287 lateness: i64,
288 #[arg(long = "end-on", value_name = "EVENT")]
291 end_on: Vec<String>,
292 #[arg(long, value_name = "TICKS")]
296 idle: Option<i64>,
297 #[arg(long, default_value_t = 100_000)]
299 max_buffered: usize,
300 #[arg(long, default_value_t = 6)]
302 max_length: usize,
303 #[arg(long, default_value_t = 65_536)]
305 max_symbols: usize,
306 #[arg(long, default_value_t = 200_000)]
308 max_candidates: usize,
309 #[arg(long, default_value_t = 100_000)]
311 max_entities: usize,
312 #[arg(long, default_value_t = 5)]
313 min_support: u64,
314 #[arg(long, default_value_t = 1.0)]
315 min_cohesion_bits: f64,
316 #[arg(long, default_value_t = 100)]
318 max_patterns: usize,
319 #[arg(long)]
321 checkpoint: Option<PathBuf>,
322 #[arg(long, default_value_t = 1)]
324 checkpoint_every: u64,
325 #[arg(long)]
327 resume: bool,
328 #[arg(long)]
330 skip_bad_lines: bool,
331 },
332 Events {
335 #[command(subcommand)]
336 action: EventsAction,
337 },
338 Signals {
341 #[command(subcommand)]
342 action: SignalsAction,
343 },
344 Serve {
348 #[arg(long)]
350 vocab: Vec<PathBuf>,
351 #[arg(long, default_value = "127.0.0.1:8787")]
354 listen: String,
355 #[arg(long)]
358 insecure_remote: bool,
359 #[arg(long)]
363 studio: bool,
364 #[arg(long)]
368 registry: bool,
369 #[arg(long, conflicts_with = "studio")]
372 registry_only: bool,
373 #[arg(long, value_name = "URL")]
378 upstream: Vec<String>,
379 #[arg(long, value_name = "KEY")]
384 upstream_trusted_key: Vec<String>,
385 #[arg(long, default_value_t = 10)]
387 upstream_timeout: u64,
388 #[arg(long, default_value_t = 16_777_216)]
390 upstream_max_bytes: u64,
391 #[arg(long, default_value_t = 67_108_864)]
393 upstream_cache_bytes: u64,
394 #[arg(long, default_value_t = 1_048_576)]
396 max_input_bytes: u64,
397 #[arg(long, default_value_t = 4_194_304)]
399 max_output_bytes: u64,
400 #[arg(long, default_value_t = 4)]
402 workers: usize,
403 #[arg(long, default_value_t = 10)]
405 timeout: u64,
406 },
407 Fetch {
413 #[arg(long, required = true)]
417 from: Vec<String>,
418 #[arg(long, required_unless_present = "list", conflicts_with = "list")]
420 digest: Option<String>,
421 #[arg(long, required_unless_present = "list")]
423 output: Option<PathBuf>,
424 #[arg(long = "trusted-key", value_name = "BASE64")]
427 trusted_keys: Vec<String>,
428 #[arg(long)]
430 force: bool,
431 #[arg(long)]
433 list: bool,
434 #[arg(long, default_value_t = 67_108_864)]
438 max_bytes: u64,
439 #[arg(long, default_value_t = 60)]
441 timeout: u64,
442 },
443 Capabilities,
445 SampleData {
447 #[arg(long)]
449 output: PathBuf,
450 },
451}
452
453#[derive(Clone, Copy, ValueEnum)]
454enum ExportFormat {
455 Tiktoken,
456}
457
458#[derive(Subcommand)]
459enum EventsAction {
460 Pack {
462 input: PathBuf,
464 #[arg(long)]
466 output: PathBuf,
467 #[arg(long, value_name = "FIELD")]
469 symbol_field: String,
470 #[arg(long, value_name = "FIELD")]
472 time_field: Option<String>,
473 #[arg(long, value_name = "FIELD")]
475 group_field: Option<String>,
476 #[arg(long)]
481 codec: Option<String>,
482 },
483 Unpack {
485 input: PathBuf,
486 #[arg(long)]
488 output: Option<PathBuf>,
489 #[arg(long, default_value_t = 1 << 32)]
491 max_bytes: u64,
492 },
493 Inspect { input: PathBuf },
495}
496
497#[derive(Subcommand)]
498enum SignalsAction {
499 Pack {
501 input: PathBuf,
504 #[arg(long)]
505 output: PathBuf,
506 #[arg(long, value_name = "ERROR")]
509 max_error: Option<f64>,
510 #[arg(long)]
513 codec: Option<String>,
514 #[arg(long, requires = "delimiter")]
516 column: Option<usize>,
517 #[arg(long, requires = "column")]
519 delimiter: Option<char>,
520 #[arg(long, default_value_t = 0)]
522 skip_lines: usize,
523 },
524 Unpack {
527 input: PathBuf,
528 #[arg(long)]
530 output: Option<PathBuf>,
531 #[arg(long, default_value_t = 1 << 24)]
535 max_values: u64,
536 },
537 Inspect { input: PathBuf },
539}
540
541#[derive(Subcommand)]
542enum PeerAction {
543 Serve {
545 #[arg(long)]
547 listen: String,
548 #[arg(long)]
550 vocab: Vec<PathBuf>,
551 #[arg(long)]
554 accept_vocabularies: bool,
555 #[arg(long)]
557 accept_proposals: bool,
558 #[arg(long, value_name = "PUBLIC_KEY", requires = "accept_vocabularies")]
565 require_signature_from: Vec<String>,
566 #[arg(long)]
568 give_vocabularies: bool,
569 #[arg(long)]
571 answer_queries: bool,
572 #[arg(long)]
574 translate: bool,
575 #[arg(long, default_value_t = 30)]
578 timeout: u64,
579 #[arg(long, conflicts_with = "tls_cert")]
582 insecure_plain: bool,
583 #[arg(long, default_value_t = 268_435_456)]
585 max_units: u64,
586 #[arg(long)]
588 output_dir: Option<PathBuf>,
589 #[arg(long, requires_all = ["tls_key", "tls_client_ca"])]
594 tls_cert: Option<PathBuf>,
595 #[arg(long, requires = "tls_cert")]
597 tls_key: Option<PathBuf>,
598 #[arg(long, requires = "tls_cert")]
600 tls_client_ca: Option<PathBuf>,
601 #[arg(long, value_name = "SHA256", requires = "tls_cert")]
608 allow: Vec<String>,
609 },
610 Send {
612 #[arg(long)]
614 connect: String,
615 #[arg(long)]
616 vocab: PathBuf,
617 #[arg(long, num_args = 0..)]
619 input: Vec<PathBuf>,
620 #[arg(long, default_value = "strict")]
622 unknown: String,
623 #[arg(long = "propose", value_name = "SYMBOLS", requires = "new_version")]
625 additions: Vec<String>,
626 #[arg(long)]
627 new_version: Option<String>,
628 #[arg(long, value_name = "KEY", requires = "new_version")]
632 sign_with: Option<PathBuf>,
633 #[arg(long, requires_all = ["tls_key", "tls_ca"])]
636 tls_cert: Option<PathBuf>,
637 #[arg(long, requires = "tls_cert")]
639 tls_key: Option<PathBuf>,
640 #[arg(long, requires = "tls_cert")]
642 tls_ca: Option<PathBuf>,
643 #[arg(long, requires = "tls_cert")]
646 server_name: Option<String>,
647 #[arg(long, value_name = "SHA256", requires = "tls_cert")]
651 server_fingerprint: Option<String>,
652 #[arg(long, conflicts_with = "tls_cert")]
655 insecure_plain: bool,
656 },
657 Fingerprint {
659 #[arg(long)]
661 cert: PathBuf,
662 },
663}
664
665const NO_TRANSPORT: &str = "give the TLS options (--tls-cert, --tls-key and an authority file), or --insecure-plain for a socket with no encryption and no authentication";
666
667trait Stream: std::io::Read + std::io::Write {}
669impl<T: std::io::Read + std::io::Write> Stream for T {}
670
671fn split_additions(additions: &[String]) -> Vec<Vec<String>> {
672 additions.iter().map(|a| a.split_whitespace().map(str::to_string).collect()).collect()
673}
674
675fn peer(engine: Engine, action: PeerAction) -> kute::Result<()> {
676 use kute_protocol::{tls, Framed, Peer, Policy, Session, DEFAULT_MAX_FRAME};
677 match action {
678 PeerAction::Fingerprint { cert } => {
679 let chain = tls::load_certificates(&cert)?;
680 print(&json!({ "certificate": cert, "fingerprint": tls::fingerprint(&chain[0]) }))
681 }
682 PeerAction::Serve {
683 listen,
684 vocab: held,
685 accept_vocabularies,
686 accept_proposals,
687 require_signature_from,
688 give_vocabularies,
689 answer_queries,
690 translate,
691 timeout,
692 insecure_plain,
693 max_units,
694 output_dir,
695 tls_cert,
696 tls_key,
697 tls_client_ca,
698 allow,
699 } => {
700 let policy = Policy { accept_vocabularies, accept_proposals, give_vocabularies, answer_queries, translate, max_decoded_units: max_units, ..Policy::default() };
701 if tls_cert.is_none() && !insecure_plain {
702 return Err(KuteError::InvalidConfig(NO_TRANSPORT.into()));
703 }
704 let gate = if require_signature_from.is_empty() { None } else { Some(sign::gate(&require_signature_from)?) };
708 let timeout = (timeout > 0).then(|| std::time::Duration::from_secs(timeout));
709 let secured = match (&tls_cert, &tls_key, &tls_client_ca) {
710 (Some(cert), Some(key), Some(ca)) => {
711 if allow.is_empty() {
712 return Err(KuteError::InvalidConfig("with TLS, name at least one peer with --allow; nobody is allowed otherwise".into()));
713 }
714 let mut access = tls::Access::new();
715 for fingerprint in &allow {
716 access.allow(fingerprint, policy.clone())?;
717 }
718 Some((tls::server_config(tls::load_certificates(cert)?, tls::load_private_key(key)?, tls::load_certificates(ca)?)?, access))
719 }
720 _ => None,
721 };
722 let listener = std::net::TcpListener::bind(&listen)?;
723 let _ = writeln!(std::io::stderr(), "listening on {}", listener.local_addr()?);
727 if secured.is_none() {
728 let _ = writeln!(std::io::stderr(), "warning: no TLS. The connection is not encrypted and whoever connects is served.");
729 }
730 let (stream, identity, policy, from): (Box<dyn Stream>, Option<String>, Policy, std::net::SocketAddr) = loop {
735 let (tcp, from) = listener.accept()?;
736 tcp.set_read_timeout(timeout)?;
737 tcp.set_write_timeout(timeout)?;
738 let Some((config, access)) = &secured else { break (Box::new(tcp), None, policy, from) };
739 match tls::accept(config, tcp).and_then(|(stream, who)| Ok((stream, access.policy_for(&who)?, who))) {
740 Ok((stream, policy, who)) => break (Box::new(stream), Some(who.fingerprint), policy, from),
741 Err(e) => {
742 let _ = writeln!(std::io::stderr(), "refused {from}: {e}");
743 }
744 }
745 };
746 let mut peer = Peer::new("kute", engine, policy);
747 if let Some(gate) = gate {
748 peer.require_vocabulary_check(Box::new(gate));
749 }
750 for path in &held {
751 peer.add_vocabulary(vocab::load(path)?)?;
752 }
753 let before = peer.digests();
754 let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
755 let handled = session.serve()?;
756 let inbox = session.peer.take_inbox();
757 let new: Vec<String> = session.peer.digests().into_iter().filter(|d| !before.contains(d)).collect();
758 if let Some(dir) = output_dir.as_ref().filter(|_| !inbox.is_empty() || !new.is_empty()) {
760 std::fs::create_dir_all(dir)?;
761 for message in &inbox {
762 std::fs::write(dir.join(format!("message-{}.bin", message.id)), &message.bytes)?;
763 }
764 for digest in &new {
765 if let Some(v) = session.peer.vocabulary(digest) {
766 let name = format!("{}-{}.kvf", v.id().as_str().replace(':', "_"), v.version());
767 vocab::save(v, dir.join(name), true)?;
768 }
769 }
770 }
771 print(&json!({
772 "from": from.to_string(),
773 "peer_identity": identity,
774 "messages_handled": handled,
775 "vocabularies_received": new,
776 "received": inbox.iter().map(|m| json!({
777 "id": m.id,
778 "bytes": m.bytes.len(),
779 "tokens": m.sequence.ids.len(),
780 "escaped_symbols": m.sequence.escapes.len(),
781 "vocabulary": format!("{} {}", m.sequence.vocabulary_id, m.sequence.vocabulary_version),
782 })).collect::<Vec<_>>(),
783 }))
784 }
785 PeerAction::Send { connect, vocab: vocab_path, input, unknown, additions, new_version, sign_with, tls_cert, tls_key, tls_ca, server_name, server_fingerprint, insecure_plain } => {
786 let signer = sign_with.as_deref().map(sign::signer).transpose()?;
789 if tls_cert.is_none() && !insecure_plain {
790 return Err(KuteError::InvalidConfig(NO_TRANSPORT.into()));
791 }
792 let policy = kute::UnknownPolicy::parse(&unknown)?;
793 let mut peer = Peer::new("kute", engine, Policy::default());
794 let mut digest = peer.add_vocabulary(vocab::load(&vocab_path)?)?;
795 let tcp = std::net::TcpStream::connect(&connect)?;
796 let (stream, server_identity): (Box<dyn Stream>, Option<String>) = match (&tls_cert, &tls_key, &tls_ca) {
797 (Some(cert), Some(key), Some(ca)) => {
798 let config = tls::client_config(tls::load_certificates(cert)?, tls::load_private_key(key)?, tls::load_certificates(ca)?)?;
799 let host = connect.rsplit_once(':').map_or(connect.as_str(), |(host, _)| host);
800 let (stream, who) = tls::connect(&config, server_name.as_deref().unwrap_or(host), tcp)?;
801 if server_fingerprint.as_ref().is_some_and(|wanted| *wanted != who.fingerprint) {
802 return Err(KuteError::Integrity(format!("the server is {}, not the one named by --server-fingerprint", who.fingerprint)));
803 }
804 (Box::new(stream), Some(who.fingerprint))
805 }
806 _ => (Box::new(tcp), None),
807 };
808 let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
809 let remote = session.connect()?;
810 let transferred = session.share(&digest)?;
811 let mut proposed = None;
812 if let Some(version) = &new_version {
813 digest = match &signer {
814 Some(signer) => session.propose_signed(&digest, &split_additions(&additions), version, signer)?,
815 None => session.propose(&digest, &split_additions(&additions), version)?,
816 };
817 proposed = Some(digest.clone());
818 }
819 let mut sent = Vec::new();
820 for path in &input {
821 let raw = std::fs::read(path)?;
822 let units = session.send(&digest, &raw, policy)?;
823 sent.push(json!({ "input": path, "bytes": raw.len(), "units_decoded_by_peer": units, "receipt_matches": true }));
824 }
825 print(&json!({
826 "peer": remote.peer,
827 "peer_software": remote.software,
828 "server_identity": server_identity,
829 "vocabulary_transferred": transferred,
830 "vocabulary_after_proposal": proposed,
831 "proposal_signed": proposed.is_some() && sign_with.is_some(),
832 "sent": sent,
833 }))
834 }
835 }
836}
837
838#[derive(clap::Args)]
839struct DiscoverArgs {
840 #[arg(long, required = true, num_args = 1..)]
842 input: Vec<PathBuf>,
843 #[arg(long, default_value = "jsonl-events")]
845 adapter: String,
846 #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
848 adapter_options: Vec<String>,
849 #[arg(long, conflicts_with_all = ["adapter", "adapter_options"])]
852 lines: bool,
853 #[arg(long, value_name = "FIELD", conflicts_with_all = ["adapter", "adapter_options", "lines"])]
857 symbol_field: Option<String>,
858 #[arg(long, value_name = "FIELD", requires = "symbol_field")]
861 time_field: Option<String>,
862 #[arg(long, default_value = "s", requires = "time_field")]
864 time_unit: String,
865 #[arg(long, value_name = "FIELD", requires = "symbol_field")]
868 group_field: Option<String>,
869 #[arg(long, default_value = "kute:events:unnamed", requires = "symbol_field")]
871 schema_id: String,
872 #[arg(long, num_args = 1.., conflicts_with = "holdout_fraction")]
874 holdout: Vec<PathBuf>,
875 #[arg(long)]
878 holdout_fraction: Option<f64>,
879 #[arg(long, default_value_t = 5)]
880 min_support: u64,
881 #[arg(long, default_value_t = 8)]
883 max_length: usize,
884 #[arg(long, default_value_t = 1.0)]
886 min_cohesion: f64,
887 #[arg(long, default_value_t = 8)]
889 window: usize,
890 #[arg(long, default_value_t = 50)]
892 top: usize,
893 #[arg(long)]
896 control: bool,
897 #[arg(long)]
899 output: Option<PathBuf>,
900}
901
902fn read_records(engine: &Engine, args: &DiscoverArgs, paths: &[PathBuf]) -> kute::Result<Vec<Vec<String>>> {
903 let mut adapter_config = AdapterConfig::default();
904 for option in &args.adapter_options {
905 let (key, value) = option
906 .split_once('=')
907 .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
908 adapter_config = adapter_config.with(key, value);
909 }
910 let mut records = Vec::new();
911 for path in paths {
912 for file in kute::collect_files(path)? {
913 let raw = std::fs::read(&file)?;
914 if args.lines {
915 let text = String::from_utf8(raw).map_err(|_| KuteError::InvalidInput(format!("{}: not UTF-8", file.display())))?;
916 records.extend(text.lines().map(|l| l.split_whitespace().map(str::to_string).collect::<Vec<_>>()).filter(|r| !r.is_empty()));
917 } else {
918 let input = engine.registry().adapter(&args.adapter)?.ingest(&raw, &adapter_config)?;
919 records.extend(kute_discover::records_of(&[input])?);
920 }
921 }
922 }
923 if records.is_empty() {
924 return Err(KuteError::InvalidInput("no records found in the input".into()));
925 }
926 Ok(records)
927}
928
929fn read_events(args: &DiscoverArgs, symbol_field: &str, paths: &[PathBuf]) -> kute::Result<kute::EventStream> {
930 let schema = kute::EventSchema {
931 id: args.schema_id.clone(),
932 version: 1,
933 symbol_field: symbol_field.to_string(),
934 time_unit: args.time_field.as_ref().map(|_| kute::TimeUnit::parse(&args.time_unit)).transpose()?,
935 time_field: args.time_field.clone(),
936 group_field: args.group_field.clone(),
937 };
938 let mut stream = kute::EventStream::new(schema)?;
939 for path in paths {
940 for file in kute::collect_files(path)? {
941 let reader = std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(&file)?);
942 stream.read_jsonl(reader, &file.display().to_string())?;
943 }
944 }
945 if stream.records.is_empty() {
946 return Err(KuteError::InvalidInput("no events found in the input".into()));
947 }
948 Ok(stream)
949}
950
951fn take_symbols(stream: &mut kute::EventStream) -> Vec<Vec<String>> {
953 stream.records.iter_mut().map(|r| std::mem::take(&mut r.symbols)).collect()
954}
955
956fn give_symbols(stream: &mut kute::EventStream, records: Vec<Vec<String>>) {
957 for (r, symbols) in stream.records.iter_mut().zip(records) {
958 r.symbols = symbols;
959 }
960}
961
962fn describe(stream: &kute::EventStream) -> kute::Result<serde_json::Value> {
963 Ok(json!({ "records": stream.records.len(), "events": stream.events(), "fingerprint": stream.fingerprint()? }))
964}
965
966fn discover(engine: &Engine, args: DiscoverArgs) -> kute::Result<()> {
967 use kute_discover as kd;
968 let params = kd::Params {
969 min_support: args.min_support,
970 max_length: args.max_length,
971 min_cohesion_bits: args.min_cohesion,
972 window: args.window,
973 max_patterns: args.top,
974 ..kd::Params::default()
975 };
976 let mut streams: Option<(kute::EventStream, Option<kute::EventStream>)> = match &args.symbol_field {
979 None => None,
980 Some(field) => {
981 let stream = read_events(&args, field, &args.input)?;
982 Some(if !args.holdout.is_empty() {
983 (stream, Some(read_events(&args, field, &args.holdout)?))
984 } else if let Some(fraction) = args.holdout_fraction {
985 let (head, tail) = stream.split_last(fraction)?;
986 (head, Some(tail))
987 } else {
988 (stream, None)
989 })
990 }
991 };
992 let typed = streams.is_some();
993 let mut records = match &mut streams {
994 Some((stream, _)) => take_symbols(stream),
995 None => read_records(engine, &args, &args.input)?,
996 };
997 let mut held_out = match &mut streams {
998 Some((_, held)) => held.as_mut().map(take_symbols),
999 None if args.holdout.is_empty() => None,
1000 None => Some(read_records(engine, &args, &args.holdout)?),
1001 };
1002 if let Some(fraction) = args.holdout_fraction.filter(|_| !typed) {
1003 if args.lines {
1004 if !(fraction > 0.0 && fraction < 1.0) {
1005 return Err(KuteError::InvalidConfig("the held-out fraction must be between 0 and 1".into()));
1006 }
1007 let cut = ((records.len() as f64) * (1.0 - fraction)).round() as usize;
1008 held_out = Some(records.split_off(cut.clamp(1, records.len())));
1009 } else {
1010 let (head, tail) = kd::split_holdout(&records, fraction)?;
1011 records = head;
1012 held_out = Some(tail);
1013 }
1014 }
1015 let start = std::time::Instant::now();
1016 let found = kd::discover(&records, ¶ms)?;
1017 let seconds = start.elapsed().as_secs_f64();
1018 let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
1019 let control = if args.control {
1020 let found = kd::discover(&kd::shuffled(&records, 0), ¶ms)?;
1021 let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
1022 Some(json!({
1023 "what": "the same run on a shuffled copy of the input: same symbol counts, no order",
1024 "patterns": found.patterns.len(),
1025 "strongest_evidence_bits": found.patterns.iter().map(|p| p.evidence_bits).fold(0.0, f64::max),
1026 "coverage": found.coverage,
1027 "held_out_confirmed": evaluation.as_ref().map(|e| e.confirmed),
1028 "held_out_coverage": evaluation.as_ref().map(|e| e.coverage),
1029 }))
1030 } else {
1031 None
1032 };
1033 let events = match streams {
1034 None => None,
1035 Some((mut stream, mut held)) => {
1036 give_symbols(&mut stream, records);
1037 if let (Some(h), Some(symbols)) = (held.as_mut(), held_out) {
1038 give_symbols(h, symbols);
1039 }
1040 let timing = if stream.timed() { Some(kd::timing(&found, &stream)?) } else { None };
1041 let held_timing = match &held {
1042 Some(h) if h.timed() => Some(kd::timing(&found, h)?),
1043 _ => None,
1044 };
1045 Some(json!({
1046 "schema": stream.schema,
1047 "searched": describe(&stream)?,
1048 "held_out": held.as_ref().map(describe).transpose()?,
1049 "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",
1050 "timing": timing,
1051 "held_out_timing": held_timing,
1052 }))
1053 }
1054 };
1055 let report = json!({
1056 "kute_version": kute::KUTE_VERSION,
1057 "discover_seconds": seconds,
1058 "peak_memory_bytes": kute_bench::peak_memory_bytes(),
1059 "discovery": found,
1060 "held_out": evaluation,
1061 "control": control,
1062 "events": events,
1063 });
1064 if let Some(path) = &args.output {
1065 std::fs::write(path, serde_json::to_vec_pretty(&report)?)?;
1066 }
1067 print(&report)
1068}
1069
1070#[derive(clap::Args)]
1071struct TrainArgs {
1072 #[arg(long, required = true, num_args = 1..)]
1074 input: Vec<PathBuf>,
1075 #[arg(long)]
1077 id: String,
1078 #[arg(long, default_value = "0.1.0")]
1080 vocab_version: String,
1081 #[arg(long, default_value = "bpe")]
1082 algorithm: String,
1083 #[arg(long, default_value = "text")]
1084 adapter: String,
1085 #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
1087 adapter_options: Vec<String>,
1088 #[arg(long, default_value_t = 4096)]
1089 vocab_size: u32,
1090 #[arg(long)]
1092 pretokenizer: Option<String>,
1093 #[arg(long, default_value_t = 1)]
1094 min_frequency: u64,
1095 #[arg(long)]
1096 max_token_length: Option<usize>,
1097 #[arg(long = "reserved")]
1099 reserved: Vec<String>,
1100 #[arg(long)]
1102 dictionary_file: Option<PathBuf>,
1103 #[arg(long)]
1104 description: Option<String>,
1105 #[arg(long)]
1107 license: Option<String>,
1108 #[arg(long, value_name = "BYTES")]
1112 stream_bytes: Option<usize>,
1113 #[arg(long, value_name = "VOCAB")]
1118 resume_from: Option<PathBuf>,
1119 #[arg(long, conflicts_with = "no_test_vectors")]
1123 embed_test_vectors: bool,
1124 #[arg(long, hide = true)]
1126 no_test_vectors: bool,
1127 #[arg(long)]
1128 output: PathBuf,
1129 #[arg(long)]
1131 force: bool,
1132}
1133
1134fn print(value: &impl serde::Serialize) -> kute::Result<()> {
1135 let text = serde_json::to_string_pretty(value)?;
1136 let mut out = std::io::stdout().lock();
1137 writeln!(out, "{text}")?;
1138 Ok(())
1139}
1140
1141fn parse_pretokenizer(spec: Option<&str>, adapter: &str) -> kute::Result<Pretokenizer> {
1142 match spec {
1143 None => Ok(if adapter == "text" { Pretokenizer::Gpt4 } else { Pretokenizer::None }),
1144 Some("none") => Ok(Pretokenizer::None),
1145 Some("gpt4") => Ok(Pretokenizer::Gpt4),
1146 Some(s) => match s.strip_prefix("regex:") {
1147 Some(p) if !p.is_empty() => Ok(Pretokenizer::Regex(p.to_string())),
1148 _ => Err(KuteError::InvalidConfig(format!("pretokenizer {s:?}: expected none, gpt4 or regex:<pattern>"))),
1149 },
1150 }
1151}
1152
1153fn train(engine: &Engine, args: TrainArgs) -> kute::Result<()> {
1154 let mut config = TrainingConfig::new(VocabularyId::parse(&args.id)?, args.vocab_size);
1155 config.vocabulary_version = Version::parse(&args.vocab_version)
1156 .map_err(|e| KuteError::InvalidIdentifier(format!("version {:?}: {e}", args.vocab_version)))?;
1157 let symbol_algorithm = args.algorithm == "sequence-bpe";
1158 config.pretokenizer = if symbol_algorithm && args.pretokenizer.is_none() {
1159 Pretokenizer::None
1160 } else {
1161 parse_pretokenizer(args.pretokenizer.as_deref(), &args.adapter)?
1162 };
1163 config.min_frequency = args.min_frequency;
1164 config.max_token_length = args.max_token_length;
1165 config.reserved_tokens = args.reserved;
1166 config.description = args.description;
1167 config.license = args.license;
1168 config.embed_test_vectors = args.embed_test_vectors;
1169 config.stream_bytes = args.stream_bytes;
1170 if let Some(path) = &args.resume_from {
1171 config.resume_from = Some(Box::new(vocab::load(path)?));
1172 }
1173 if let Some(path) = &args.dictionary_file {
1174 let text = std::fs::read_to_string(path)?;
1175 config.dictionary = text.lines().map(|l| l.trim_end_matches('\r')).filter(|l| !l.is_empty()).map(str::to_string).collect();
1176 }
1177 let mut adapter_config = AdapterConfig::default();
1178 for option in &args.adapter_options {
1179 let (key, value) = option
1180 .split_once('=')
1181 .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
1182 adapter_config = adapter_config.with(key, value);
1183 }
1184 let start = std::time::Instant::now();
1185 let vocabulary = engine.train_paths(&args.algorithm, &args.adapter, &adapter_config, &args.input, &config)?;
1186 let seconds = start.elapsed().as_secs_f64();
1187 vocab::save(&vocabulary, &args.output, args.force)?;
1188 eprintln!("trained {} {} in {seconds:.2} s -> {}", vocabulary.id(), vocabulary.version(), args.output.display());
1189 print(&json!({
1190 "output": args.output,
1191 "train_seconds": seconds,
1192 "peak_memory_bytes": kute_bench::peak_memory_bytes(),
1193 "resumed_from": args.resume_from,
1194 "summary": vocab::summarize(&vocabulary)?,
1195 }))
1196}
1197
1198fn run(engine: Engine, cli: Cli) -> kute::Result<()> {
1199 match cli.command {
1200 Command::Train(args) => train(&engine, *args),
1201 Command::Encode { vocab: vocab_path, input, output, compress, unknown } => {
1202 let policy = kute::UnknownPolicy::parse(&unknown)?;
1203 let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
1204 let raw = std::fs::read(&input)?;
1205 let sequence = engine.encode_raw_open(tokenizer.as_ref(), &raw, policy)?;
1206 match output {
1207 Some(path) => {
1208 let bytes = if compress { sequence.to_bytes_compressed()? } else { sequence.to_bytes()? };
1209 std::fs::write(&path, &bytes)?;
1210 print(&json!({
1211 "output": path,
1212 "input_bytes": raw.len(),
1213 "tokens": sequence.ids.len(),
1214 "escaped_symbols": sequence.escapes.len(),
1215 "serialized_bytes": bytes.len(),
1216 "vocabulary": format!("{} {}", sequence.vocabulary_id, sequence.vocabulary_version),
1217 }))
1218 }
1219 None => print(&sequence),
1220 }
1221 }
1222 Command::Decode { vocab: vocab_path, input, output, max_units } => {
1223 let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
1224 let sequence = TokenSequence::from_bytes(&std::fs::read(&input)?)?;
1225 let bytes = engine.decode_raw_bounded(tokenizer.as_ref(), &sequence, max_units.unwrap_or(u64::MAX))?;
1226 match output {
1227 Some(path) => {
1228 std::fs::write(&path, &bytes)?;
1229 print(&json!({ "output": path, "bytes": bytes.len(), "tokens": sequence.ids.len() }))
1230 }
1231 None => {
1232 let mut out = std::io::stdout().lock();
1233 out.write_all(&bytes)?;
1234 out.flush()?;
1235 Ok(())
1236 }
1237 }
1238 }
1239 Command::Inspect { vocab: vocab_path, token, longest } => {
1240 let vocabulary = vocab::load(&vocab_path)?;
1241 if let Some(id) = token {
1242 return print(&vocabulary.record(id)?);
1243 }
1244 let mut report = json!({ "summary": vocab::summarize(&vocabulary)? });
1245 if longest > 0 {
1246 let mut learned: Vec<&kute::TokenEntry> = vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
1247 learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
1248 let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| vocabulary.record(t.id)).collect::<kute::Result<_>>()?;
1249 report["longest_learned_tokens"] = serde_json::to_value(rows)?;
1250 }
1251 print(&report)
1252 }
1253 Command::Keygen { output } => print(&sign::keygen(&output)?),
1254 Command::Sign { vocab: vocab_path, key, output, force } => print(&sign::sign(&vocab_path, &key, &output, force)?),
1255 Command::Verify { vocab: vocab_path, trusted_keys } => {
1256 let (report, verified) = sign::verify(&vocab_path, &trusted_keys)?;
1257 print(&report)?;
1258 if !verified {
1259 return Err(KuteError::Integrity("no trusted key has signed this vocabulary".into()));
1260 }
1261 Ok(())
1262 }
1263 Command::Validate { vocab: vocab_path } => {
1264 let vocabulary = vocab::load(&vocab_path)?;
1265 let report = engine.verify(&vocabulary)?;
1266 print(&report)?;
1267 if report.ok() {
1268 Ok(())
1269 } else {
1270 Err(KuteError::InvalidVocabulary(format!("{} of {} test vectors failed", report.failures.len(), report.vectors)))
1271 }
1272 }
1273 Command::Compare { a, b } => print(&vocab::compare(&vocab::load(&a)?, &vocab::load(&b)?)?),
1274 Command::Convert { input, output, force } => {
1275 let vocabulary = vocab::load(&input)?;
1276 vocab::save(&vocabulary, &output, force)?;
1277 let written = vocab::load(&output)?;
1279 if written != vocabulary {
1280 return Err(KuteError::Integrity("the converted file does not read back as the same vocabulary".into()));
1281 }
1282 let median_ms = |path: &PathBuf| -> kute::Result<f64> {
1283 let bytes = std::fs::read(path)?;
1284 let mut times = Vec::new();
1285 for _ in 0..5 {
1286 let start = std::time::Instant::now();
1287 vocab::from_slice(&bytes)?;
1288 times.push(start.elapsed().as_secs_f64() * 1000.0);
1289 }
1290 times.sort_by(|a, b| a.total_cmp(b));
1291 Ok((times[2] * 1000.0).round() / 1000.0)
1292 };
1293 print(&json!({
1294 "input": { "path": input, "bytes": std::fs::metadata(&input)?.len(), "load_ms_median": median_ms(&input)? },
1295 "output": { "path": output, "bytes": std::fs::metadata(&output)?.len(), "load_ms_median": median_ms(&output)? },
1296 "digest": written.digest()?,
1297 "tokens": written.len(),
1298 "identical": true,
1299 }))
1300 }
1301 Command::Export { vocab: vocab_path, format: ExportFormat::Tiktoken, output } => {
1302 let vocabulary = vocab::load(&vocab_path)?;
1303 let export = vocab::export_tiktoken(&vocabulary)?;
1304 std::fs::write(&output, &export.bpe_file)?;
1305 let mut sidecar = output.clone().into_os_string();
1306 sidecar.push(".json");
1307 let sidecar = PathBuf::from(sidecar);
1308 let meta = json!({
1309 "name": vocabulary.id().as_str().replace(':', "_"),
1310 "pat_str": export.pat_str,
1311 "special_tokens": export.special_tokens,
1312 "explicit_n_vocab": export.n_vocab,
1313 "source_vocabulary": format!("{} {}", vocabulary.id(), vocabulary.version()),
1314 "source_digest": vocabulary.digest()?,
1315 });
1316 std::fs::write(&sidecar, serde_json::to_vec_pretty(&meta)?)?;
1317 print(&json!({ "bpe_file": output, "metadata": sidecar, "tokens": export.n_vocab }))
1318 }
1319 Command::Benchmark { vocab: vocab_path, dataset, suite, repo_root, large_text, iterations, output } => {
1320 let report = if suite {
1321 serde_json::to_value(kute_bench::suite::run(&engine, &kute_bench::suite::Options { repo_root, iterations, large_text })?)?
1322 } else {
1323 let (Some(vocab_path), Some(dataset)) = (vocab_path, dataset) else {
1324 return Err(KuteError::InvalidConfig("benchmark needs --vocab and --dataset, or --suite".into()));
1325 };
1326 let vocabulary = vocab::load(&vocab_path)?;
1327 let documents = kute_bench::read_dataset(&dataset)?;
1328 json!({
1329 "environment": kute_bench::Environment::detect(),
1330 "dataset": dataset,
1331 "evaluation": kute_bench::evaluate(&engine, &vocabulary, &documents, iterations)?,
1332 })
1333 };
1334 if let Some(path) = output {
1335 let mut text = serde_json::to_string_pretty(&report)?;
1336 text.push('\n');
1337 std::fs::write(&path, text)?;
1338 eprintln!("report written to {}", path.display());
1339 }
1340 print(&report)
1341 }
1342 Command::SampleData { output } => {
1343 use kute_bench::data;
1344 std::fs::create_dir_all(&output)?;
1345 let files: Vec<(&str, Vec<u8>, &str)> = vec![
1346 ("alarms-train.jsonl", data::alarm_log(51, 4000), "plant alarm log, 4000 episodes"),
1347 ("alarms-eval.jsonl", data::alarm_log(52, 1000), "plant alarm log, 1000 episodes, different seed"),
1348 ("messages-train.jsonl", data::agent_messages(61, 4000), "agent messages, 4000 records"),
1349 ("messages-eval.jsonl", data::agent_messages(62, 1000), "agent messages, 1000 records, different seed"),
1350 ("frames-train.bin", data::binary_records(31, 6000), "binary telemetry frames, 6000 records"),
1351 ("frames-eval.bin", data::binary_records(32, 2000), "binary telemetry frames, 2000 records, different seed"),
1352 ("words-train.txt", data::invented_words(81, 60_000), "invented-word text, 60000 words"),
1353 ("words-eval.txt", data::invented_words(82, 15_000), "invented-word text, 15000 words, different seed"),
1354 ];
1355 let mut written = Vec::new();
1356 for (name, bytes, what) in files {
1357 std::fs::write(output.join(name), &bytes)?;
1358 written.push(json!({ "file": name, "bytes": bytes.len(), "sha256": kute::sha256_tagged(&bytes), "content": what }));
1359 }
1360 print(&json!({ "output": output, "synthetic": true, "files": written }))
1361 }
1362 Command::Discover(args) => discover(&engine, *args),
1363 Command::Evolve { vocab: vocab_path, additions, new_version, output, force } => {
1364 let version = Version::parse(&new_version).map_err(|e| KuteError::InvalidIdentifier(format!("version {new_version:?}: {e}")))?;
1365 let parent = vocab::load(&vocab_path)?;
1366 let child = kute::bpe::sequence::evolve(&parent, &split_additions(&additions), version)?;
1367 let report = engine.verify(&child)?;
1368 if !report.ok() {
1369 return Err(KuteError::Backend(format!("the evolved vocabulary fails its test vectors: {}", report.failures.join("; "))));
1370 }
1371 vocab::save(&child, &output, force)?;
1372 let mut warnings = Vec::new();
1377 for (limit, bytes) in [(256usize, "one byte"), (65_536, "two bytes")] {
1378 if parent.len() <= limit && child.len() > limit {
1379 warnings.push(format!(
1380 "the vocabulary grew from {} to {} tokens, past {limit}: a token id no longer fits {bytes}, so sequences can come out larger than under the parent even with fewer tokens. Measure on your data before adopting it.",
1381 parent.len(),
1382 child.len()
1383 ));
1384 }
1385 }
1386 for warning in &warnings {
1387 eprintln!("warning: {warning}");
1388 }
1389 print(&json!({
1390 "output": output,
1391 "parent": { "version": parent.version().to_string(), "digest": parent.digest()?, "tokens": parent.len() },
1392 "summary": vocab::summarize(&child)?,
1393 "warnings": warnings,
1394 }))
1395 }
1396 Command::Peer { action } => peer(engine, action),
1397 Command::Mcp { vocab: paths, max_input_bytes, max_output_bytes } => {
1398 let vocabularies = paths.iter().map(vocab::load).collect::<kute::Result<Vec<_>>>()?;
1399 let limits = mcp::Limits { max_input_bytes, max_output_bytes, max_request_bytes: max_input_bytes.saturating_mul(2).saturating_add(1 << 20), ..Default::default() };
1400 let server = mcp::Server::new(engine, vocabularies, limits)?;
1401 server.serve(std::io::stdin().lock(), std::io::stdout().lock())?;
1402 Ok(())
1403 }
1404 Command::Live {
1405 input,
1406 symbol_field,
1407 time_field,
1408 group_field,
1409 pane,
1410 panes,
1411 lateness,
1412 end_on,
1413 idle,
1414 max_buffered,
1415 max_length,
1416 max_symbols,
1417 max_candidates,
1418 max_entities,
1419 min_support,
1420 min_cohesion_bits,
1421 max_patterns,
1422 checkpoint,
1423 checkpoint_every,
1424 resume,
1425 skip_bad_lines,
1426 } => {
1427 let bounds = kute_discover::live::LiveParams { max_length, max_symbols, max_candidates, max_entities, ..Default::default() };
1428 let params = kute_discover::watch::WatchParams { live: bounds, pane_ticks: pane, panes, lateness, max_buffered, min_support, min_cohesion_bits, max_patterns, end_symbols: end_on, idle_ticks: idle };
1429 live::run(live::Options { input, symbol_field, time_field, group_field, params, checkpoint, checkpoint_every, resume, skip_bad_lines })
1430 }
1431 Command::Predict { input, symbol_field, time_field, time_unit, group_field, holdout_fraction, max_context, min_count, windows, resamples, seed, output } => {
1432 let schema = kute::EventSchema {
1433 id: "kute:events:unnamed".into(),
1434 version: 1,
1435 symbol_field,
1436 time_unit: Some(kute::TimeUnit::parse(&time_unit)?),
1437 time_field: Some(time_field),
1438 group_field,
1439 };
1440 let mut stream = kute::EventStream::new(schema)?;
1441 for path in &input {
1442 for file in kute::collect_files(path)? {
1443 let reader = std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(&file)?);
1444 stream.read_jsonl(reader, &file.display().to_string())?;
1445 }
1446 }
1447 let params = kute_discover::predict::PredictParams { holdout_fraction, max_context, min_count, windows, resamples, seed };
1448 let report = kute_discover::predict::evaluate(&stream, ¶ms)?;
1449 if let Some(path) = output {
1450 std::fs::write(&path, serde_json::to_vec_pretty(&report)?)?;
1451 }
1452 print(&report)
1453 }
1454 Command::Shadow { parent, candidate, input, unknown, min_improvement, horizon, distributions, max_slowdown, passes, fail_on_reject } => {
1455 let (report, approved) = shadow::run(&engine, &shadow::Options { parent, candidate, inputs: input, unknown, min_improvement, horizon, distributions, max_slowdown, passes })?;
1456 print(&report)?;
1457 if fail_on_reject && !approved {
1458 return Err(KuteError::Backend("the candidate was rejected".into()));
1459 }
1460 Ok(())
1461 }
1462 Command::Events { action } => match action {
1463 EventsAction::Pack { input, output, symbol_field, time_field, group_field, codec } => {
1464 let layout = kute_events::Layout { symbol_field, time_field, group_field };
1465 let (container, report) = kute_events::pack_with(&std::fs::read(&input)?, &layout, codec.as_deref().map_or(Ok(kute_events::Codec::preferred()), kute_events::Codec::parse)?)?;
1466 std::fs::write(&output, &container)?;
1467 print(&json!({ "output": output, "report": report }))
1468 }
1469 EventsAction::Unpack { input, output, max_bytes } => {
1470 let bytes = kute_events::unpack(&std::fs::read(&input)?, max_bytes)?;
1471 match output {
1472 Some(path) => {
1473 std::fs::write(&path, &bytes)?;
1474 print(&json!({ "output": path, "bytes": bytes.len() }))
1475 }
1476 None => {
1477 let mut out = std::io::stdout().lock();
1478 out.write_all(&bytes)?;
1479 out.flush()?;
1480 Ok(())
1481 }
1482 }
1483 }
1484 EventsAction::Inspect { input } => print(&kute_events::header(&std::fs::read(&input)?)?.0),
1485 },
1486 Command::Signals { action } => match action {
1487 SignalsAction::Pack { input, output, max_error, codec, column, delimiter, skip_lines } => {
1488 let text = std::fs::read_to_string(&input)?;
1489 let mut values = Vec::new();
1490 let mut missing = 0u64;
1491 for (number, line) in text.lines().enumerate().skip(skip_lines) {
1492 let field = match (column, delimiter) {
1493 (Some(column), Some(delimiter)) => line.split(delimiter).nth(column.saturating_sub(1)).ok_or_else(|| KuteError::InvalidInput(format!("line {} has no column {column}", number + 1)))?,
1494 _ => line,
1495 }
1496 .trim();
1497 if field.is_empty() || field == "?" || field.eq_ignore_ascii_case("na") || field.eq_ignore_ascii_case("nan") {
1498 missing += 1;
1499 values.push(f64::NAN);
1500 } else {
1501 values.push(field.parse::<f64>().map_err(|_| KuteError::InvalidInput(format!("line {}: {field:?} is not a number", number + 1)))?);
1502 }
1503 }
1504 let mode = max_error.map_or(kute_signals::Mode::Exact, |max_error| kute_signals::Mode::Bounded { max_error });
1505 let (container, report) = kute_signals::pack_with(&values, mode, codec.as_deref().map_or(Ok(kute_signals::Codec::preferred()), kute_signals::Codec::parse)?)?;
1506 std::fs::write(&output, &container)?;
1507 print(&json!({ "output": output, "input_bytes": text.len(), "missing_values": missing, "report": report }))
1508 }
1509 SignalsAction::Unpack { input, output, max_values } => {
1510 let values = kute_signals::unpack(&std::fs::read(&input)?, max_values)?;
1511 let mut text = String::with_capacity(values.len() * 8);
1512 for value in &values {
1513 let plain = value.to_string();
1517 if plain.len() > 24 {
1518 text.push_str(&format!("{value:e}"));
1519 } else {
1520 text.push_str(&plain);
1521 }
1522 text.push('\n');
1523 }
1524 match output {
1525 Some(path) => {
1526 std::fs::write(&path, &text)?;
1527 print(&json!({ "output": path, "values": values.len() }))
1528 }
1529 None => {
1530 let mut out = std::io::stdout().lock();
1531 out.write_all(text.as_bytes())?;
1532 out.flush()?;
1533 Ok(())
1534 }
1535 }
1536 }
1537 SignalsAction::Inspect { input } => print(&kute_signals::header(&std::fs::read(&input)?)?),
1538 },
1539 Command::Fetch { from, digest, output, trusted_keys, force, list, max_bytes, timeout } => {
1540 let timeout = std::time::Duration::from_secs(timeout.max(1));
1541 match (list, digest, output) {
1542 (true, _, _) => print(®istry::list(&from, timeout)?),
1543 (false, Some(digest), Some(output)) => print(®istry::fetch(&engine, &from, &digest, &output, &trusted_keys, force, max_bytes, timeout)?),
1544 _ => Err(KuteError::InvalidConfig("give --digest and --output, or --list".into())),
1545 }
1546 }
1547 Command::Serve { vocab: paths, listen, insecure_remote, studio, registry, registry_only, upstream, upstream_trusted_key, upstream_timeout, upstream_max_bytes, upstream_cache_bytes, max_input_bytes, max_output_bytes, workers, timeout } => {
1548 let registry = registry || registry_only;
1549 if !upstream.is_empty() && !registry {
1550 return Err(KuteError::InvalidConfig("--upstream is for a registry: add --registry or --registry-only".into()));
1551 }
1552 if upstream.is_empty() && !upstream_trusted_key.is_empty() {
1555 return Err(KuteError::InvalidConfig("--upstream-trusted-key is about files from an --upstream, and none was named".into()));
1556 }
1557 let federation = if upstream.is_empty() {
1558 None
1559 } else {
1560 let check: Option<http::UpstreamCheck> = if upstream_trusted_key.is_empty() { None } else { Some(Box::new(sign::gate(&upstream_trusted_key)?)) };
1561 Some(std::sync::Arc::new(http::Federation::new(upstream.clone(), std::time::Duration::from_secs(upstream_timeout.max(1)), upstream_max_bytes, upstream_cache_bytes, check)?))
1562 };
1563 let vocabularies = paths.iter().map(vocab::load).collect::<kute::Result<Vec<_>>>()?;
1564 let max_body_bytes = max_input_bytes.saturating_mul(2).saturating_add(1 << 20);
1565 let limits = mcp::Limits { max_input_bytes, max_output_bytes, max_request_bytes: max_body_bytes, ..Default::default() };
1566 let server = mcp::Server::new(engine, vocabularies, limits)?;
1567 let listener = std::net::TcpListener::bind(&listen)?;
1568 let address = listener.local_addr()?;
1569 if !http::is_loopback(&address) && !insecure_remote {
1570 return Err(KuteError::InvalidConfig(format!(
1571 "{address} is not a loopback address, and this service has no TLS and no authentication; pass --insecure-remote to serve it anyway"
1572 )));
1573 }
1574 if studio && !http::is_loopback(&address) {
1575 return Err(KuteError::InvalidConfig("Studio is served on a loopback address only: it is a page for the person at this machine".into()));
1576 }
1577 print(&json!({ "listening": address.to_string(), "api": "v1", "loopback_only": http::is_loopback(&address), "studio": studio.then(|| format!("http://{address}/studio")), "registry": registry.then(|| format!("http://{address}")), "upstreams": upstream, "upstream_files_need_a_trusted_signature": !upstream_trusted_key.is_empty(), "operations": !registry_only }))?;
1578 let options = http::Options { workers, timeout: std::time::Duration::from_secs(timeout.max(1)), max_body_bytes, any_host: !http::is_loopback(&address), studio, registry, operations: !registry_only, federation, ..Default::default() };
1579 http::serve(server, listener, options)
1580 }
1581 Command::Capabilities => {
1582 let registry = engine.registry();
1583 let algorithms: Vec<kute::TokenizerCapabilities> =
1584 registry.algorithm_names().iter().map(|n| registry.tokenizer(n).map(|t| t.capabilities())).collect::<kute::Result<_>>()?;
1585 let adapters: Vec<serde_json::Value> = registry
1586 .adapter_names()
1587 .iter()
1588 .map(|n| {
1589 registry.adapter(n).map(|a| {
1590 let c = a.capabilities();
1591 json!({ "name": c.name, "modality": c.modality, "lossless": c.lossless, "notes": c.notes })
1592 })
1593 })
1594 .collect::<kute::Result<_>>()?;
1595 print(&json!({
1596 "kute_version": kute::KUTE_VERSION,
1597 "kvf_version": kute::KVF_VERSION,
1598 "algorithms": algorithms,
1599 "adapters": adapters,
1600 }))
1601 }
1602 }
1603}
1604
1605pub fn main_with(engine: Engine) -> ExitCode {
1608 match run(engine, Cli::parse()) {
1609 Ok(()) => ExitCode::SUCCESS,
1610 Err(e) => {
1611 eprintln!("kute: {e}");
1612 ExitCode::FAILURE
1613 }
1614 }
1615}