1use kute::{Engine, KuteError, Result, TokenPayload, TokenSequence, Tokenizer, UnknownPolicy, Version, Vocabulary};
17use serde::{Deserialize, Serialize};
18use sha2::{Digest, Sha256};
19use std::collections::BTreeMap;
20use std::io::{Read, Write};
21
22pub const PROTOCOL_VERSION: u32 = 1;
23pub const DEFAULT_MAX_FRAME: u64 = 64 * 1024 * 1024;
25
26#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
28pub struct VocabRef {
29 pub id: String,
30 pub version: String,
31 pub digest: String,
32 pub algorithm: String,
33 pub tokens: u64,
34}
35
36impl VocabRef {
37 pub fn of(vocabulary: &Vocabulary) -> Result<Self> {
38 Ok(Self {
39 id: vocabulary.id().to_string(),
40 version: vocabulary.version().to_string(),
41 digest: vocabulary.digest()?,
42 algorithm: vocabulary.manifest.algorithm.clone(),
43 tokens: vocabulary.len() as u64,
44 })
45 }
46}
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(rename_all = "snake_case")]
50pub enum ErrorCode {
51 OutOfOrder,
53 UnsupportedProtocol,
54 UnsupportedAlgorithm,
55 VocabularyConflict,
57 UnknownVocabulary,
58 Invalid,
60 Refused,
62 TooLarge,
63}
64
65#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
66#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
67pub enum Message {
68 Hello { protocol: u32, peer: String, software: String },
69 Capabilities { algorithms: Vec<String>, adapters: Vec<String>, max_frame_bytes: u64, accepts_vocabularies: bool, accepts_proposals: bool },
70 VocabAnnounce { vocabulary: VocabRef },
72 VocabRequest { digest: String },
74 VocabData {
77 digest: String,
78 #[serde(with = "kute::b64")]
79 kvf: Vec<u8>,
80 },
81 VocabAccept { digest: String },
83 SymbolQuery { digest: String, symbols: Vec<String> },
85 SymbolInfo { digest: String, token_id: Option<u32>, content_hash: String },
87 SymbolPropose { digest: String, additions: Vec<Vec<String>>, version: String },
90 Translate {
92 id: u64,
93 #[serde(with = "kute::b64")]
94 container: Vec<u8>,
95 to_digest: String,
96 },
97 EncodedMessage {
99 id: u64,
100 #[serde(with = "kute::b64")]
101 container: Vec<u8>,
102 },
103 Ack { id: u64, units: u64, sha256: String },
106 Error { code: ErrorCode, message: String },
107}
108
109fn refuse(code: ErrorCode, message: impl Into<String>) -> Vec<Message> {
110 vec![Message::Error { code, message: message.into() }]
111}
112
113#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct Policy {
116 pub accept_vocabularies: bool,
118 pub accept_proposals: bool,
120 pub max_frame_bytes: u64,
121 pub max_vocabulary_tokens: u64,
122 pub max_decoded_units: u64,
124}
125
126impl Default for Policy {
127 fn default() -> Self {
128 Self {
129 accept_vocabularies: true,
130 accept_proposals: false,
131 max_frame_bytes: DEFAULT_MAX_FRAME,
132 max_vocabulary_tokens: 1_000_000,
133 max_decoded_units: 256 * 1024 * 1024,
134 }
135 }
136}
137
138#[derive(Clone, Debug, PartialEq)]
140pub struct Delivered {
141 pub id: u64,
142 pub sequence: TokenSequence,
143 pub bytes: Vec<u8>,
145}
146
147struct Held {
148 vocabulary: Vocabulary,
149 tokenizer: Box<dyn Tokenizer>,
150}
151
152#[derive(Clone, Copy, PartialEq, Eq)]
153enum Stage {
154 New,
155 Greeted,
156 Ready,
157}
158
159pub struct Peer {
161 name: String,
162 engine: Engine,
163 policy: Policy,
164 held: BTreeMap<String, Held>,
165 stage: Stage,
166 wanted: Option<VocabRef>,
167 inbox: Vec<Delivered>,
168}
169
170pub fn sha256_hex(bytes: &[u8]) -> String {
171 kute::hex(&Sha256::digest(bytes))
172}
173
174impl Peer {
175 pub fn new(name: &str, engine: Engine, policy: Policy) -> Self {
176 Self { name: name.to_string(), engine, policy, held: BTreeMap::new(), stage: Stage::New, wanted: None, inbox: Vec::new() }
177 }
178
179 pub fn add_vocabulary(&mut self, vocabulary: Vocabulary) -> Result<String> {
181 vocabulary.validate()?;
182 let digest = vocabulary.compute_digest()?;
183 if let Some(other) = self.held.values().find(|h| h.vocabulary.id() == vocabulary.id() && h.vocabulary.version() == vocabulary.version()) {
184 if other.vocabulary.digest()? != digest {
185 return Err(KuteError::VocabularyMismatch(format!(
186 "a different vocabulary is already held as {} {}",
187 vocabulary.id(),
188 vocabulary.version()
189 )));
190 }
191 }
192 let tokenizer = self.engine.tokenizer(vocabulary.clone())?;
193 let vocabulary = tokenizer.vocabulary().cloned().unwrap_or(vocabulary);
194 self.held.insert(digest.clone(), Held { vocabulary, tokenizer });
195 Ok(digest)
196 }
197
198 pub fn vocabulary(&self, digest: &str) -> Option<&Vocabulary> {
199 self.held.get(digest).map(|h| &h.vocabulary)
200 }
201
202 pub fn digests(&self) -> Vec<String> {
203 self.held.keys().cloned().collect()
204 }
205
206 pub fn take_inbox(&mut self) -> Vec<Delivered> {
208 std::mem::take(&mut self.inbox)
209 }
210
211 pub fn engine(&self) -> &Engine {
212 &self.engine
213 }
214
215 fn hold(&self, digest: &str) -> Result<&Held> {
216 self.held.get(digest).ok_or_else(|| KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")))
217 }
218
219 pub fn hello(&self) -> Message {
220 Message::Hello { protocol: PROTOCOL_VERSION, peer: self.name.clone(), software: format!("kute {}", kute::KUTE_VERSION) }
221 }
222
223 pub fn capabilities(&self) -> Message {
224 Message::Capabilities {
225 algorithms: self.engine.registry().algorithm_names(),
226 adapters: self.engine.registry().adapter_names(),
227 max_frame_bytes: self.policy.max_frame_bytes,
228 accepts_vocabularies: self.policy.accept_vocabularies,
229 accepts_proposals: self.policy.accept_proposals,
230 }
231 }
232
233 pub fn encode_message(&self, id: u64, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<(Message, String)> {
236 let held = self.hold(digest)?;
237 let sequence = self.engine.encode_raw_open(held.tokenizer.as_ref(), raw, policy)?;
238 let expected = sha256_hex(&self.engine.decode_raw(held.tokenizer.as_ref(), &sequence)?);
239 Ok((Message::EncodedMessage { id, container: sequence.to_bytes_compressed()? }, expected))
240 }
241
242 pub fn evolve(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
244 let version = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
245 let child = kute::bpe::sequence::evolve(&self.hold(digest)?.vocabulary, additions, version)?;
246 self.add_vocabulary(child)
247 }
248
249 pub fn translate(&self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
252 let from = self.hold(&sequence.vocabulary_digest)?;
253 let to = self.hold(to_digest)?;
254 let units = kute::decoded_units(&from.vocabulary, sequence)?;
255 if units > self.policy.max_decoded_units {
256 return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units")));
257 }
258 to.tokenizer.encode_open(&from.tokenizer.decode(sequence)?, UnknownPolicy::Escape)
259 }
260
261 pub fn handle(&mut self, message: Message) -> Vec<Message> {
264 match (self.stage, &message) {
265 (Stage::New, Message::Hello { protocol, .. }) => {
266 if *protocol != PROTOCOL_VERSION {
267 return refuse(ErrorCode::UnsupportedProtocol, format!("this peer speaks protocol {PROTOCOL_VERSION}, not {protocol}"));
268 }
269 self.stage = Stage::Greeted;
270 return vec![self.hello()];
271 }
272 (Stage::Greeted, Message::Capabilities { .. }) => {
273 self.stage = Stage::Ready;
274 return vec![self.capabilities()];
275 }
276 (Stage::Ready, Message::Hello { .. } | Message::Capabilities { .. }) | (Stage::New | Stage::Greeted, _) => {
277 return refuse(ErrorCode::OutOfOrder, "expected HELLO, then CAPABILITIES, before anything else");
278 }
279 (Stage::Ready, _) => {}
280 }
281 match self.respond(message) {
282 Ok(replies) => replies,
283 Err(e) => {
284 let code = match e {
285 KuteError::LimitExceeded(_) => ErrorCode::TooLarge,
286 KuteError::VocabularyMismatch(_) => ErrorCode::UnknownVocabulary,
287 _ => ErrorCode::Invalid,
288 };
289 refuse(code, e.to_string())
290 }
291 }
292 }
293
294 fn respond(&mut self, message: Message) -> Result<Vec<Message>> {
295 match message {
296 Message::VocabAnnounce { vocabulary } => {
297 if self.held.contains_key(&vocabulary.digest) {
298 return Ok(vec![Message::VocabAccept { digest: vocabulary.digest }]);
299 }
300 if self.held.values().any(|h| h.vocabulary.id().as_str() == vocabulary.id && h.vocabulary.version().to_string() == vocabulary.version) {
301 return Ok(refuse(
302 ErrorCode::VocabularyConflict,
303 format!("{} {} is held here with different content", vocabulary.id, vocabulary.version),
304 ));
305 }
306 if !self.engine.registry().algorithm_names().contains(&vocabulary.algorithm) {
307 return Ok(refuse(ErrorCode::UnsupportedAlgorithm, format!("algorithm {:?} is not available here", vocabulary.algorithm)));
308 }
309 if !self.policy.accept_vocabularies {
310 return Ok(refuse(ErrorCode::Refused, "this peer does not take vocabularies from the other side"));
311 }
312 if vocabulary.tokens > self.policy.max_vocabulary_tokens {
313 return Ok(refuse(ErrorCode::TooLarge, format!("vocabularies above {} tokens are not taken", self.policy.max_vocabulary_tokens)));
314 }
315 let digest = vocabulary.digest.clone();
316 self.wanted = Some(vocabulary);
317 Ok(vec![Message::VocabRequest { digest }])
318 }
319 Message::VocabRequest { digest } => {
320 let kvf = kute::vocab::to_vec(&self.hold(&digest)?.vocabulary)?;
321 Ok(vec![Message::VocabData { digest, kvf }])
322 }
323 Message::VocabData { digest, kvf } => {
324 let Some(wanted) = self.wanted.take().filter(|w| w.digest == digest) else {
325 return Ok(refuse(ErrorCode::OutOfOrder, "vocabulary data that was not requested"));
326 };
327 let vocabulary = kute::vocab::from_slice(&kvf)?;
328 if vocabulary.compute_digest()? != digest || VocabRef::of(&vocabulary)? != wanted {
331 return Ok(refuse(ErrorCode::Invalid, "the vocabulary sent is not the one announced"));
332 }
333 if vocabulary.len() as u64 > self.policy.max_vocabulary_tokens {
334 return Ok(refuse(ErrorCode::TooLarge, "vocabulary exceeds the token limit"));
335 }
336 let report = self.engine.verify(&vocabulary)?;
337 if !report.ok() {
338 return Ok(refuse(ErrorCode::Invalid, format!("the vocabulary fails its own test vectors: {}", report.failures.join("; "))));
339 }
340 let digest = self.add_vocabulary(vocabulary)?;
341 Ok(vec![Message::VocabAccept { digest }])
342 }
343 Message::SymbolQuery { digest, symbols } => {
344 let payload = TokenPayload::Symbols(symbols);
345 let token_id = self.hold(&digest)?.vocabulary.tokens.iter().find(|t| t.payload == payload).map(|t| t.id);
346 Ok(vec![Message::SymbolInfo { digest, token_id, content_hash: payload.content_hash() }])
347 }
348 Message::SymbolPropose { digest, additions, version } => {
349 if !self.policy.accept_proposals {
350 return Ok(refuse(ErrorCode::Refused, "this peer does not accept vocabulary proposals"));
351 }
352 let digest = self.evolve(&digest, &additions, &version)?;
353 Ok(vec![Message::VocabAccept { digest }])
354 }
355 Message::Translate { id, container, to_digest } => {
356 let sequence = TokenSequence::from_bytes(&container)?;
357 let translated = self.translate(&sequence, &to_digest)?;
358 Ok(vec![Message::EncodedMessage { id, container: translated.to_bytes_compressed()? }])
359 }
360 Message::EncodedMessage { id, container } => {
361 let sequence = TokenSequence::from_bytes(&container)?;
362 let held = self.hold(&sequence.vocabulary_digest)?;
363 let units = kute::decoded_units(&held.vocabulary, &sequence)?;
364 let bytes = self.engine.decode_raw_bounded(held.tokenizer.as_ref(), &sequence, self.policy.max_decoded_units)?;
365 let sha256 = sha256_hex(&bytes);
366 self.inbox.push(Delivered { id, sequence, bytes });
367 Ok(vec![Message::Ack { id, units, sha256 }])
368 }
369 Message::VocabAccept { .. } | Message::SymbolInfo { .. } | Message::Ack { .. } | Message::Error { .. } => {
370 Ok(refuse(ErrorCode::OutOfOrder, "a reply arrived where a request was expected"))
371 }
372 Message::Hello { .. } | Message::Capabilities { .. } => Ok(refuse(ErrorCode::OutOfOrder, "the handshake is already complete")),
373 }
374 }
375}
376
377pub trait Transport {
379 fn send(&mut self, message: &Message) -> Result<()>;
380 fn recv(&mut self) -> Result<Option<Message>>;
382}
383
384pub struct Framed<S: Read + Write> {
387 stream: S,
388 max_frame: u64,
389}
390
391impl<S: Read + Write> Framed<S> {
392 pub fn new(stream: S, max_frame: u64) -> Self {
393 Self { stream, max_frame: max_frame.min(DEFAULT_MAX_FRAME) }
394 }
395}
396
397impl<S: Read + Write> Transport for Framed<S> {
398 fn send(&mut self, message: &Message) -> Result<()> {
399 let body = serde_json::to_vec(message)?;
400 if body.len() as u64 > self.max_frame {
401 return Err(KuteError::LimitExceeded(format!("message of {} bytes exceeds the frame limit of {}", body.len(), self.max_frame)));
402 }
403 self.stream.write_all(&(body.len() as u32).to_le_bytes())?;
404 self.stream.write_all(&body)?;
405 self.stream.flush()?;
406 Ok(())
407 }
408
409 fn recv(&mut self) -> Result<Option<Message>> {
410 let mut length = [0u8; 4];
411 let mut got = 0;
412 while got < 4 {
413 match self.stream.read(&mut length[got..]) {
414 Ok(0) if got == 0 => return Ok(None),
415 Ok(0) => return Err(KuteError::InvalidInput("the stream ended inside a frame header".into())),
416 Ok(n) => got += n,
417 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
418 Err(e) => return Err(e.into()),
419 }
420 }
421 let length = u32::from_le_bytes(length) as u64;
422 if length > self.max_frame {
423 return Err(KuteError::LimitExceeded(format!("incoming frame of {length} bytes exceeds the limit of {}", self.max_frame)));
424 }
425 let mut body = Vec::new();
428 (&mut self.stream).take(length).read_to_end(&mut body)?;
429 if body.len() as u64 != length {
430 return Err(KuteError::InvalidInput("the stream ended inside a frame".into()));
431 }
432 serde_json::from_slice(&body).map(Some).map_err(|e| KuteError::InvalidInput(format!("not a protocol message: {e}")))
433 }
434}
435
436#[derive(Clone, Debug, PartialEq, Eq)]
438pub struct Remote {
439 pub peer: String,
440 pub software: String,
441 pub algorithms: Vec<String>,
442 pub accepts_vocabularies: bool,
443 pub accepts_proposals: bool,
444}
445
446fn peer_error(code: ErrorCode, message: String) -> KuteError {
447 KuteError::Backend(format!("the peer answered {code:?}: {message}"))
448}
449
450pub struct Session<T: Transport> {
452 pub peer: Peer,
453 transport: T,
454 next_id: u64,
455}
456
457impl<T: Transport> Session<T> {
458 pub fn new(peer: Peer, transport: T) -> Self {
459 Self { peer, transport, next_id: 1 }
460 }
461
462 fn ask(&mut self, message: &Message) -> Result<Message> {
463 self.transport.send(message)?;
464 match self.transport.recv()? {
465 Some(Message::Error { code, message }) => Err(peer_error(code, message)),
466 Some(reply) => Ok(reply),
467 None => Err(KuteError::Backend("the peer closed the connection".into())),
468 }
469 }
470
471 fn unexpected<R>(reply: Message) -> Result<R> {
472 Err(KuteError::Backend(format!("unexpected reply from the peer: {reply:?}")))
473 }
474
475 pub fn connect(&mut self) -> Result<Remote> {
477 let (peer, software) = match self.ask(&self.peer.hello())? {
478 Message::Hello { protocol, peer, software } if protocol == PROTOCOL_VERSION => (peer, software),
479 other => return Self::unexpected(other),
480 };
481 match self.ask(&self.peer.capabilities())? {
482 Message::Capabilities { algorithms, accepts_vocabularies, accepts_proposals, .. } => {
483 Ok(Remote { peer, software, algorithms, accepts_vocabularies, accepts_proposals })
484 }
485 other => Self::unexpected(other),
486 }
487 }
488
489 pub fn share(&mut self, digest: &str) -> Result<bool> {
492 let vocabulary = VocabRef::of(&self.peer.hold(digest)?.vocabulary)?;
493 match self.ask(&Message::VocabAnnounce { vocabulary })? {
494 Message::VocabAccept { digest: d } if d == digest => Ok(false),
495 Message::VocabRequest { digest: d } if d == digest => {
496 let kvf = kute::vocab::to_vec(&self.peer.hold(digest)?.vocabulary)?;
497 match self.ask(&Message::VocabData { digest: digest.to_string(), kvf })? {
498 Message::VocabAccept { digest: d } if d == digest => Ok(true),
499 other => Self::unexpected(other),
500 }
501 }
502 other => Self::unexpected(other),
503 }
504 }
505
506 pub fn send(&mut self, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<u64> {
510 let id = self.next_id;
511 self.next_id += 1;
512 let (message, expected) = self.peer.encode_message(id, digest, raw, policy)?;
513 match self.ask(&message)? {
514 Message::Ack { id: acked, units, sha256 } if acked == id => {
515 if sha256 != expected {
516 return Err(KuteError::Integrity("the peer decoded the message to different content".into()));
517 }
518 Ok(units)
519 }
520 other => Self::unexpected(other),
521 }
522 }
523
524 pub fn propose(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
528 let parsed = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
529 let child = kute::bpe::sequence::evolve(&self.peer.hold(digest)?.vocabulary, additions, parsed)?;
530 let expected = child.digest()?;
531 let propose = Message::SymbolPropose { digest: digest.to_string(), additions: additions.to_vec(), version: version.to_string() };
532 match self.ask(&propose)? {
533 Message::VocabAccept { digest: theirs } if theirs == expected => self.peer.add_vocabulary(child),
534 Message::VocabAccept { digest: theirs } => {
535 Err(KuteError::Integrity(format!("the peer derived {theirs}, this side derived {expected}")))
536 }
537 other => Self::unexpected(other),
538 }
539 }
540
541 pub fn query(&mut self, digest: &str, symbols: &[String]) -> Result<Option<u32>> {
543 match self.ask(&Message::SymbolQuery { digest: digest.to_string(), symbols: symbols.to_vec() })? {
544 Message::SymbolInfo { token_id, .. } => Ok(token_id),
545 other => Self::unexpected(other),
546 }
547 }
548
549 pub fn translate(&mut self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
552 let id = self.next_id;
553 self.next_id += 1;
554 let ask = Message::Translate { id, container: sequence.to_bytes_compressed()?, to_digest: to_digest.to_string() };
555 match self.ask(&ask)? {
556 Message::EncodedMessage { id: got, container } if got == id => {
557 let translated = TokenSequence::from_bytes(&container)?;
558 if translated.vocabulary_digest != to_digest {
559 return Err(KuteError::Integrity("the peer translated to a different vocabulary".into()));
560 }
561 Ok(translated)
562 }
563 other => Self::unexpected(other),
564 }
565 }
566
567 pub fn serve(&mut self) -> Result<u64> {
570 let mut handled = 0;
571 while let Some(message) = self.transport.recv()? {
572 for reply in self.peer.handle(message) {
573 self.transport.send(&reply)?;
574 }
575 handled += 1;
576 }
577 Ok(handled)
578 }
579}