1use std::collections::BTreeMap;
9
10use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
11use serde::{Deserialize, Serialize};
12use serde_json::{Map, Value};
13
14use super::address::{Address, is_worker_id};
15
16pub const BUS_SCHEMA: &str = "leanctx.hive.bus/v2";
17pub const CONTROL_DOMAIN: &str = "leanctx.hive.control.v1\n";
18const TEXT_MAX: usize = 4000;
19const REFS_MAX: usize = 10;
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum MessageType {
25 Question,
26 Offer,
27 Handoff,
28 Finding,
29 Answer,
30 Need,
31 Claim,
32 Progress,
33 Result,
34}
35
36impl MessageType {
37 pub fn parse(s: &str) -> Option<Self> {
38 serde_json::from_value(Value::String(s.to_string())).ok()
39 }
40
41 pub fn in_phase_a(self) -> bool {
44 matches!(
45 self,
46 Self::Question
47 | Self::Answer
48 | Self::Finding
49 | Self::Offer
50 | Self::Handoff
51 | Self::Progress
52 )
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct Ref {
59 pub kind: RefKind,
60 #[serde(rename = "ref")]
61 pub target: String,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(rename_all = "snake_case")]
66pub enum RefKind {
67 Node,
68 Msg,
69 File,
70 Commit,
71 Url,
72 Test,
73}
74
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
77pub struct Publish {
78 pub schema: String,
79 pub client_msg_id: String,
80 pub to: String,
81 #[serde(rename = "type")]
82 pub kind: MessageType,
83 pub worker_id: String,
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub thread_id: Option<String>,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub reply_to: Option<String>,
88 #[serde(default, skip_serializing_if = "Vec::is_empty")]
89 pub refs: Vec<Ref>,
90 pub body: Value,
91 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub ck_wrapped: Option<String>,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub epoch: Option<u32>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
98 pub about: Option<About>,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
100 pub counts: Option<CollabCounts>,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub window: Option<Window>,
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
106#[serde(rename_all = "snake_case")]
107pub enum About {
108 Collaboration,
109}
110
111#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(deny_unknown_fields)]
115pub struct CollabCounts {
116 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub registration_renewed: Option<u32>,
118 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub wait_timeout: Option<u32>,
120 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub merge_conflict: Option<u32>,
122 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub claim_refused: Option<u32>,
124 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub claim_expired: Option<u32>,
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub gate_reruns: Option<u32>,
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub agent_seconds: Option<u32>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub idle_seconds: Option<u32>,
132}
133
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
135#[serde(deny_unknown_fields)]
136pub struct Window {
137 pub from_ms: u64,
138 pub to_ms: u64,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct Invalid(pub String);
144
145impl std::fmt::Display for Invalid {
146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147 write!(f, "invalid_message: {}", self.0)
148 }
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
155#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
156pub enum Sender {
157 Worker {
158 worker_id: String,
159 name: String,
160 owner_handle: String,
161 host_app: String,
162 },
163 Person {
164 handle: String,
165 },
166 System,
167}
168
169pub fn sender_of(message: &Value) -> Result<Sender, Invalid> {
171 let sender = message.get("sender").ok_or(Invalid("sender".into()))?;
172 let parsed: Sender =
173 serde_json::from_value(sender.clone()).map_err(|e| Invalid(format!("sender: {e}")))?;
174 if let Sender::Worker { worker_id, .. } = &parsed
175 && !is_worker_id(worker_id)
176 {
177 return Err(Invalid("sender.worker_id".into()));
178 }
179 Ok(parsed)
180}
181
182fn bad(why: impl Into<String>) -> Invalid {
183 Invalid(why.into())
184}
185
186fn chars(value: &Value, field: &str, min: usize, max: usize) -> Result<(), Invalid> {
187 let n = value[field]
188 .as_str()
189 .ok_or_else(|| bad(format!("{field} is required")))?
190 .chars()
191 .count();
192 if (min..=max).contains(&n) {
193 Ok(())
194 } else {
195 Err(bad(format!("{field} must be {min} to {max} characters")))
196 }
197}
198
199fn opt_chars(value: &Value, field: &str, min: usize, max: usize) -> Result<(), Invalid> {
200 if value.get(field).is_some() {
201 chars(value, field, min, max)
202 } else {
203 Ok(())
204 }
205}
206
207fn int(value: &Value, field: &str, min: u64, max: u64, required: bool) -> Result<(), Invalid> {
208 match value.get(field) {
209 None if !required => Ok(()),
210 None => Err(bad(format!("{field} is required"))),
211 Some(v) => v
212 .as_u64()
213 .filter(|n| (min..=max).contains(n))
214 .map(|_| ())
215 .ok_or_else(|| bad(format!("{field} must be an integer {min} to {max}"))),
216 }
217}
218
219fn worker(value: &Value, field: &str, required: bool) -> Result<(), Invalid> {
220 match value.get(field) {
221 None if !required => Ok(()),
222 Some(Value::String(id)) if is_worker_id(id) => Ok(()),
223 _ => Err(bad(format!("{field} must be a worker id"))),
224 }
225}
226
227fn only(body: &Map<String, Value>, allowed: &[&str]) -> Result<(), Invalid> {
228 match body.keys().find(|k| !allowed.contains(&k.as_str())) {
229 Some(extra) => Err(bad(format!("unknown body field {extra}"))),
230 None => Ok(()),
231 }
232}
233
234fn check_body(kind: MessageType, body: &Value) -> Result<(), Invalid> {
236 let map = body
237 .as_object()
238 .ok_or_else(|| bad("body must be an object"))?;
239 match kind {
240 MessageType::Question => {
241 only(map, &["text", "to_worker", "deadline"])?;
242 chars(body, "text", 1, TEXT_MAX)?;
243 worker(body, "to_worker", false)?;
244 int(body, "deadline", 0, u64::MAX, false)
245 }
246 MessageType::Offer => {
247 only(map, &["what", "capability", "eta_minutes", "withdraw"])?;
248 chars(body, "what", 1, 1000)?;
249 chars(body, "capability", 1, 64)?;
250 int(body, "eta_minutes", 1, 10_080, true)?;
251 match body.get("withdraw") {
252 None | Some(Value::Bool(_)) => Ok(()),
253 _ => Err(bad("withdraw must be true or false")),
254 }
255 }
256 MessageType::Handoff => {
257 only(map, &["to_worker", "resource", "note", "lease_id"])?;
258 worker(body, "to_worker", true)?;
259 chars(body, "resource", 1, 200)?;
260 opt_chars(body, "note", 1, 1000)?;
261 lease(body, false)
262 }
263 MessageType::Finding => {
264 only(map, &["statement", "evidence"])?;
265 chars(body, "statement", 24, 300)?;
266 match body["evidence"].as_str() {
267 Some("observed" | "stated" | "imported") => Ok(()),
268 _ => Err(bad("evidence must be observed, stated or imported")),
269 }
270 }
271 MessageType::Answer => {
272 only(map, &["text", "accept"])?;
273 chars(body, "text", 1, TEXT_MAX)?;
274 match body.get("accept") {
275 None | Some(Value::Bool(_)) => Ok(()),
276 _ => Err(bad("accept must be true or false")),
277 }
278 }
279 MessageType::Need => {
280 only(map, &["text", "capabilities", "budget_hint", "expires_at"])?;
281 chars(body, "text", 1, 1000)?;
282 let caps = body["capabilities"]
283 .as_array()
284 .ok_or_else(|| bad("capabilities is required"))?;
285 if !(1..=5).contains(&caps.len())
286 || caps.iter().any(|c| {
287 c.as_str()
288 .is_none_or(|c| c.is_empty() || c.chars().count() > 64)
289 })
290 {
291 return Err(bad("capabilities must name 1 to 5 tools or hosts"));
292 }
293 if let Some(hint) = body.get("budget_hint") {
294 let hint_map = hint
295 .as_object()
296 .ok_or_else(|| bad("budget_hint must be an object"))?;
297 only(hint_map, &["tasks", "usd_cents"])?;
298 int(hint, "tasks", 1, 50, false)?;
299 int(hint, "usd_cents", 0, 50_000, false)?;
300 }
301 int(body, "expires_at", 0, u64::MAX, false)
302 }
303 MessageType::Claim => {
304 only(map, &["resource", "lease_id"])?;
305 chars(body, "resource", 1, 200)?;
306 lease(body, true)
307 }
308 MessageType::Progress => {
309 only(map, &["percentage", "step", "usage", "goal"])?;
310 if map.get("percentage").is_none() && map.get("step").is_none() {
311 return Err(bad("progress needs percentage or step"));
312 }
313 int(body, "percentage", 0, 100, false)?;
314 opt_chars(body, "step", 1, 300)
315 }
316 MessageType::Result => {
317 only(map, &["summary", "artefacts", "goal"])?;
318 chars(body, "summary", 1, 1000)?;
319 match body["artefacts"].as_array() {
320 Some(a) if a.len() <= 20 => Ok(()),
321 _ => Err(bad("artefacts must be a list of at most 20")),
322 }
323 }
324 }
325}
326
327fn lease(body: &Value, required: bool) -> Result<(), Invalid> {
328 match body.get("lease_id") {
329 None if !required => Ok(()),
330 Some(Value::String(id))
331 if id.strip_prefix("bl_").is_some_and(|r| {
332 (1..=40).contains(&r.len())
333 && r.bytes()
334 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
335 }) =>
336 {
337 Ok(())
338 }
339 _ => Err(bad("lease_id must be bl_<id>")),
340 }
341}
342
343fn is_msg_id(s: &str) -> bool {
344 s.strip_prefix("msg_").is_some_and(|r| {
345 r.len() == 16
346 && r.bytes()
347 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
348 })
349}
350
351impl Publish {
352 pub fn validate(&self) -> Result<(), Invalid> {
355 if self.schema != BUS_SCHEMA {
356 return Err(bad("schema"));
357 }
358 if !is_ulid(&self.client_msg_id) {
359 return Err(bad("client_msg_id must be a ULID"));
360 }
361 match Address::parse(Some(&self.to)) {
362 Ok(a) if a.is_remote() => {}
363 _ => return Err(bad("to must be #<ws>/<vault>, ~<swarm> or @wkr_<id>")),
364 }
365 if !is_worker_id(&self.worker_id) {
366 return Err(bad("worker_id"));
367 }
368 for id in [&self.thread_id, &self.reply_to].into_iter().flatten() {
369 if !is_msg_id(id) {
370 return Err(bad("thread_id and reply_to must be msg_ ids"));
371 }
372 }
373 if self.refs.len() > REFS_MAX
374 || self
375 .refs
376 .iter()
377 .any(|r| r.target.is_empty() || r.target.chars().count() > 500)
378 {
379 return Err(bad("refs: at most 10, each 1 to 500 characters"));
380 }
381 let sealed = self.body.get("sealed").is_some();
382 let collaboration = self.about.is_some();
383 if collaboration {
384 if self.kind != MessageType::Finding {
385 return Err(bad("about: collaboration is for findings only"));
386 }
387 if sealed {
388 return Err(bad("collaboration counts never go to a sealed place"));
389 }
390 if self.counts.is_none() || self.window.is_none() {
391 return Err(bad("a collaboration finding needs counts and window"));
392 }
393 } else if self.counts.is_some() || self.window.is_some() {
394 return Err(bad("counts and window need about: collaboration"));
395 }
396 if self.kind == MessageType::Finding && self.refs.is_empty() && !collaboration {
397 return Err(bad("a finding needs at least one ref"));
398 }
399 if self.kind == MessageType::Answer && self.reply_to.is_none() {
400 return Err(bad("an answer needs reply_to"));
401 }
402 match (sealed, &self.ck_wrapped, self.epoch) {
403 (true, Some(ck), Some(_)) => {
404 let len_ok = ck.len() == 96
405 && ck
406 .bytes()
407 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
408 if !len_ok {
409 return Err(bad("ck_wrapped"));
410 }
411 Ok(())
412 }
413 (true, _, _) => Err(bad("a sealed body needs ck_wrapped and epoch")),
414 (false, None, None) => check_body(self.kind, &self.body),
415 (false, _, _) => Err(bad("key material on a plain place")),
416 }
417 }
418}
419
420pub fn is_ulid(s: &str) -> bool {
422 s.len() == 26
423 && s.bytes().all(|b| {
424 b.is_ascii_digit()
425 || (b.is_ascii_uppercase() && !matches!(b, b'I' | b'L' | b'O' | b'U'))
426 })
427}
428
429pub fn new_ulid(now_ms: u64) -> String {
431 let mut random = [0u8; 10];
432 let _ = getrandom::fill(&mut random);
433 ulid_of(now_ms, random)
434}
435
436pub fn ulid_for(at_ms: u64, seed: &str) -> String {
440 let digest = blake3::hash(seed.as_bytes());
441 let mut bits = [0u8; 10];
442 bits.copy_from_slice(&digest.as_bytes()[..10]);
443 ulid_of(at_ms, bits)
444}
445
446fn ulid_of(ms: u64, low: [u8; 10]) -> String {
447 const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
448 let mut value: u128 = u128::from(ms & 0xFFFF_FFFF_FFFF) << 80;
449 for (i, byte) in low.iter().enumerate() {
450 value |= u128::from(*byte) << (8 * (9 - i));
451 }
452 (0..26)
453 .rev()
454 .map(|i| ALPHABET[((value >> (5 * i)) & 31) as usize] as char)
455 .collect()
456}
457
458#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
460#[serde(deny_unknown_fields)]
461pub struct Control {
462 pub id: String,
463 pub place: String,
464 pub target: ControlTarget,
465 #[serde(default, skip_serializing_if = "Option::is_none")]
466 pub worker_id: Option<String>,
467 #[serde(default, rename = "ref", skip_serializing_if = "Option::is_none")]
468 pub target_ref: Option<ControlRef>,
469 pub action: ControlAction,
470 pub reason: String,
471 pub issued_by: IssuedBy,
472 pub created_at: u64,
473 #[serde(default, skip_serializing_if = "Option::is_none")]
474 pub lifted_at: Option<u64>,
475 pub key_id: String,
476 pub signature: String,
477}
478
479#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
480#[serde(rename_all = "snake_case")]
481pub enum ControlTarget {
482 Worker,
483 Bus,
484}
485
486#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
487#[serde(rename_all = "snake_case")]
488pub enum ControlAction {
489 Hold,
490 Stop,
491 Resume,
492 Veto,
493}
494
495#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
496#[serde(deny_unknown_fields)]
497pub struct ControlRef {
498 pub kind: String,
499 pub id: String,
500}
501
502#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
503#[serde(deny_unknown_fields)]
504pub struct IssuedBy {
505 pub kind: String,
506 pub user_id: String,
507 #[serde(default, skip_serializing_if = "Option::is_none")]
510 pub label: Option<String>,
511}
512
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
515pub enum ControlRejection {
516 Invalid,
519 SigInvalid,
521}
522
523pub type ControlKeys = BTreeMap<String, VerifyingKey>;
526
527impl Control {
528 pub fn verify(&self, lifted: bool, keys: &ControlKeys) -> Result<(), ControlRejection> {
532 let shape_ok = (self.target == ControlTarget::Worker) == self.worker_id.is_some()
533 && (self.action != ControlAction::Veto || self.target_ref.is_some())
534 && lifted == self.lifted_at.is_some()
535 && (2..=500).contains(&self.reason.chars().count())
536 && self.issued_by.kind == "person";
537 if !shape_ok {
538 return Err(ControlRejection::Invalid);
539 }
540 let key = keys.get(&self.key_id).ok_or(ControlRejection::SigInvalid)?;
541 let value = serde_json::to_value(self).map_err(|_| ControlRejection::Invalid)?;
542 let input =
543 lean_ctx_protocol::hive::signing_input_without_signature(CONTROL_DOMAIN, &value)
544 .map_err(|_| ControlRejection::Invalid)?;
545 let mut sig = [0u8; 64];
546 hex::decode_to_slice(&self.signature, &mut sig)
547 .map_err(|_| ControlRejection::SigInvalid)?;
548 key.verify(&input, &Signature::from_bytes(&sig))
549 .map_err(|_| ControlRejection::SigInvalid)
550 }
551}
552
553#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
555#[serde(rename_all = "snake_case")]
556pub enum PresenceState {
557 Active,
558 Idle,
559 Held,
560}
561
562#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
563#[serde(deny_unknown_fields)]
564pub struct PresenceEntry {
565 pub worker_id: String,
566 pub role: String,
567 pub state: PresenceState,
568}
569
570#[derive(Debug, Clone, PartialEq)]
572pub enum Inbound {
573 HelloAck(Value),
574 Stored {
575 client_msg_id: String,
576 id: String,
577 seq: u64,
578 thread_id: String,
579 },
580 Deliver(Value),
581 Presence {
582 address: String,
583 worker_id: String,
584 role: String,
585 state: PresenceState,
586 at: u64,
587 },
588 Control {
589 lifted: bool,
590 control: Box<Control>,
591 },
592 PlaceDenied {
593 place: String,
594 code: String,
595 },
596 Resync {
597 place: String,
598 },
599 Error {
600 client_msg_id: Option<String>,
601 code: String,
602 reason: Option<String>,
603 quota: Option<Box<Value>>,
607 },
608 Ping,
609 ConsentAnswered {
611 consent_id: String,
612 },
613 Other(String),
614}
615
616fn quota_fields(frame: &Value) -> Option<Box<Value>> {
620 let mut out = serde_json::Map::new();
621 for (field, string) in [
622 ("resource", true),
623 ("reset_at", true),
624 ("limit", false),
625 ("used", false),
626 ("retry_after_s", false),
627 ] {
628 let value = &frame[field];
629 if field == "retry_after_s" {
630 if let Some(s) = value.as_u64() {
632 let capped = s.min(crate::core::hive::error::RETRY_AFTER_CAP_S);
633 out.insert(field.to_string(), Value::from(capped));
634 }
635 } else if (string && value.is_string()) || (!string && value.is_u64()) {
636 out.insert(field.to_string(), value.clone());
637 }
638 }
639 (!out.is_empty()).then(|| Box::new(Value::Object(out)))
640}
641
642pub fn parse_frame(text: &str) -> Result<Inbound, Invalid> {
644 let value: Value = serde_json::from_str(text).map_err(|e| bad(format!("frame: {e}")))?;
645 let t = value["t"]
646 .as_str()
647 .ok_or_else(|| bad("frame without t"))?
648 .to_string();
649 let s = |field: &str| -> Result<String, Invalid> {
650 value[field]
651 .as_str()
652 .map(str::to_string)
653 .ok_or_else(|| bad(format!("{t}: {field}")))
654 };
655 let n = |field: &str| -> Result<u64, Invalid> {
656 value[field]
657 .as_u64()
658 .ok_or_else(|| bad(format!("{t}: {field}")))
659 };
660 Ok(match t.as_str() {
661 "hello.ack" => Inbound::HelloAck(value),
662 "message.stored" => Inbound::Stored {
663 client_msg_id: s("client_msg_id")?,
664 id: s("id")?,
665 seq: n("seq")?,
666 thread_id: s("thread_id")?,
667 },
668 "message.deliver" => Inbound::Deliver(value),
669 "presence.update" => Inbound::Presence {
670 address: s("address")?,
671 worker_id: s("worker_id")?,
672 role: s("role")?,
673 state: serde_json::from_value(value["state"].clone())
674 .map_err(|_| bad("presence.update: state"))?,
675 at: n("at")?,
676 },
677 "control" => {
678 let lifted = match value["state"].as_str() {
679 Some("issued") => false,
680 Some("lifted") => true,
681 _ => return Err(bad("control: state")),
682 };
683 let control = serde_json::from_value(value["control"].clone())
684 .map_err(|e| bad(format!("control: {e}")))?;
685 Inbound::Control { lifted, control }
686 }
687 "place.denied" => Inbound::PlaceDenied {
688 place: s("place")?,
689 code: s("code")?,
690 },
691 "resync" => Inbound::Resync { place: s("place")? },
692 "error" => Inbound::Error {
693 client_msg_id: value["client_msg_id"].as_str().map(str::to_string),
694 code: s("code")?,
695 reason: value["reason"].as_str().map(str::to_string),
696 quota: quota_fields(&value),
697 },
698 "ping" => Inbound::Ping,
699 "consent.answered" => Inbound::ConsentAnswered {
700 consent_id: s("consent_id")?,
701 },
702 _ => Inbound::Other(t),
703 })
704}
705
706#[cfg(test)]
707#[path = "v2_tests.rs"]
708mod tests;