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
22#[cfg(feature = "tls")]
23pub mod tls;
24
25pub const PROTOCOL_VERSION: u32 = 2;
30pub const EVOLUTION_RULE: &str = kute::bpe::sequence::EVOLVE_GENERATOR;
34pub const DEFAULT_MAX_FRAME: u64 = 64 * 1024 * 1024;
36
37#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
39pub struct VocabRef {
40 pub id: String,
41 pub version: String,
42 pub digest: String,
43 pub algorithm: String,
44 pub tokens: u64,
45}
46
47impl VocabRef {
48 pub fn of(vocabulary: &Vocabulary) -> Result<Self> {
49 Ok(Self {
50 id: vocabulary.id().to_string(),
51 version: vocabulary.version().to_string(),
52 digest: vocabulary.digest()?,
53 algorithm: vocabulary.manifest.algorithm.clone(),
54 tokens: vocabulary.len() as u64,
55 })
56 }
57}
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
60#[serde(rename_all = "snake_case")]
61pub enum ErrorCode {
62 OutOfOrder,
64 UnsupportedProtocol,
65 UnsupportedAlgorithm,
66 VocabularyConflict,
68 UnknownVocabulary,
69 Invalid,
71 Refused,
73 TooLarge,
74 UnsupportedRule,
76 Busy,
78}
79
80#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
81#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
82pub enum Message {
83 Hello { protocol: u32, peer: String, software: String },
84 Capabilities {
85 algorithms: Vec<String>,
86 adapters: Vec<String>,
87 max_frame_bytes: u64,
88 accepts_vocabularies: bool,
89 accepts_proposals: bool,
90 #[serde(default)]
92 evolution_rules: Vec<String>,
93 #[serde(default)]
95 kvf_versions: Vec<String>,
96 },
97 VocabAnnounce { vocabulary: VocabRef },
99 VocabRequest { digest: String },
101 VocabData {
104 digest: String,
105 #[serde(with = "kute::b64")]
106 kvf: Vec<u8>,
107 },
108 VocabAccept { digest: String },
110 SymbolQuery { digest: String, symbols: Vec<String> },
112 SymbolInfo { digest: String, token_id: Option<u32>, content_hash: String },
114 SymbolPropose {
119 digest: String,
120 additions: Vec<Vec<String>>,
121 version: String,
122 #[serde(default)]
123 rule: String,
124 },
125 Translate {
127 id: u64,
128 #[serde(with = "kute::b64")]
129 container: Vec<u8>,
130 to_digest: String,
131 },
132 EncodedMessage {
134 id: u64,
135 #[serde(with = "kute::b64")]
136 container: Vec<u8>,
137 },
138 Ack { id: u64, units: u64, sha256: String },
141 Error { code: ErrorCode, message: String },
142}
143
144fn refuse(code: ErrorCode, message: impl Into<String>) -> Vec<Message> {
145 vec![Message::Error { code, message: message.into() }]
146}
147
148#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct Policy {
157 pub give_vocabularies: bool,
159 pub answer_queries: bool,
161 pub translate: bool,
163 pub vocabularies: Option<std::collections::BTreeSet<String>>,
168 pub max_message_tokens: u64,
171 pub accept_vocabularies: bool,
173 pub accept_proposals: bool,
175 pub max_frame_bytes: u64,
176 pub max_vocabulary_tokens: u64,
177 pub max_decoded_units: u64,
179 pub max_held_vocabularies: u64,
182 pub max_held_tokens: u64,
184 pub max_inbox_messages: u64,
187 pub max_inbox_bytes: u64,
190 pub replay_window: u64,
193}
194
195impl Default for Policy {
196 fn default() -> Self {
197 Self {
198 give_vocabularies: false,
199 answer_queries: false,
200 translate: false,
201 vocabularies: None,
202 max_message_tokens: 16 * 1024 * 1024,
203 accept_vocabularies: false,
204 accept_proposals: false,
205 max_frame_bytes: DEFAULT_MAX_FRAME,
206 max_vocabulary_tokens: 1_000_000,
207 max_decoded_units: 256 * 1024 * 1024,
208 max_held_vocabularies: 64,
209 max_held_tokens: 4_000_000,
210 max_inbox_messages: 1024,
211 max_inbox_bytes: 256 * 1024 * 1024,
212 replay_window: 1024,
213 }
214 }
215}
216
217#[derive(Clone, Debug, PartialEq)]
219pub struct Delivered {
220 pub id: u64,
221 pub sequence: TokenSequence,
222 pub bytes: Vec<u8>,
224}
225
226struct Held {
227 vocabulary: Vocabulary,
228 tokenizer: Box<dyn Tokenizer>,
229}
230
231#[derive(Clone, Copy, PartialEq, Eq)]
232enum Stage {
233 New,
234 Greeted,
235 Ready,
236}
237
238pub struct Peer {
240 name: String,
241 engine: Engine,
242 policy: Policy,
243 held: BTreeMap<String, Held>,
244 stage: Stage,
245 wanted: Option<VocabRef>,
246 inbox: Vec<Delivered>,
247 inbox_bytes: u64,
248 seen: std::collections::VecDeque<(u64, String, Message)>,
250}
251
252pub fn sha256_hex(bytes: &[u8]) -> String {
253 kute::hex(&Sha256::digest(bytes))
254}
255
256impl Peer {
257 pub fn new(name: &str, engine: Engine, policy: Policy) -> Self {
258 Self {
259 name: name.to_string(),
260 engine,
261 policy,
262 held: BTreeMap::new(),
263 stage: Stage::New,
264 wanted: None,
265 inbox: Vec::new(),
266 inbox_bytes: 0,
267 seen: Default::default(),
268 }
269 }
270
271 pub fn add_vocabulary(&mut self, vocabulary: Vocabulary) -> Result<String> {
273 vocabulary.validate()?;
274 let digest = vocabulary.compute_digest()?;
275 if let Some(other) = self.held.values().find(|h| h.vocabulary.id() == vocabulary.id() && h.vocabulary.version() == vocabulary.version()) {
276 if other.vocabulary.digest()? != digest {
277 return Err(KuteError::VocabularyMismatch(format!(
278 "a different vocabulary is already held as {} {}",
279 vocabulary.id(),
280 vocabulary.version()
281 )));
282 }
283 }
284 let tokenizer = self.engine.tokenizer(vocabulary.clone())?;
285 let vocabulary = tokenizer.vocabulary().cloned().unwrap_or(vocabulary);
286 self.held.insert(digest.clone(), Held { vocabulary, tokenizer });
287 Ok(digest)
288 }
289
290 pub fn vocabulary(&self, digest: &str) -> Option<&Vocabulary> {
291 self.held.get(digest).map(|h| &h.vocabulary)
292 }
293
294 pub fn digests(&self) -> Vec<String> {
295 self.held.keys().cloned().collect()
296 }
297
298 pub fn take_inbox(&mut self) -> Vec<Delivered> {
300 self.inbox_bytes = 0;
301 std::mem::take(&mut self.inbox)
302 }
303
304 fn over_budget(&self, tokens: u64) -> Option<Vec<Message>> {
307 if self.held.len() as u64 >= self.policy.max_held_vocabularies {
308 return Some(refuse(ErrorCode::TooLarge, format!("this peer already holds {} vocabularies, its limit", self.held.len())));
309 }
310 let held: u64 = self.held.values().map(|h| h.vocabulary.len() as u64).sum();
311 if held.saturating_add(tokens) > self.policy.max_held_tokens {
312 return Some(refuse(
313 ErrorCode::TooLarge,
314 format!("this peer holds {held} tokens and takes at most {} in all", self.policy.max_held_tokens),
315 ));
316 }
317 None
318 }
319
320 pub fn engine(&self) -> &Engine {
321 &self.engine
322 }
323
324 fn hold(&self, digest: &str) -> Result<&Held> {
325 self.held.get(digest).ok_or_else(|| KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")))
326 }
327
328 fn sees(&self, digest: &str) -> bool {
330 self.policy.vocabularies.as_ref().is_none_or(|listed| listed.contains(digest))
331 }
332
333 fn usable(&self, digest: &str) -> Result<&Held> {
336 if !self.sees(digest) {
337 return Err(KuteError::VocabularyMismatch(format!("no vocabulary with digest {digest} is held")));
338 }
339 self.hold(digest)
340 }
341
342 fn show(&mut self, digest: &str) {
344 if let Some(listed) = &mut self.policy.vocabularies {
345 listed.insert(digest.to_string());
346 }
347 }
348
349 fn token_limit(&self) -> u64 {
352 self.policy.max_message_tokens.min(self.policy.max_decoded_units)
353 }
354
355 pub fn hello(&self) -> Message {
356 Message::Hello { protocol: PROTOCOL_VERSION, peer: self.name.clone(), software: format!("kute {}", kute::KUTE_VERSION) }
357 }
358
359 pub fn capabilities(&self) -> Message {
360 Message::Capabilities {
361 algorithms: self.engine.registry().algorithm_names(),
362 adapters: self.engine.registry().adapter_names(),
363 max_frame_bytes: self.policy.max_frame_bytes,
364 accepts_vocabularies: self.policy.accept_vocabularies,
365 accepts_proposals: self.policy.accept_proposals,
366 evolution_rules: vec![EVOLUTION_RULE.to_string()],
367 kvf_versions: vec![kute::KVF_VERSION.to_string()],
368 }
369 }
370
371 pub fn encode_message(&self, id: u64, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<(Message, String)> {
374 let held = self.hold(digest)?;
375 let sequence = self.engine.encode_raw_open(held.tokenizer.as_ref(), raw, policy)?;
376 let expected = sha256_hex(&self.engine.decode_raw(held.tokenizer.as_ref(), &sequence)?);
377 Ok((Message::EncodedMessage { id, container: sequence.to_bytes_compressed()? }, expected))
378 }
379
380 pub fn evolve(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
382 let version = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
383 let child = kute::bpe::sequence::evolve(&self.hold(digest)?.vocabulary, additions, version)?;
384 self.add_vocabulary(child)
385 }
386
387 pub fn translate(&self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
390 let from = self.hold(&sequence.vocabulary_digest)?;
391 let to = self.hold(to_digest)?;
392 let units = kute::decoded_units(&from.vocabulary, sequence)?;
393 if units > self.policy.max_decoded_units {
394 return Err(KuteError::LimitExceeded(format!("the sequence decodes to {units} units")));
395 }
396 let bytes = kute::decoded_bytes_at_least(&from.vocabulary, sequence)?;
399 if bytes > self.policy.max_frame_bytes {
400 return Err(KuteError::LimitExceeded(format!("the sequence decodes to at least {bytes} bytes; a frame holds {}", self.policy.max_frame_bytes)));
401 }
402 to.tokenizer.encode_open(&from.tokenizer.decode(sequence)?, UnknownPolicy::Escape)
403 }
404
405 pub fn handle(&mut self, message: Message) -> Vec<Message> {
408 match (self.stage, &message) {
409 (Stage::New, Message::Hello { protocol, .. }) => {
410 if *protocol != PROTOCOL_VERSION {
411 return refuse(ErrorCode::UnsupportedProtocol, format!("this peer speaks protocol {PROTOCOL_VERSION}, not {protocol}"));
412 }
413 self.stage = Stage::Greeted;
414 return vec![self.hello()];
415 }
416 (Stage::Greeted, Message::Capabilities { .. }) => {
417 self.stage = Stage::Ready;
418 return vec![self.capabilities()];
419 }
420 (Stage::Ready, Message::Hello { .. } | Message::Capabilities { .. }) | (Stage::New | Stage::Greeted, _) => {
421 return refuse(ErrorCode::OutOfOrder, "expected HELLO, then CAPABILITIES, before anything else");
422 }
423 (Stage::Ready, _) => {}
424 }
425 match self.respond(message) {
426 Ok(replies) => replies,
427 Err(e) => {
428 let code = match e {
429 KuteError::LimitExceeded(_) => ErrorCode::TooLarge,
430 KuteError::VocabularyMismatch(_) => ErrorCode::UnknownVocabulary,
431 _ => ErrorCode::Invalid,
432 };
433 refuse(code, e.to_string())
434 }
435 }
436 }
437
438 fn respond(&mut self, message: Message) -> Result<Vec<Message>> {
439 match message {
440 Message::VocabAnnounce { vocabulary } => {
441 if self.held.contains_key(&vocabulary.digest) && self.sees(&vocabulary.digest) {
447 return Ok(vec![Message::VocabAccept { digest: vocabulary.digest }]);
448 }
449 if self.held.values().any(|h| {
450 h.vocabulary.id().as_str() == vocabulary.id && h.vocabulary.version().to_string() == vocabulary.version && h.vocabulary.integrity.as_ref().is_none_or(|i| i.digest != vocabulary.digest)
451 }) {
452 return Ok(refuse(
457 ErrorCode::VocabularyConflict,
458 format!("{} {} is held here with different content", vocabulary.id, vocabulary.version),
459 ));
460 }
461 if !self.engine.registry().algorithm_names().contains(&vocabulary.algorithm) {
462 return Ok(refuse(ErrorCode::UnsupportedAlgorithm, format!("algorithm {:?} is not available here", vocabulary.algorithm)));
463 }
464 if !self.policy.accept_vocabularies {
465 return Ok(refuse(ErrorCode::Refused, "this peer does not take vocabularies from the other side"));
466 }
467 if vocabulary.tokens > self.policy.max_vocabulary_tokens {
468 return Ok(refuse(ErrorCode::TooLarge, format!("vocabularies above {} tokens are not taken", self.policy.max_vocabulary_tokens)));
469 }
470 if let Some(refusal) = self.over_budget(vocabulary.tokens) {
471 return Ok(refusal);
472 }
473 let digest = vocabulary.digest.clone();
474 self.wanted = Some(vocabulary);
475 Ok(vec![Message::VocabRequest { digest }])
476 }
477 Message::VocabRequest { digest } => {
478 if !self.policy.give_vocabularies {
479 return Ok(refuse(ErrorCode::Refused, "this peer does not give out vocabularies"));
480 }
481 let kvf = kute::vocab::to_vec(&self.usable(&digest)?.vocabulary)?;
482 Ok(vec![Message::VocabData { digest, kvf }])
483 }
484 Message::VocabData { digest, kvf } => {
485 let Some(wanted) = self.wanted.take().filter(|w| w.digest == digest) else {
486 return Ok(refuse(ErrorCode::OutOfOrder, "vocabulary data that was not requested"));
487 };
488 let vocabulary = kute::vocab::from_slice(&kvf)?;
489 if vocabulary.compute_digest()? != digest || VocabRef::of(&vocabulary)? != wanted {
492 return Ok(refuse(ErrorCode::Invalid, "the vocabulary sent is not the one announced"));
493 }
494 if vocabulary.len() as u64 > self.policy.max_vocabulary_tokens {
495 return Ok(refuse(ErrorCode::TooLarge, "vocabulary exceeds the token limit"));
496 }
497 if let Some(refusal) = self.over_budget(vocabulary.len() as u64) {
499 return Ok(refusal);
500 }
501 let report = self.engine.verify(&vocabulary)?;
502 if !report.ok() {
503 return Ok(refuse(ErrorCode::Invalid, format!("the vocabulary fails its own test vectors: {}", report.failures.join("; "))));
504 }
505 let digest = self.add_vocabulary(vocabulary)?;
506 self.show(&digest);
507 Ok(vec![Message::VocabAccept { digest }])
508 }
509 Message::SymbolQuery { digest, symbols } => {
510 if !self.policy.answer_queries {
511 return Ok(refuse(ErrorCode::Refused, "this peer does not answer questions about its vocabularies"));
512 }
513 let payload = TokenPayload::Symbols(symbols);
514 let token_id = self.usable(&digest)?.vocabulary.tokens.iter().find(|t| t.payload == payload).map(|t| t.id);
515 Ok(vec![Message::SymbolInfo { digest, token_id, content_hash: payload.content_hash() }])
516 }
517 Message::SymbolPropose { digest, additions, version, rule } => {
518 if !self.policy.accept_proposals {
519 return Ok(refuse(ErrorCode::Refused, "this peer does not accept vocabulary proposals"));
520 }
521 if rule != EVOLUTION_RULE {
524 return Ok(refuse(
525 ErrorCode::UnsupportedRule,
526 format!("the proposal uses evolution rule {rule:?}; this peer implements {EVOLUTION_RULE:?}"),
527 ));
528 }
529 let most: u64 = additions.iter().map(|a| 2 * a.len() as u64).sum();
531 let parent = self.usable(&digest)?.vocabulary.len() as u64;
532 if parent.saturating_add(most) > self.policy.max_vocabulary_tokens {
533 return Ok(refuse(ErrorCode::TooLarge, "the proposal would pass the vocabulary token limit"));
534 }
535 if let Some(refusal) = self.over_budget(parent.saturating_add(most)) {
536 return Ok(refusal);
537 }
538 let digest = match self.evolve(&digest, &additions, &version) {
543 Ok(digest) => digest,
544 Err(KuteError::VocabularyMismatch(why)) => return Ok(refuse(ErrorCode::VocabularyConflict, why)),
545 Err(e) => return Err(e),
546 };
547 self.show(&digest);
548 Ok(vec![Message::VocabAccept { digest }])
549 }
550 Message::Translate { id, container, to_digest } => {
551 if !self.policy.translate {
552 return Ok(refuse(ErrorCode::Refused, "this peer does not translate for the other side"));
553 }
554 let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
557 self.usable(&sequence.vocabulary_digest)?;
558 self.usable(&to_digest)?;
559 let translated = self.translate(&sequence, &to_digest)?;
560 Ok(vec![Message::EncodedMessage { id, container: translated.to_bytes_compressed()? }])
561 }
562 Message::EncodedMessage { id, container } => {
563 let fingerprint = sha256_hex(&container);
567 if let Some((_, first, receipt)) = self.seen.iter().find(|(seen, _, _)| *seen == id) {
568 return Ok(if *first == fingerprint {
569 vec![receipt.clone()]
570 } else {
571 refuse(ErrorCode::Invalid, format!("message id {id} was already used for different content"))
572 });
573 }
574 if self.inbox.len() as u64 >= self.policy.max_inbox_messages {
575 return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} messages, its limit", self.inbox.len())));
576 }
577 let sequence = TokenSequence::from_bytes_bounded(&container, self.token_limit())?;
578 let held = self.usable(&sequence.vocabulary_digest)?;
579 let units = kute::decoded_units(&held.vocabulary, &sequence)?;
580 let bytes = self.engine.decode_raw_within(held.tokenizer.as_ref(), &sequence, self.policy.max_decoded_units, self.policy.max_inbox_bytes)?;
581 let kept = (bytes.len() as u64).saturating_add(4 * sequence.ids.len() as u64).saturating_add(container.len() as u64);
584 if self.inbox_bytes.saturating_add(kept) > self.policy.max_inbox_bytes {
585 return Ok(refuse(ErrorCode::Busy, format!("the inbox holds {} bytes and takes at most {}", self.inbox_bytes, self.policy.max_inbox_bytes)));
586 }
587 let receipt = Message::Ack { id, units, sha256: sha256_hex(&bytes) };
588 self.inbox_bytes += kept;
589 self.inbox.push(Delivered { id, sequence, bytes });
590 self.seen.push_back((id, fingerprint, receipt.clone()));
591 while self.seen.len() as u64 > self.policy.replay_window {
592 self.seen.pop_front();
593 }
594 Ok(vec![receipt])
595 }
596 Message::VocabAccept { .. } | Message::SymbolInfo { .. } | Message::Ack { .. } | Message::Error { .. } => {
597 Ok(refuse(ErrorCode::OutOfOrder, "a reply arrived where a request was expected"))
598 }
599 Message::Hello { .. } | Message::Capabilities { .. } => Ok(refuse(ErrorCode::OutOfOrder, "the handshake is already complete")),
600 }
601 }
602}
603
604pub trait Transport {
606 fn send(&mut self, message: &Message) -> Result<()>;
607 fn recv(&mut self) -> Result<Option<Message>>;
609}
610
611pub struct Framed<S: Read + Write> {
614 stream: S,
615 max_frame: u64,
616}
617
618impl<S: Read + Write> Framed<S> {
619 pub fn new(stream: S, max_frame: u64) -> Self {
620 Self { stream, max_frame: max_frame.min(DEFAULT_MAX_FRAME) }
621 }
622}
623
624impl<S: Read + Write> Transport for Framed<S> {
625 fn send(&mut self, message: &Message) -> Result<()> {
626 let body = serde_json::to_vec(message)?;
627 if body.len() as u64 > self.max_frame {
628 return Err(KuteError::LimitExceeded(format!("message of {} bytes exceeds the frame limit of {}", body.len(), self.max_frame)));
629 }
630 self.stream.write_all(&(body.len() as u32).to_le_bytes())?;
631 self.stream.write_all(&body)?;
632 self.stream.flush()?;
633 Ok(())
634 }
635
636 fn recv(&mut self) -> Result<Option<Message>> {
637 let mut length = [0u8; 4];
638 let mut got = 0;
639 while got < 4 {
640 match self.stream.read(&mut length[got..]) {
641 Ok(0) if got == 0 => return Ok(None),
642 Ok(0) => return Err(KuteError::InvalidInput("the stream ended inside a frame header".into())),
643 Ok(n) => got += n,
644 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
645 Err(e) => return Err(e.into()),
646 }
647 }
648 let length = u32::from_le_bytes(length) as u64;
649 if length > self.max_frame {
650 return Err(KuteError::LimitExceeded(format!("incoming frame of {length} bytes exceeds the limit of {}", self.max_frame)));
651 }
652 let mut body = Vec::new();
655 (&mut self.stream).take(length).read_to_end(&mut body)?;
656 if body.len() as u64 != length {
657 return Err(KuteError::InvalidInput("the stream ended inside a frame".into()));
658 }
659 serde_json::from_slice(&body).map(Some).map_err(|e| KuteError::InvalidInput(format!("not a protocol message: {e}")))
660 }
661}
662
663#[derive(Clone, Debug, PartialEq, Eq)]
665pub struct Remote {
666 pub peer: String,
667 pub software: String,
668 pub algorithms: Vec<String>,
669 pub accepts_vocabularies: bool,
670 pub accepts_proposals: bool,
671 pub evolution_rules: Vec<String>,
672}
673
674fn peer_error(code: ErrorCode, message: String) -> KuteError {
675 KuteError::Backend(format!("the peer answered {code:?}: {message}"))
676}
677
678pub struct Session<T: Transport> {
680 pub peer: Peer,
681 transport: T,
682 next_id: u64,
683 remote: Option<Remote>,
684}
685
686impl<T: Transport> Session<T> {
687 pub fn new(peer: Peer, transport: T) -> Self {
688 Self { peer, transport, next_id: 1, remote: None }
689 }
690
691 fn ask(&mut self, message: &Message) -> Result<Message> {
692 self.transport.send(message)?;
693 match self.transport.recv()? {
694 Some(Message::Error { code, message }) => Err(peer_error(code, message)),
695 Some(reply) => Ok(reply),
696 None => Err(KuteError::Backend("the peer closed the connection".into())),
697 }
698 }
699
700 fn unexpected<R>(reply: Message) -> Result<R> {
701 Err(KuteError::Backend(format!("unexpected reply from the peer: {reply:?}")))
702 }
703
704 pub fn connect(&mut self) -> Result<Remote> {
706 let (peer, software) = match self.ask(&self.peer.hello())? {
707 Message::Hello { protocol, peer, software } if protocol == PROTOCOL_VERSION => (peer, software),
708 other => return Self::unexpected(other),
709 };
710 match self.ask(&self.peer.capabilities())? {
711 Message::Capabilities { algorithms, accepts_vocabularies, accepts_proposals, evolution_rules, .. } => {
712 let remote = Remote { peer, software, algorithms, accepts_vocabularies, accepts_proposals, evolution_rules };
713 self.remote = Some(remote.clone());
714 Ok(remote)
715 }
716 other => Self::unexpected(other),
717 }
718 }
719
720 pub fn share(&mut self, digest: &str) -> Result<bool> {
723 let vocabulary = VocabRef::of(&self.peer.hold(digest)?.vocabulary)?;
724 match self.ask(&Message::VocabAnnounce { vocabulary })? {
725 Message::VocabAccept { digest: d } if d == digest => Ok(false),
726 Message::VocabRequest { digest: d } if d == digest => {
727 let kvf = kute::vocab::to_vec(&self.peer.hold(digest)?.vocabulary)?;
728 match self.ask(&Message::VocabData { digest: digest.to_string(), kvf })? {
729 Message::VocabAccept { digest: d } if d == digest => Ok(true),
730 other => Self::unexpected(other),
731 }
732 }
733 other => Self::unexpected(other),
734 }
735 }
736
737 pub fn send(&mut self, digest: &str, raw: &[u8], policy: UnknownPolicy) -> Result<u64> {
741 let id = self.next_id;
742 self.next_id += 1;
743 let (message, expected) = self.peer.encode_message(id, digest, raw, policy)?;
744 match self.ask(&message)? {
745 Message::Ack { id: acked, units, sha256 } if acked == id => {
746 if sha256 != expected {
747 return Err(KuteError::Integrity("the peer decoded the message to different content".into()));
748 }
749 Ok(units)
750 }
751 other => Self::unexpected(other),
752 }
753 }
754
755 pub fn propose(&mut self, digest: &str, additions: &[Vec<String>], version: &str) -> Result<String> {
759 if let Some(remote) = &self.remote {
760 if !remote.evolution_rules.iter().any(|r| r == EVOLUTION_RULE) {
761 return Err(KuteError::Unsupported(format!(
762 "the peer implements evolution rules {:?}, not {EVOLUTION_RULE:?}; a proposal would derive different vocabularies on the two sides",
763 remote.evolution_rules
764 )));
765 }
766 }
767 let parsed = Version::parse(version).map_err(|e| KuteError::InvalidIdentifier(format!("version {version:?}: {e}")))?;
768 let child = kute::bpe::sequence::evolve(&self.peer.hold(digest)?.vocabulary, additions, parsed)?;
769 let expected = child.digest()?;
770 let propose = Message::SymbolPropose {
771 digest: digest.to_string(),
772 additions: additions.to_vec(),
773 version: version.to_string(),
774 rule: EVOLUTION_RULE.to_string(),
775 };
776 match self.ask(&propose)? {
777 Message::VocabAccept { digest: theirs } if theirs == expected => self.peer.add_vocabulary(child),
778 Message::VocabAccept { digest: theirs } => {
779 Err(KuteError::Integrity(format!("the peer derived {theirs}, this side derived {expected}")))
780 }
781 other => Self::unexpected(other),
782 }
783 }
784
785 pub fn query(&mut self, digest: &str, symbols: &[String]) -> Result<Option<u32>> {
787 match self.ask(&Message::SymbolQuery { digest: digest.to_string(), symbols: symbols.to_vec() })? {
788 Message::SymbolInfo { token_id, .. } => Ok(token_id),
789 other => Self::unexpected(other),
790 }
791 }
792
793 pub fn translate(&mut self, sequence: &TokenSequence, to_digest: &str) -> Result<TokenSequence> {
796 let id = self.next_id;
797 self.next_id += 1;
798 let ask = Message::Translate { id, container: sequence.to_bytes_compressed()?, to_digest: to_digest.to_string() };
799 match self.ask(&ask)? {
800 Message::EncodedMessage { id: got, container } if got == id => {
801 let translated = TokenSequence::from_bytes(&container)?;
802 if translated.vocabulary_digest != to_digest {
803 return Err(KuteError::Integrity("the peer translated to a different vocabulary".into()));
804 }
805 Ok(translated)
806 }
807 other => Self::unexpected(other),
808 }
809 }
810
811 pub fn serve(&mut self) -> Result<u64> {
814 let mut handled = 0;
815 while let Some(message) = self.transport.recv()? {
816 for reply in self.peer.handle(message) {
817 self.transport.send(&reply)?;
818 }
819 handled += 1;
820 }
821 Ok(handled)
822 }
823}