1pub mod http;
7pub mod live;
8pub mod peer_status;
9pub mod registry;
10pub mod shadow;
11pub mod sign;
12pub mod mcp;
13
14use clap::{Parser, Subcommand, ValueEnum};
15use kute::{vocab, AdapterConfig, Engine, KuteError, Pretokenizer, TokenSequence, TrainingConfig, Version, VocabularyId};
16use serde_json::json;
17use std::io::Write;
18use std::path::PathBuf;
19use std::process::ExitCode;
20
21#[derive(Parser)]
22#[command(name = "kute", version, about = "Kannaka Universal Tokenization Engine", long_about = None)]
23struct Cli {
24 #[command(subcommand)]
25 command: Command,
26}
27
28#[derive(Subcommand)]
29enum Command {
30 Train(Box<TrainArgs>),
32 Encode {
34 #[arg(long)]
35 vocab: PathBuf,
36 #[arg(long)]
37 input: PathBuf,
38 #[arg(long)]
40 output: Option<PathBuf>,
41 #[arg(long, requires = "output")]
43 compress: bool,
44 #[arg(long, default_value = "strict")]
48 unknown: String,
49 },
50 Decode {
52 #[arg(long)]
53 vocab: PathBuf,
54 #[arg(long)]
55 input: PathBuf,
56 #[arg(long)]
58 output: Option<PathBuf>,
59 #[arg(long)]
62 max_units: Option<u64>,
63 },
64 Inspect {
66 vocab: PathBuf,
67 #[arg(long)]
69 token: Option<u32>,
70 #[arg(long, default_value_t = 0)]
72 longest: usize,
73 },
74 Validate { vocab: PathBuf },
76 Keygen {
79 #[arg(long)]
81 output: PathBuf,
82 },
83 Sign {
85 #[arg(long)]
86 vocab: PathBuf,
87 #[arg(long)]
89 key: PathBuf,
90 #[arg(long)]
91 output: PathBuf,
92 #[arg(long)]
93 force: bool,
94 },
95 Verify {
98 #[arg(long)]
99 vocab: PathBuf,
100 #[arg(long = "trusted-key", value_name = "BASE64", required = true)]
102 trusted_keys: Vec<String>,
103 },
104 Compare { a: PathBuf, b: PathBuf },
106 Convert {
109 #[arg(long)]
110 input: PathBuf,
111 #[arg(long)]
112 output: PathBuf,
113 #[arg(long)]
115 force: bool,
116 },
117 Export {
119 #[arg(long)]
120 vocab: PathBuf,
121 #[arg(long, value_enum, default_value_t = ExportFormat::Tiktoken)]
122 format: ExportFormat,
123 #[arg(long)]
126 output: PathBuf,
127 },
128 Benchmark {
130 #[arg(long, required_unless_present = "suite")]
131 vocab: Option<PathBuf>,
132 #[arg(long, required_unless_present = "suite")]
134 dataset: Option<PathBuf>,
135 #[arg(long, conflicts_with_all = ["vocab", "dataset"])]
137 suite: bool,
138 #[arg(long)]
140 repo_root: Option<PathBuf>,
141 #[arg(long, requires = "suite")]
144 large_text: Option<PathBuf>,
145 #[arg(long, default_value_t = 5)]
146 iterations: usize,
147 #[arg(long)]
149 output: Option<PathBuf>,
150 },
151 Discover(Box<DiscoverArgs>),
153 Evolve {
156 #[arg(long)]
157 vocab: PathBuf,
158 #[arg(long = "add", required = true, value_name = "SYMBOLS")]
160 additions: Vec<String>,
161 #[arg(long)]
163 new_version: String,
164 #[arg(long)]
165 output: PathBuf,
166 #[arg(long)]
167 force: bool,
168 },
169 Peer {
172 #[command(subcommand)]
173 action: PeerAction,
174 },
175 Mcp {
180 #[arg(long)]
182 vocab: Vec<PathBuf>,
183 #[arg(long, default_value_t = 1_048_576)]
185 max_input_bytes: u64,
186 #[arg(long, default_value_t = 4_194_304)]
188 max_output_bytes: u64,
189 },
190 Predict {
194 #[arg(long, required = true, num_args = 1..)]
196 input: Vec<PathBuf>,
197 #[arg(long, value_name = "FIELD")]
199 symbol_field: String,
200 #[arg(long, value_name = "FIELD")]
202 time_field: String,
203 #[arg(long, default_value = "s")]
205 time_unit: String,
206 #[arg(long, value_name = "FIELD")]
208 group_field: Option<String>,
209 #[arg(long, default_value_t = 0.25)]
211 holdout_fraction: f64,
212 #[arg(long, default_value_t = 3)]
214 max_context: usize,
215 #[arg(long, default_value_t = 5)]
217 min_count: u64,
218 #[arg(long, default_value_t = 4)]
220 windows: usize,
221 #[arg(long, default_value_t = 1000)]
223 resamples: usize,
224 #[arg(long, default_value_t = 1)]
225 seed: u64,
226 #[arg(long)]
228 output: Option<PathBuf>,
229 },
230 Shadow {
234 #[arg(long)]
236 parent: PathBuf,
237 #[arg(long)]
239 candidate: PathBuf,
240 #[arg(long, required = true, num_args = 1..)]
242 input: Vec<PathBuf>,
243 #[arg(long, default_value = "escape")]
245 unknown: String,
246 #[arg(long, default_value_t = 0.01)]
248 min_improvement: f64,
249 #[arg(long, default_value_t = 1.0)]
251 horizon: f64,
252 #[arg(long, default_value_t = 1)]
254 distributions: u64,
255 #[arg(long, default_value_t = 2.0)]
257 max_slowdown: f64,
258 #[arg(long, default_value_t = 3)]
260 passes: usize,
261 #[arg(long)]
263 fail_on_reject: bool,
264 },
265 Live {
269 input: Option<PathBuf>,
271 #[arg(long, value_name = "FIELD")]
273 symbol_field: String,
274 #[arg(long, value_name = "FIELD")]
276 time_field: String,
277 #[arg(long, value_name = "FIELD")]
279 group_field: Option<String>,
280 #[arg(long)]
282 pane: i64,
283 #[arg(long, default_value_t = 1)]
285 panes: usize,
286 #[arg(long, default_value_t = 0)]
288 lateness: i64,
289 #[arg(long = "end-on", value_name = "EVENT")]
292 end_on: Vec<String>,
293 #[arg(long, value_name = "TICKS")]
297 idle: Option<i64>,
298 #[arg(long, default_value_t = 100_000)]
300 max_buffered: usize,
301 #[arg(long, default_value_t = 6)]
303 max_length: usize,
304 #[arg(long, default_value_t = 65_536)]
306 max_symbols: usize,
307 #[arg(long, default_value_t = 200_000)]
309 max_candidates: usize,
310 #[arg(long, default_value_t = 100_000)]
312 max_entities: usize,
313 #[arg(long, default_value_t = 5)]
314 min_support: u64,
315 #[arg(long, default_value_t = 1.0)]
316 min_cohesion_bits: f64,
317 #[arg(long, default_value_t = 100)]
319 max_patterns: usize,
320 #[arg(long)]
322 checkpoint: Option<PathBuf>,
323 #[arg(long, default_value_t = 1)]
325 checkpoint_every: u64,
326 #[arg(long)]
328 resume: bool,
329 #[arg(long)]
331 skip_bad_lines: bool,
332 },
333 Events {
336 #[command(subcommand)]
337 action: EventsAction,
338 },
339 Signals {
342 #[command(subcommand)]
343 action: SignalsAction,
344 },
345 Serve {
349 #[arg(long)]
351 vocab: Vec<PathBuf>,
352 #[arg(long, default_value = "127.0.0.1:8787")]
355 listen: String,
356 #[arg(long)]
359 insecure_remote: bool,
360 #[arg(long)]
364 studio: bool,
365 #[arg(long)]
369 registry: bool,
370 #[arg(long, conflicts_with = "studio")]
373 registry_only: bool,
374 #[arg(long, value_name = "FILE", conflicts_with = "registry_only")]
379 peer_status: Option<PathBuf>,
380 #[arg(long, value_name = "URL")]
385 upstream: Vec<String>,
386 #[arg(long, value_name = "KEY")]
391 upstream_trusted_key: Vec<String>,
392 #[arg(long, default_value_t = 10)]
394 upstream_timeout: u64,
395 #[arg(long, default_value_t = 16_777_216)]
397 upstream_max_bytes: u64,
398 #[arg(long, default_value_t = 67_108_864)]
400 upstream_cache_bytes: u64,
401 #[arg(long, default_value_t = 1_048_576)]
403 max_input_bytes: u64,
404 #[arg(long, default_value_t = 4_194_304)]
406 max_output_bytes: u64,
407 #[arg(long, default_value_t = 4)]
409 workers: usize,
410 #[arg(long, default_value_t = 10)]
412 timeout: u64,
413 },
414 Fetch {
420 #[arg(long, required = true)]
424 from: Vec<String>,
425 #[arg(long, required_unless_present = "list", conflicts_with = "list")]
427 digest: Option<String>,
428 #[arg(long, required_unless_present = "list")]
430 output: Option<PathBuf>,
431 #[arg(long = "trusted-key", value_name = "BASE64")]
434 trusted_keys: Vec<String>,
435 #[arg(long)]
437 force: bool,
438 #[arg(long)]
440 list: bool,
441 #[arg(long, default_value_t = 67_108_864)]
445 max_bytes: u64,
446 #[arg(long, default_value_t = 60)]
448 timeout: u64,
449 },
450 Capabilities,
452 SampleData {
454 #[arg(long)]
456 output: PathBuf,
457 },
458}
459
460#[derive(Clone, Copy, ValueEnum)]
461enum ExportFormat {
462 Tiktoken,
463}
464
465#[derive(Subcommand)]
466enum EventsAction {
467 Pack {
469 input: PathBuf,
471 #[arg(long)]
473 output: PathBuf,
474 #[arg(long, value_name = "FIELD")]
476 symbol_field: String,
477 #[arg(long, value_name = "FIELD")]
479 time_field: Option<String>,
480 #[arg(long, value_name = "FIELD")]
482 group_field: Option<String>,
483 #[arg(long)]
488 codec: Option<String>,
489 },
490 Unpack {
492 input: PathBuf,
493 #[arg(long)]
495 output: Option<PathBuf>,
496 #[arg(long, default_value_t = 1 << 32)]
498 max_bytes: u64,
499 },
500 Inspect { input: PathBuf },
502}
503
504#[derive(Subcommand)]
505enum SignalsAction {
506 Pack {
508 input: PathBuf,
511 #[arg(long)]
512 output: PathBuf,
513 #[arg(long, value_name = "ERROR")]
516 max_error: Option<f64>,
517 #[arg(long)]
520 codec: Option<String>,
521 #[arg(long, requires = "delimiter")]
523 column: Option<usize>,
524 #[arg(long, requires = "column")]
526 delimiter: Option<char>,
527 #[arg(long, default_value_t = 0)]
529 skip_lines: usize,
530 },
531 Unpack {
534 input: PathBuf,
535 #[arg(long)]
537 output: Option<PathBuf>,
538 #[arg(long, default_value_t = 1 << 24)]
542 max_values: u64,
543 },
544 Inspect { input: PathBuf },
546}
547
548#[derive(Subcommand)]
549enum PeerAction {
550 Serve {
552 #[arg(long)]
554 listen: String,
555 #[arg(long)]
557 vocab: Vec<PathBuf>,
558 #[arg(long)]
561 accept_vocabularies: bool,
562 #[arg(long)]
564 accept_proposals: bool,
565 #[arg(long, value_name = "PUBLIC_KEY", requires = "accept_vocabularies")]
572 require_signature_from: Vec<String>,
573 #[arg(long)]
575 give_vocabularies: bool,
576 #[arg(long)]
578 answer_queries: bool,
579 #[arg(long)]
581 translate: bool,
582 #[arg(long, default_value_t = 30)]
585 timeout: u64,
586 #[arg(long, conflicts_with = "tls_cert")]
589 insecure_plain: bool,
590 #[arg(long, default_value_t = 268_435_456)]
592 max_units: u64,
593 #[arg(long)]
595 output_dir: Option<PathBuf>,
596 #[arg(long, value_name = "FILE")]
602 status_file: Option<PathBuf>,
603 #[arg(long, requires_all = ["tls_key", "tls_client_ca"])]
608 tls_cert: Option<PathBuf>,
609 #[arg(long, requires = "tls_cert")]
611 tls_key: Option<PathBuf>,
612 #[arg(long, requires = "tls_cert")]
614 tls_client_ca: Option<PathBuf>,
615 #[arg(long, value_name = "SHA256", requires = "tls_cert")]
622 allow: Vec<String>,
623 },
624 Send {
626 #[arg(long)]
628 connect: String,
629 #[arg(long)]
630 vocab: PathBuf,
631 #[arg(long, num_args = 0..)]
633 input: Vec<PathBuf>,
634 #[arg(long, default_value = "strict")]
636 unknown: String,
637 #[arg(long = "propose", value_name = "SYMBOLS", requires = "new_version")]
639 additions: Vec<String>,
640 #[arg(long)]
641 new_version: Option<String>,
642 #[arg(long, value_name = "KEY", requires = "new_version")]
646 sign_with: Option<PathBuf>,
647 #[arg(long, requires_all = ["tls_key", "tls_ca"])]
650 tls_cert: Option<PathBuf>,
651 #[arg(long, requires = "tls_cert")]
653 tls_key: Option<PathBuf>,
654 #[arg(long, requires = "tls_cert")]
656 tls_ca: Option<PathBuf>,
657 #[arg(long, requires = "tls_cert")]
660 server_name: Option<String>,
661 #[arg(long, value_name = "SHA256", requires = "tls_cert")]
665 server_fingerprint: Option<String>,
666 #[arg(long, conflicts_with = "tls_cert")]
669 insecure_plain: bool,
670 },
671 Fingerprint {
673 #[arg(long)]
675 cert: PathBuf,
676 },
677}
678
679const 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";
680
681trait Stream: std::io::Read + std::io::Write {}
683impl<T: std::io::Read + std::io::Write> Stream for T {}
684
685fn split_additions(additions: &[String]) -> Vec<Vec<String>> {
686 additions.iter().map(|a| a.split_whitespace().map(str::to_string).collect()).collect()
687}
688
689fn peer(engine: Engine, action: PeerAction) -> kute::Result<()> {
690 use kute_protocol::{tls, Framed, Peer, Policy, Session, DEFAULT_MAX_FRAME};
691 match action {
692 PeerAction::Fingerprint { cert } => {
693 let chain = tls::load_certificates(&cert)?;
694 print(&json!({ "certificate": cert, "fingerprint": tls::fingerprint(&chain[0]) }))
695 }
696 PeerAction::Serve {
697 listen,
698 vocab: held,
699 accept_vocabularies,
700 accept_proposals,
701 require_signature_from,
702 give_vocabularies,
703 answer_queries,
704 translate,
705 timeout,
706 insecure_plain,
707 max_units,
708 output_dir,
709 status_file,
710 tls_cert,
711 tls_key,
712 tls_client_ca,
713 allow,
714 } => {
715 let policy = Policy { accept_vocabularies, accept_proposals, give_vocabularies, answer_queries, translate, max_decoded_units: max_units, ..Policy::default() };
716 if tls_cert.is_none() && !insecure_plain {
717 return Err(KuteError::InvalidConfig(NO_TRANSPORT.into()));
718 }
719 let gate = if require_signature_from.is_empty() { None } else { Some(sign::gate(&require_signature_from)?) };
723 let timeout = (timeout > 0).then(|| std::time::Duration::from_secs(timeout));
724 let secured = match (&tls_cert, &tls_key, &tls_client_ca) {
725 (Some(cert), Some(key), Some(ca)) => {
726 if allow.is_empty() {
727 return Err(KuteError::InvalidConfig("with TLS, name at least one peer with --allow; nobody is allowed otherwise".into()));
728 }
729 let mut access = tls::Access::new();
730 for fingerprint in &allow {
731 access.allow(fingerprint, policy.clone())?;
732 }
733 Some((tls::server_config(tls::load_certificates(cert)?, tls::load_private_key(key)?, tls::load_certificates(ca)?)?, access))
734 }
735 _ => None,
736 };
737 let listener = std::net::TcpListener::bind(&listen)?;
738 let _ = writeln!(std::io::stderr(), "listening on {}", listener.local_addr()?);
742 if let Some(path) = &status_file {
743 peer_status::start(
744 path,
745 json!({
746 "software": format!("kute {}", kute::KUTE_VERSION),
747 "process": std::process::id(),
748 "listening": listener.local_addr()?.to_string(),
749 "transport": if secured.is_some() { "TLS 1.3, a certificate on both sides" } else { "plain: not encrypted, and whoever connects is served" },
750 "certificates_allowed": allow.len(),
751 "takes": { "vocabularies": accept_vocabularies, "proposals": accept_proposals, "only_signed_by_a_trusted_key": !require_signature_from.is_empty() },
752 "gives": { "vocabularies": give_vocabularies, "answers_to_queries": answer_queries, "translations": translate },
753 "vocabulary_files_given_at_start": held.len(),
754 "quiet_connection_dropped_after_seconds": timeout.map(|t| t.as_secs()),
755 "state": peer_status::WAITING,
756 "connections_refused": 0,
757 "last_refusal": null,
758 "exchange": null,
759 "ended": null,
760 }),
761 )?;
762 }
763 if secured.is_none() {
764 let _ = writeln!(std::io::stderr(), "warning: no TLS. The connection is not encrypted and whoever connects is served.");
765 }
766 let (stream, identity, policy, from): (Box<dyn Stream>, Option<String>, Policy, std::net::SocketAddr) = loop {
771 let (tcp, from) = listener.accept()?;
772 tcp.set_read_timeout(timeout)?;
773 tcp.set_write_timeout(timeout)?;
774 let Some((config, access)) = &secured else { break (Box::new(tcp), None, policy, from) };
775 match tls::accept(config, tcp).and_then(|(stream, who)| Ok((stream, access.policy_for(&who)?, who))) {
776 Ok((stream, policy, who)) => break (Box::new(stream), Some(who.fingerprint), policy, from),
777 Err(e) => {
778 let _ = writeln!(std::io::stderr(), "refused {from}: {e}");
779 peer_status::enter(peer_status::WAITING, |status| {
780 status["connections_refused"] = json!(status["connections_refused"].as_u64().unwrap_or(0) + 1);
781 status["last_refusal"] = json!({ "from": from.to_string(), "why": e.to_string(), "at": peer_status::now() });
782 });
783 }
784 }
785 };
786 let mut peer = Peer::new("kute", engine, policy);
787 if let Some(gate) = gate {
788 peer.require_vocabulary_check(Box::new(gate));
789 }
790 for path in &held {
791 peer.add_vocabulary(vocab::load(path)?)?;
792 }
793 let before = peer.digests();
794 peer_status::enter(peer_status::EXCHANGE, |status| {
795 status["exchange"] = json!({ "from": from.to_string(), "peer_identity": identity, "messages_handled": 0, "delivered": 0, "vocabularies_held": before.len() });
796 });
797 let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
798 let handled = session.serve_observed(&mut |peer, handled| {
799 peer_status::set(|status| {
800 status["exchange"]["messages_handled"] = json!(handled);
801 status["exchange"]["delivered"] = json!(peer.inbox_len());
802 status["exchange"]["vocabularies_held"] = json!(peer.digests().len());
803 });
804 })?;
805 let inbox = session.peer.take_inbox();
806 let new: Vec<String> = session.peer.digests().into_iter().filter(|d| !before.contains(d)).collect();
807 if let Some(dir) = output_dir.as_ref().filter(|_| !inbox.is_empty() || !new.is_empty()) {
809 std::fs::create_dir_all(dir)?;
810 for message in &inbox {
811 std::fs::write(dir.join(format!("message-{}.bin", message.id)), &message.bytes)?;
812 }
813 for digest in &new {
814 if let Some(v) = session.peer.vocabulary(digest) {
815 let name = format!("{}-{}.kvf", v.id().as_str().replace(':', "_"), v.version());
816 vocab::save(v, dir.join(name), true)?;
817 }
818 }
819 }
820 peer_status::set(|status| {
821 status["exchange"]["messages_handled"] = json!(handled);
822 status["exchange"]["delivered"] = json!(inbox.len());
823 status["exchange"]["vocabularies_received_count"] = json!(new.len());
826 status["exchange"]["vocabularies_received"] = json!(new.iter().take(100).collect::<Vec<_>>());
827 });
828 print(&json!({
829 "from": from.to_string(),
830 "peer_identity": identity,
831 "messages_handled": handled,
832 "vocabularies_received": new,
833 "received": inbox.iter().map(|m| json!({
834 "id": m.id,
835 "bytes": m.bytes.len(),
836 "tokens": m.sequence.ids.len(),
837 "escaped_symbols": m.sequence.escapes.len(),
838 "vocabulary": format!("{} {}", m.sequence.vocabulary_id, m.sequence.vocabulary_version),
839 })).collect::<Vec<_>>(),
840 }))
841 }
842 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 } => {
843 let signer = sign_with.as_deref().map(sign::signer).transpose()?;
846 if tls_cert.is_none() && !insecure_plain {
847 return Err(KuteError::InvalidConfig(NO_TRANSPORT.into()));
848 }
849 let policy = kute::UnknownPolicy::parse(&unknown)?;
850 let mut peer = Peer::new("kute", engine, Policy::default());
851 let mut digest = peer.add_vocabulary(vocab::load(&vocab_path)?)?;
852 let tcp = std::net::TcpStream::connect(&connect)?;
853 let (stream, server_identity): (Box<dyn Stream>, Option<String>) = match (&tls_cert, &tls_key, &tls_ca) {
854 (Some(cert), Some(key), Some(ca)) => {
855 let config = tls::client_config(tls::load_certificates(cert)?, tls::load_private_key(key)?, tls::load_certificates(ca)?)?;
856 let host = connect.rsplit_once(':').map_or(connect.as_str(), |(host, _)| host);
857 let (stream, who) = tls::connect(&config, server_name.as_deref().unwrap_or(host), tcp)?;
858 if server_fingerprint.as_ref().is_some_and(|wanted| *wanted != who.fingerprint) {
859 return Err(KuteError::Integrity(format!("the server is {}, not the one named by --server-fingerprint", who.fingerprint)));
860 }
861 (Box::new(stream), Some(who.fingerprint))
862 }
863 _ => (Box::new(tcp), None),
864 };
865 let mut session = Session::new(peer, Framed::new(stream, DEFAULT_MAX_FRAME));
866 let remote = session.connect()?;
867 let transferred = session.share(&digest)?;
868 let mut proposed = None;
869 if let Some(version) = &new_version {
870 digest = match &signer {
871 Some(signer) => session.propose_signed(&digest, &split_additions(&additions), version, signer)?,
872 None => session.propose(&digest, &split_additions(&additions), version)?,
873 };
874 proposed = Some(digest.clone());
875 }
876 let mut sent = Vec::new();
877 for path in &input {
878 let raw = std::fs::read(path)?;
879 let units = session.send(&digest, &raw, policy)?;
880 sent.push(json!({ "input": path, "bytes": raw.len(), "units_decoded_by_peer": units, "receipt_matches": true }));
881 }
882 print(&json!({
883 "peer": remote.peer,
884 "peer_software": remote.software,
885 "server_identity": server_identity,
886 "vocabulary_transferred": transferred,
887 "vocabulary_after_proposal": proposed,
888 "proposal_signed": proposed.is_some() && sign_with.is_some(),
889 "sent": sent,
890 }))
891 }
892 }
893}
894
895#[derive(clap::Args)]
896struct DiscoverArgs {
897 #[arg(long, required = true, num_args = 1..)]
899 input: Vec<PathBuf>,
900 #[arg(long, default_value = "jsonl-events")]
902 adapter: String,
903 #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
905 adapter_options: Vec<String>,
906 #[arg(long, conflicts_with_all = ["adapter", "adapter_options"])]
909 lines: bool,
910 #[arg(long, value_name = "FIELD", conflicts_with_all = ["adapter", "adapter_options", "lines"])]
914 symbol_field: Option<String>,
915 #[arg(long, value_name = "FIELD", requires = "symbol_field")]
918 time_field: Option<String>,
919 #[arg(long, default_value = "s", requires = "time_field")]
921 time_unit: String,
922 #[arg(long, value_name = "FIELD", requires = "symbol_field")]
925 group_field: Option<String>,
926 #[arg(long, default_value = "kute:events:unnamed", requires = "symbol_field")]
928 schema_id: String,
929 #[arg(long, num_args = 1.., conflicts_with = "holdout_fraction")]
931 holdout: Vec<PathBuf>,
932 #[arg(long)]
935 holdout_fraction: Option<f64>,
936 #[arg(long, default_value_t = 5)]
937 min_support: u64,
938 #[arg(long, default_value_t = 8)]
940 max_length: usize,
941 #[arg(long, default_value_t = 1.0)]
943 min_cohesion: f64,
944 #[arg(long, default_value_t = 8)]
946 window: usize,
947 #[arg(long, default_value_t = 50)]
949 top: usize,
950 #[arg(long)]
953 control: bool,
954 #[arg(long)]
956 output: Option<PathBuf>,
957}
958
959fn read_records(engine: &Engine, args: &DiscoverArgs, paths: &[PathBuf]) -> kute::Result<Vec<Vec<String>>> {
960 let mut adapter_config = AdapterConfig::default();
961 for option in &args.adapter_options {
962 let (key, value) = option
963 .split_once('=')
964 .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
965 adapter_config = adapter_config.with(key, value);
966 }
967 let mut records = Vec::new();
968 for path in paths {
969 for file in kute::collect_files(path)? {
970 let raw = std::fs::read(&file)?;
971 if args.lines {
972 let text = String::from_utf8(raw).map_err(|_| KuteError::InvalidInput(format!("{}: not UTF-8", file.display())))?;
973 records.extend(text.lines().map(|l| l.split_whitespace().map(str::to_string).collect::<Vec<_>>()).filter(|r| !r.is_empty()));
974 } else {
975 let input = engine.registry().adapter(&args.adapter)?.ingest(&raw, &adapter_config)?;
976 records.extend(kute_discover::records_of(&[input])?);
977 }
978 }
979 }
980 if records.is_empty() {
981 return Err(KuteError::InvalidInput("no records found in the input".into()));
982 }
983 Ok(records)
984}
985
986fn read_events(args: &DiscoverArgs, symbol_field: &str, paths: &[PathBuf]) -> kute::Result<kute::EventStream> {
987 let schema = kute::EventSchema {
988 id: args.schema_id.clone(),
989 version: 1,
990 symbol_field: symbol_field.to_string(),
991 time_unit: args.time_field.as_ref().map(|_| kute::TimeUnit::parse(&args.time_unit)).transpose()?,
992 time_field: args.time_field.clone(),
993 group_field: args.group_field.clone(),
994 };
995 let mut stream = kute::EventStream::new(schema)?;
996 for path in paths {
997 for file in kute::collect_files(path)? {
998 let reader = std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(&file)?);
999 stream.read_jsonl(reader, &file.display().to_string())?;
1000 }
1001 }
1002 if stream.records.is_empty() {
1003 return Err(KuteError::InvalidInput("no events found in the input".into()));
1004 }
1005 Ok(stream)
1006}
1007
1008fn take_symbols(stream: &mut kute::EventStream) -> Vec<Vec<String>> {
1010 stream.records.iter_mut().map(|r| std::mem::take(&mut r.symbols)).collect()
1011}
1012
1013fn give_symbols(stream: &mut kute::EventStream, records: Vec<Vec<String>>) {
1014 for (r, symbols) in stream.records.iter_mut().zip(records) {
1015 r.symbols = symbols;
1016 }
1017}
1018
1019fn describe(stream: &kute::EventStream) -> kute::Result<serde_json::Value> {
1020 Ok(json!({ "records": stream.records.len(), "events": stream.events(), "fingerprint": stream.fingerprint()? }))
1021}
1022
1023fn discover(engine: &Engine, args: DiscoverArgs) -> kute::Result<()> {
1024 use kute_discover as kd;
1025 let params = kd::Params {
1026 min_support: args.min_support,
1027 max_length: args.max_length,
1028 min_cohesion_bits: args.min_cohesion,
1029 window: args.window,
1030 max_patterns: args.top,
1031 ..kd::Params::default()
1032 };
1033 let mut streams: Option<(kute::EventStream, Option<kute::EventStream>)> = match &args.symbol_field {
1036 None => None,
1037 Some(field) => {
1038 let stream = read_events(&args, field, &args.input)?;
1039 Some(if !args.holdout.is_empty() {
1040 (stream, Some(read_events(&args, field, &args.holdout)?))
1041 } else if let Some(fraction) = args.holdout_fraction {
1042 let (head, tail) = stream.split_last(fraction)?;
1043 (head, Some(tail))
1044 } else {
1045 (stream, None)
1046 })
1047 }
1048 };
1049 let typed = streams.is_some();
1050 let mut records = match &mut streams {
1051 Some((stream, _)) => take_symbols(stream),
1052 None => read_records(engine, &args, &args.input)?,
1053 };
1054 let mut held_out = match &mut streams {
1055 Some((_, held)) => held.as_mut().map(take_symbols),
1056 None if args.holdout.is_empty() => None,
1057 None => Some(read_records(engine, &args, &args.holdout)?),
1058 };
1059 if let Some(fraction) = args.holdout_fraction.filter(|_| !typed) {
1060 if args.lines {
1061 if !(fraction > 0.0 && fraction < 1.0) {
1062 return Err(KuteError::InvalidConfig("the held-out fraction must be between 0 and 1".into()));
1063 }
1064 let cut = ((records.len() as f64) * (1.0 - fraction)).round() as usize;
1065 held_out = Some(records.split_off(cut.clamp(1, records.len())));
1066 } else {
1067 let (head, tail) = kd::split_holdout(&records, fraction)?;
1068 records = head;
1069 held_out = Some(tail);
1070 }
1071 }
1072 let start = std::time::Instant::now();
1073 let found = kd::discover(&records, ¶ms)?;
1074 let seconds = start.elapsed().as_secs_f64();
1075 let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
1076 let control = if args.control {
1077 let found = kd::discover(&kd::shuffled(&records, 0), ¶ms)?;
1078 let evaluation = held_out.as_ref().map(|h| kd::evaluate(&found, h)).transpose()?;
1079 Some(json!({
1080 "what": "the same run on a shuffled copy of the input: same symbol counts, no order",
1081 "patterns": found.patterns.len(),
1082 "strongest_evidence_bits": found.patterns.iter().map(|p| p.evidence_bits).fold(0.0, f64::max),
1083 "coverage": found.coverage,
1084 "held_out_confirmed": evaluation.as_ref().map(|e| e.confirmed),
1085 "held_out_coverage": evaluation.as_ref().map(|e| e.coverage),
1086 }))
1087 } else {
1088 None
1089 };
1090 let events = match streams {
1091 None => None,
1092 Some((mut stream, mut held)) => {
1093 give_symbols(&mut stream, records);
1094 if let (Some(h), Some(symbols)) = (held.as_mut(), held_out) {
1095 give_symbols(h, symbols);
1096 }
1097 let timing = if stream.timed() { Some(kd::timing(&found, &stream)?) } else { None };
1098 let held_timing = match &held {
1099 Some(h) if h.timed() => Some(kd::timing(&found, h)?),
1100 _ => None,
1101 };
1102 Some(json!({
1103 "schema": stream.schema,
1104 "searched": describe(&stream)?,
1105 "held_out": held.as_ref().map(describe).transpose()?,
1106 "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",
1107 "timing": timing,
1108 "held_out_timing": held_timing,
1109 }))
1110 }
1111 };
1112 let report = json!({
1113 "kute_version": kute::KUTE_VERSION,
1114 "discover_seconds": seconds,
1115 "peak_memory_bytes": kute_bench::peak_memory_bytes(),
1116 "discovery": found,
1117 "held_out": evaluation,
1118 "control": control,
1119 "events": events,
1120 });
1121 if let Some(path) = &args.output {
1122 std::fs::write(path, serde_json::to_vec_pretty(&report)?)?;
1123 }
1124 print(&report)
1125}
1126
1127#[derive(clap::Args)]
1128struct TrainArgs {
1129 #[arg(long, required = true, num_args = 1..)]
1131 input: Vec<PathBuf>,
1132 #[arg(long)]
1134 id: String,
1135 #[arg(long, default_value = "0.1.0")]
1137 vocab_version: String,
1138 #[arg(long, default_value = "bpe")]
1139 algorithm: String,
1140 #[arg(long, default_value = "text")]
1141 adapter: String,
1142 #[arg(long = "adapter-option", value_name = "KEY=VALUE")]
1144 adapter_options: Vec<String>,
1145 #[arg(long, default_value_t = 4096)]
1146 vocab_size: u32,
1147 #[arg(long)]
1149 pretokenizer: Option<String>,
1150 #[arg(long, default_value_t = 1)]
1151 min_frequency: u64,
1152 #[arg(long)]
1153 max_token_length: Option<usize>,
1154 #[arg(long = "reserved")]
1156 reserved: Vec<String>,
1157 #[arg(long)]
1159 dictionary_file: Option<PathBuf>,
1160 #[arg(long)]
1161 description: Option<String>,
1162 #[arg(long)]
1164 license: Option<String>,
1165 #[arg(long, value_name = "BYTES")]
1169 stream_bytes: Option<usize>,
1170 #[arg(long, value_name = "VOCAB")]
1175 resume_from: Option<PathBuf>,
1176 #[arg(long, conflicts_with = "no_test_vectors")]
1180 embed_test_vectors: bool,
1181 #[arg(long, hide = true)]
1183 no_test_vectors: bool,
1184 #[arg(long)]
1185 output: PathBuf,
1186 #[arg(long)]
1188 force: bool,
1189}
1190
1191fn print(value: &impl serde::Serialize) -> kute::Result<()> {
1192 let text = serde_json::to_string_pretty(value)?;
1193 let mut out = std::io::stdout().lock();
1194 writeln!(out, "{text}")?;
1195 Ok(())
1196}
1197
1198fn parse_pretokenizer(spec: Option<&str>, adapter: &str) -> kute::Result<Pretokenizer> {
1199 match spec {
1200 None => Ok(if adapter == "text" { Pretokenizer::Gpt4 } else { Pretokenizer::None }),
1201 Some("none") => Ok(Pretokenizer::None),
1202 Some("gpt4") => Ok(Pretokenizer::Gpt4),
1203 Some(s) => match s.strip_prefix("regex:") {
1204 Some(p) if !p.is_empty() => Ok(Pretokenizer::Regex(p.to_string())),
1205 _ => Err(KuteError::InvalidConfig(format!("pretokenizer {s:?}: expected none, gpt4 or regex:<pattern>"))),
1206 },
1207 }
1208}
1209
1210fn train(engine: &Engine, args: TrainArgs) -> kute::Result<()> {
1211 let mut config = TrainingConfig::new(VocabularyId::parse(&args.id)?, args.vocab_size);
1212 config.vocabulary_version = Version::parse(&args.vocab_version)
1213 .map_err(|e| KuteError::InvalidIdentifier(format!("version {:?}: {e}", args.vocab_version)))?;
1214 let symbol_algorithm = args.algorithm == "sequence-bpe";
1215 config.pretokenizer = if symbol_algorithm && args.pretokenizer.is_none() {
1216 Pretokenizer::None
1217 } else {
1218 parse_pretokenizer(args.pretokenizer.as_deref(), &args.adapter)?
1219 };
1220 config.min_frequency = args.min_frequency;
1221 config.max_token_length = args.max_token_length;
1222 config.reserved_tokens = args.reserved;
1223 config.description = args.description;
1224 config.license = args.license;
1225 config.embed_test_vectors = args.embed_test_vectors;
1226 config.stream_bytes = args.stream_bytes;
1227 if let Some(path) = &args.resume_from {
1228 config.resume_from = Some(Box::new(vocab::load(path)?));
1229 }
1230 if let Some(path) = &args.dictionary_file {
1231 let text = std::fs::read_to_string(path)?;
1232 config.dictionary = text.lines().map(|l| l.trim_end_matches('\r')).filter(|l| !l.is_empty()).map(str::to_string).collect();
1233 }
1234 let mut adapter_config = AdapterConfig::default();
1235 for option in &args.adapter_options {
1236 let (key, value) = option
1237 .split_once('=')
1238 .ok_or_else(|| KuteError::InvalidConfig(format!("adapter option {option:?}: expected key=value")))?;
1239 adapter_config = adapter_config.with(key, value);
1240 }
1241 let start = std::time::Instant::now();
1242 let vocabulary = engine.train_paths(&args.algorithm, &args.adapter, &adapter_config, &args.input, &config)?;
1243 let seconds = start.elapsed().as_secs_f64();
1244 vocab::save(&vocabulary, &args.output, args.force)?;
1245 eprintln!("trained {} {} in {seconds:.2} s -> {}", vocabulary.id(), vocabulary.version(), args.output.display());
1246 print(&json!({
1247 "output": args.output,
1248 "train_seconds": seconds,
1249 "peak_memory_bytes": kute_bench::peak_memory_bytes(),
1250 "resumed_from": args.resume_from,
1251 "summary": vocab::summarize(&vocabulary)?,
1252 }))
1253}
1254
1255fn run(engine: Engine, cli: Cli) -> kute::Result<()> {
1256 match cli.command {
1257 Command::Train(args) => train(&engine, *args),
1258 Command::Encode { vocab: vocab_path, input, output, compress, unknown } => {
1259 let policy = kute::UnknownPolicy::parse(&unknown)?;
1260 let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
1261 let raw = std::fs::read(&input)?;
1262 let sequence = engine.encode_raw_open(tokenizer.as_ref(), &raw, policy)?;
1263 match output {
1264 Some(path) => {
1265 let bytes = if compress { sequence.to_bytes_compressed()? } else { sequence.to_bytes()? };
1266 std::fs::write(&path, &bytes)?;
1267 print(&json!({
1268 "output": path,
1269 "input_bytes": raw.len(),
1270 "tokens": sequence.ids.len(),
1271 "escaped_symbols": sequence.escapes.len(),
1272 "serialized_bytes": bytes.len(),
1273 "vocabulary": format!("{} {}", sequence.vocabulary_id, sequence.vocabulary_version),
1274 }))
1275 }
1276 None => print(&sequence),
1277 }
1278 }
1279 Command::Decode { vocab: vocab_path, input, output, max_units } => {
1280 let tokenizer = engine.tokenizer(vocab::load(&vocab_path)?)?;
1281 let sequence = TokenSequence::from_bytes(&std::fs::read(&input)?)?;
1282 let bytes = engine.decode_raw_bounded(tokenizer.as_ref(), &sequence, max_units.unwrap_or(u64::MAX))?;
1283 match output {
1284 Some(path) => {
1285 std::fs::write(&path, &bytes)?;
1286 print(&json!({ "output": path, "bytes": bytes.len(), "tokens": sequence.ids.len() }))
1287 }
1288 None => {
1289 let mut out = std::io::stdout().lock();
1290 out.write_all(&bytes)?;
1291 out.flush()?;
1292 Ok(())
1293 }
1294 }
1295 }
1296 Command::Inspect { vocab: vocab_path, token, longest } => {
1297 let vocabulary = vocab::load(&vocab_path)?;
1298 if let Some(id) = token {
1299 return print(&vocabulary.record(id)?);
1300 }
1301 let mut report = json!({ "summary": vocab::summarize(&vocabulary)? });
1302 if longest > 0 {
1303 let mut learned: Vec<&kute::TokenEntry> = vocabulary.tokens.iter().filter(|t| t.kind == kute::TokenKind::Merge).collect();
1304 learned.sort_by(|a, b| b.payload.len().cmp(&a.payload.len()).then(a.id.cmp(&b.id)));
1305 let rows: Vec<kute::TokenRecord> = learned.into_iter().take(longest).map(|t| vocabulary.record(t.id)).collect::<kute::Result<_>>()?;
1306 report["longest_learned_tokens"] = serde_json::to_value(rows)?;
1307 }
1308 print(&report)
1309 }
1310 Command::Keygen { output } => print(&sign::keygen(&output)?),
1311 Command::Sign { vocab: vocab_path, key, output, force } => print(&sign::sign(&vocab_path, &key, &output, force)?),
1312 Command::Verify { vocab: vocab_path, trusted_keys } => {
1313 let (report, verified) = sign::verify(&vocab_path, &trusted_keys)?;
1314 print(&report)?;
1315 if !verified {
1316 return Err(KuteError::Integrity("no trusted key has signed this vocabulary".into()));
1317 }
1318 Ok(())
1319 }
1320 Command::Validate { vocab: vocab_path } => {
1321 let vocabulary = vocab::load(&vocab_path)?;
1322 let report = engine.verify(&vocabulary)?;
1323 print(&report)?;
1324 if report.ok() {
1325 Ok(())
1326 } else {
1327 Err(KuteError::InvalidVocabulary(format!("{} of {} test vectors failed", report.failures.len(), report.vectors)))
1328 }
1329 }
1330 Command::Compare { a, b } => print(&vocab::compare(&vocab::load(&a)?, &vocab::load(&b)?)?),
1331 Command::Convert { input, output, force } => {
1332 let vocabulary = vocab::load(&input)?;
1333 vocab::save(&vocabulary, &output, force)?;
1334 let written = vocab::load(&output)?;
1336 if written != vocabulary {
1337 return Err(KuteError::Integrity("the converted file does not read back as the same vocabulary".into()));
1338 }
1339 let median_ms = |path: &PathBuf| -> kute::Result<f64> {
1340 let bytes = std::fs::read(path)?;
1341 let mut times = Vec::new();
1342 for _ in 0..5 {
1343 let start = std::time::Instant::now();
1344 vocab::from_slice(&bytes)?;
1345 times.push(start.elapsed().as_secs_f64() * 1000.0);
1346 }
1347 times.sort_by(|a, b| a.total_cmp(b));
1348 Ok((times[2] * 1000.0).round() / 1000.0)
1349 };
1350 print(&json!({
1351 "input": { "path": input, "bytes": std::fs::metadata(&input)?.len(), "load_ms_median": median_ms(&input)? },
1352 "output": { "path": output, "bytes": std::fs::metadata(&output)?.len(), "load_ms_median": median_ms(&output)? },
1353 "digest": written.digest()?,
1354 "tokens": written.len(),
1355 "identical": true,
1356 }))
1357 }
1358 Command::Export { vocab: vocab_path, format: ExportFormat::Tiktoken, output } => {
1359 let vocabulary = vocab::load(&vocab_path)?;
1360 let export = vocab::export_tiktoken(&vocabulary)?;
1361 std::fs::write(&output, &export.bpe_file)?;
1362 let mut sidecar = output.clone().into_os_string();
1363 sidecar.push(".json");
1364 let sidecar = PathBuf::from(sidecar);
1365 let meta = json!({
1366 "name": vocabulary.id().as_str().replace(':', "_"),
1367 "pat_str": export.pat_str,
1368 "special_tokens": export.special_tokens,
1369 "explicit_n_vocab": export.n_vocab,
1370 "source_vocabulary": format!("{} {}", vocabulary.id(), vocabulary.version()),
1371 "source_digest": vocabulary.digest()?,
1372 });
1373 std::fs::write(&sidecar, serde_json::to_vec_pretty(&meta)?)?;
1374 print(&json!({ "bpe_file": output, "metadata": sidecar, "tokens": export.n_vocab }))
1375 }
1376 Command::Benchmark { vocab: vocab_path, dataset, suite, repo_root, large_text, iterations, output } => {
1377 let report = if suite {
1378 serde_json::to_value(kute_bench::suite::run(&engine, &kute_bench::suite::Options { repo_root, iterations, large_text })?)?
1379 } else {
1380 let (Some(vocab_path), Some(dataset)) = (vocab_path, dataset) else {
1381 return Err(KuteError::InvalidConfig("benchmark needs --vocab and --dataset, or --suite".into()));
1382 };
1383 let vocabulary = vocab::load(&vocab_path)?;
1384 let documents = kute_bench::read_dataset(&dataset)?;
1385 json!({
1386 "environment": kute_bench::Environment::detect(),
1387 "dataset": dataset,
1388 "evaluation": kute_bench::evaluate(&engine, &vocabulary, &documents, iterations)?,
1389 })
1390 };
1391 if let Some(path) = output {
1392 let mut text = serde_json::to_string_pretty(&report)?;
1393 text.push('\n');
1394 std::fs::write(&path, text)?;
1395 eprintln!("report written to {}", path.display());
1396 }
1397 print(&report)
1398 }
1399 Command::SampleData { output } => {
1400 use kute_bench::data;
1401 std::fs::create_dir_all(&output)?;
1402 let files: Vec<(&str, Vec<u8>, &str)> = vec![
1403 ("alarms-train.jsonl", data::alarm_log(51, 4000), "plant alarm log, 4000 episodes"),
1404 ("alarms-eval.jsonl", data::alarm_log(52, 1000), "plant alarm log, 1000 episodes, different seed"),
1405 ("messages-train.jsonl", data::agent_messages(61, 4000), "agent messages, 4000 records"),
1406 ("messages-eval.jsonl", data::agent_messages(62, 1000), "agent messages, 1000 records, different seed"),
1407 ("frames-train.bin", data::binary_records(31, 6000), "binary telemetry frames, 6000 records"),
1408 ("frames-eval.bin", data::binary_records(32, 2000), "binary telemetry frames, 2000 records, different seed"),
1409 ("words-train.txt", data::invented_words(81, 60_000), "invented-word text, 60000 words"),
1410 ("words-eval.txt", data::invented_words(82, 15_000), "invented-word text, 15000 words, different seed"),
1411 ];
1412 let mut written = Vec::new();
1413 for (name, bytes, what) in files {
1414 std::fs::write(output.join(name), &bytes)?;
1415 written.push(json!({ "file": name, "bytes": bytes.len(), "sha256": kute::sha256_tagged(&bytes), "content": what }));
1416 }
1417 print(&json!({ "output": output, "synthetic": true, "files": written }))
1418 }
1419 Command::Discover(args) => discover(&engine, *args),
1420 Command::Evolve { vocab: vocab_path, additions, new_version, output, force } => {
1421 let version = Version::parse(&new_version).map_err(|e| KuteError::InvalidIdentifier(format!("version {new_version:?}: {e}")))?;
1422 let parent = vocab::load(&vocab_path)?;
1423 let child = kute::bpe::sequence::evolve(&parent, &split_additions(&additions), version)?;
1424 let report = engine.verify(&child)?;
1425 if !report.ok() {
1426 return Err(KuteError::Backend(format!("the evolved vocabulary fails its test vectors: {}", report.failures.join("; "))));
1427 }
1428 vocab::save(&child, &output, force)?;
1429 let mut warnings = Vec::new();
1434 for (limit, bytes) in [(256usize, "one byte"), (65_536, "two bytes")] {
1435 if parent.len() <= limit && child.len() > limit {
1436 warnings.push(format!(
1437 "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.",
1438 parent.len(),
1439 child.len()
1440 ));
1441 }
1442 }
1443 for warning in &warnings {
1444 eprintln!("warning: {warning}");
1445 }
1446 print(&json!({
1447 "output": output,
1448 "parent": { "version": parent.version().to_string(), "digest": parent.digest()?, "tokens": parent.len() },
1449 "summary": vocab::summarize(&child)?,
1450 "warnings": warnings,
1451 }))
1452 }
1453 Command::Peer { action } => {
1454 let result = peer(engine, action);
1455 peer_status::end(&result);
1458 result
1459 }
1460 Command::Mcp { vocab: paths, max_input_bytes, max_output_bytes } => {
1461 let vocabularies = paths.iter().map(vocab::load).collect::<kute::Result<Vec<_>>>()?;
1462 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() };
1463 let server = mcp::Server::new(engine, vocabularies, limits)?;
1464 server.serve(std::io::stdin().lock(), std::io::stdout().lock())?;
1465 Ok(())
1466 }
1467 Command::Live {
1468 input,
1469 symbol_field,
1470 time_field,
1471 group_field,
1472 pane,
1473 panes,
1474 lateness,
1475 end_on,
1476 idle,
1477 max_buffered,
1478 max_length,
1479 max_symbols,
1480 max_candidates,
1481 max_entities,
1482 min_support,
1483 min_cohesion_bits,
1484 max_patterns,
1485 checkpoint,
1486 checkpoint_every,
1487 resume,
1488 skip_bad_lines,
1489 } => {
1490 let bounds = kute_discover::live::LiveParams { max_length, max_symbols, max_candidates, max_entities, ..Default::default() };
1491 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 };
1492 live::run(live::Options { input, symbol_field, time_field, group_field, params, checkpoint, checkpoint_every, resume, skip_bad_lines })
1493 }
1494 Command::Predict { input, symbol_field, time_field, time_unit, group_field, holdout_fraction, max_context, min_count, windows, resamples, seed, output } => {
1495 let schema = kute::EventSchema {
1496 id: "kute:events:unnamed".into(),
1497 version: 1,
1498 symbol_field,
1499 time_unit: Some(kute::TimeUnit::parse(&time_unit)?),
1500 time_field: Some(time_field),
1501 group_field,
1502 };
1503 let mut stream = kute::EventStream::new(schema)?;
1504 for path in &input {
1505 for file in kute::collect_files(path)? {
1506 let reader = std::io::BufReader::with_capacity(1 << 20, std::fs::File::open(&file)?);
1507 stream.read_jsonl(reader, &file.display().to_string())?;
1508 }
1509 }
1510 let params = kute_discover::predict::PredictParams { holdout_fraction, max_context, min_count, windows, resamples, seed };
1511 let report = kute_discover::predict::evaluate(&stream, ¶ms)?;
1512 if let Some(path) = output {
1513 std::fs::write(&path, serde_json::to_vec_pretty(&report)?)?;
1514 }
1515 print(&report)
1516 }
1517 Command::Shadow { parent, candidate, input, unknown, min_improvement, horizon, distributions, max_slowdown, passes, fail_on_reject } => {
1518 let (report, approved) = shadow::run(&engine, &shadow::Options { parent, candidate, inputs: input, unknown, min_improvement, horizon, distributions, max_slowdown, passes })?;
1519 print(&report)?;
1520 if fail_on_reject && !approved {
1521 return Err(KuteError::Backend("the candidate was rejected".into()));
1522 }
1523 Ok(())
1524 }
1525 Command::Events { action } => match action {
1526 EventsAction::Pack { input, output, symbol_field, time_field, group_field, codec } => {
1527 let layout = kute_events::Layout { symbol_field, time_field, group_field };
1528 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)?)?;
1529 std::fs::write(&output, &container)?;
1530 print(&json!({ "output": output, "report": report }))
1531 }
1532 EventsAction::Unpack { input, output, max_bytes } => {
1533 let bytes = kute_events::unpack(&std::fs::read(&input)?, max_bytes)?;
1534 match output {
1535 Some(path) => {
1536 std::fs::write(&path, &bytes)?;
1537 print(&json!({ "output": path, "bytes": bytes.len() }))
1538 }
1539 None => {
1540 let mut out = std::io::stdout().lock();
1541 out.write_all(&bytes)?;
1542 out.flush()?;
1543 Ok(())
1544 }
1545 }
1546 }
1547 EventsAction::Inspect { input } => print(&kute_events::header(&std::fs::read(&input)?)?.0),
1548 },
1549 Command::Signals { action } => match action {
1550 SignalsAction::Pack { input, output, max_error, codec, column, delimiter, skip_lines } => {
1551 let text = std::fs::read_to_string(&input)?;
1552 let mut values = Vec::new();
1553 let mut missing = 0u64;
1554 for (number, line) in text.lines().enumerate().skip(skip_lines) {
1555 let field = match (column, delimiter) {
1556 (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)))?,
1557 _ => line,
1558 }
1559 .trim();
1560 if field.is_empty() || field == "?" || field.eq_ignore_ascii_case("na") || field.eq_ignore_ascii_case("nan") {
1561 missing += 1;
1562 values.push(f64::NAN);
1563 } else {
1564 values.push(field.parse::<f64>().map_err(|_| KuteError::InvalidInput(format!("line {}: {field:?} is not a number", number + 1)))?);
1565 }
1566 }
1567 let mode = max_error.map_or(kute_signals::Mode::Exact, |max_error| kute_signals::Mode::Bounded { max_error });
1568 let (container, report) = kute_signals::pack_with(&values, mode, codec.as_deref().map_or(Ok(kute_signals::Codec::preferred()), kute_signals::Codec::parse)?)?;
1569 std::fs::write(&output, &container)?;
1570 print(&json!({ "output": output, "input_bytes": text.len(), "missing_values": missing, "report": report }))
1571 }
1572 SignalsAction::Unpack { input, output, max_values } => {
1573 let values = kute_signals::unpack(&std::fs::read(&input)?, max_values)?;
1574 let mut text = String::with_capacity(values.len() * 8);
1575 for value in &values {
1576 let plain = value.to_string();
1580 if plain.len() > 24 {
1581 text.push_str(&format!("{value:e}"));
1582 } else {
1583 text.push_str(&plain);
1584 }
1585 text.push('\n');
1586 }
1587 match output {
1588 Some(path) => {
1589 std::fs::write(&path, &text)?;
1590 print(&json!({ "output": path, "values": values.len() }))
1591 }
1592 None => {
1593 let mut out = std::io::stdout().lock();
1594 out.write_all(text.as_bytes())?;
1595 out.flush()?;
1596 Ok(())
1597 }
1598 }
1599 }
1600 SignalsAction::Inspect { input } => print(&kute_signals::header(&std::fs::read(&input)?)?),
1601 },
1602 Command::Fetch { from, digest, output, trusted_keys, force, list, max_bytes, timeout } => {
1603 let timeout = std::time::Duration::from_secs(timeout.max(1));
1604 match (list, digest, output) {
1605 (true, _, _) => print(®istry::list(&from, timeout)?),
1606 (false, Some(digest), Some(output)) => print(®istry::fetch(&engine, &from, &digest, &output, &trusted_keys, force, max_bytes, timeout)?),
1607 _ => Err(KuteError::InvalidConfig("give --digest and --output, or --list".into())),
1608 }
1609 }
1610 Command::Serve { vocab: paths, listen, insecure_remote, studio, registry, registry_only, peer_status, upstream, upstream_trusted_key, upstream_timeout, upstream_max_bytes, upstream_cache_bytes, max_input_bytes, max_output_bytes, workers, timeout } => {
1611 let registry = registry || registry_only;
1612 if !upstream.is_empty() && !registry {
1613 return Err(KuteError::InvalidConfig("--upstream is for a registry: add --registry or --registry-only".into()));
1614 }
1615 if upstream.is_empty() && !upstream_trusted_key.is_empty() {
1618 return Err(KuteError::InvalidConfig("--upstream-trusted-key is about files from an --upstream, and none was named".into()));
1619 }
1620 let federation = if upstream.is_empty() {
1621 None
1622 } else {
1623 let check: Option<http::UpstreamCheck> = if upstream_trusted_key.is_empty() { None } else { Some(Box::new(sign::gate(&upstream_trusted_key)?)) };
1624 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)?))
1625 };
1626 let vocabularies = paths.iter().map(vocab::load).collect::<kute::Result<Vec<_>>>()?;
1627 let max_body_bytes = max_input_bytes.saturating_mul(2).saturating_add(1 << 20);
1628 let limits = mcp::Limits { max_input_bytes, max_output_bytes, max_request_bytes: max_body_bytes, ..Default::default() };
1629 let server = mcp::Server::new(engine, vocabularies, limits)?;
1630 let listener = std::net::TcpListener::bind(&listen)?;
1631 let address = listener.local_addr()?;
1632 if !http::is_loopback(&address) && !insecure_remote {
1633 return Err(KuteError::InvalidConfig(format!(
1634 "{address} is not a loopback address, and this service has no TLS and no authentication; pass --insecure-remote to serve it anyway"
1635 )));
1636 }
1637 if studio && !http::is_loopback(&address) {
1638 return Err(KuteError::InvalidConfig("Studio is served on a loopback address only: it is a page for the person at this machine".into()));
1639 }
1640 if peer_status.is_some() && !http::is_loopback(&address) {
1641 return Err(KuteError::InvalidConfig("--peer-status is given on a loopback address only: the status names who connected to the peer".into()));
1642 }
1643 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 }))?;
1644 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, peer_status, ..Default::default() };
1645 http::serve(server, listener, options)
1646 }
1647 Command::Capabilities => {
1648 let registry = engine.registry();
1649 let algorithms: Vec<kute::TokenizerCapabilities> =
1650 registry.algorithm_names().iter().map(|n| registry.tokenizer(n).map(|t| t.capabilities())).collect::<kute::Result<_>>()?;
1651 let adapters: Vec<serde_json::Value> = registry
1652 .adapter_names()
1653 .iter()
1654 .map(|n| {
1655 registry.adapter(n).map(|a| {
1656 let c = a.capabilities();
1657 json!({ "name": c.name, "modality": c.modality, "lossless": c.lossless, "notes": c.notes })
1658 })
1659 })
1660 .collect::<kute::Result<_>>()?;
1661 print(&json!({
1662 "kute_version": kute::KUTE_VERSION,
1663 "kvf_version": kute::KVF_VERSION,
1664 "algorithms": algorithms,
1665 "adapters": adapters,
1666 }))
1667 }
1668 }
1669}
1670
1671pub fn main_with(engine: Engine) -> ExitCode {
1674 match run(engine, Cli::parse()) {
1675 Ok(()) => ExitCode::SUCCESS,
1676 Err(e) => {
1677 eprintln!("kute: {e}");
1678 ExitCode::FAILURE
1679 }
1680 }
1681}