Skip to main content

lean_ctx_cloud/bus/
v2.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Bus v2 wire shapes the engine sends and reads (C0 2.0 section 3,
3//! `bus.schema.json`; SPEC-ENGINE §3.7): typed messages on vault buses,
4//! Cloud-signed controls and presence.
5//!
6//! Network-free: the relay builds and checks these, the socket moves them.
7
8use std::collections::BTreeMap;
9
10use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};
11use serde::{Deserialize, Serialize};
12use serde_json::{Map, Value};
13
14use super::address::{is_wire_address, is_worker_id};
15
16pub const BUS_SCHEMA: &str = "leanctx.cloud.bus/v2";
17pub const CONTROL_DOMAIN: &str = "leanctx.cloud.control.v1\n";
18/// The most characters of a question's or an answer's text.
19pub const TEXT_MAX: usize = 4000;
20/// The most characters of an offer's `what` and a handoff's `note`.
21pub const SHORT_TEXT_MAX: usize = 1000;
22const REFS_MAX: usize = 10;
23
24/// The most characters of the field a sending tool puts its text in for
25/// `kind` (question and answer `text`, offer `what`, handoff `note`); `None`
26/// for a finding or progress, whose text is not the sender's free text.
27pub fn text_max(kind: MessageType) -> Option<usize> {
28    match kind {
29        MessageType::Question | MessageType::Answer => Some(TEXT_MAX),
30        MessageType::Offer | MessageType::Handoff => Some(SHORT_TEXT_MAX),
31        MessageType::Finding | MessageType::Progress => None,
32    }
33}
34/// A syntactically valid worker id, used only to validate the other fields
35/// of a person's publish; it is removed before the frame is sent
36/// ([`super::relay_v2`]). The person rules do not apply under it.
37pub(crate) const PERSON_VALIDATION_WORKER: &str = "wkr_personpublishpending";
38
39/// The six message types (C0 2.2): the conversation types and `progress`
40/// as a status line. Work is a task (`ctx_tasks`), never a bus message.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum MessageType {
44    Question,
45    Offer,
46    Handoff,
47    Finding,
48    Answer,
49    Progress,
50}
51
52impl MessageType {
53    pub fn parse(s: &str) -> Option<Self> {
54        serde_json::from_value(Value::String(s.to_string())).ok()
55    }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct Ref {
61    pub kind: RefKind,
62    #[serde(rename = "ref")]
63    pub target: String,
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum RefKind {
69    Node,
70    Msg,
71    File,
72    Commit,
73    Url,
74    Test,
75}
76
77/// E17 body and `place.publish` frame body.
78#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
79pub struct Publish {
80    pub schema: String,
81    pub client_msg_id: String,
82    pub to: String,
83    #[serde(rename = "type")]
84    pub kind: MessageType,
85    pub worker_id: String,
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub thread_id: Option<String>,
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub reply_to: Option<String>,
90    #[serde(default, skip_serializing_if = "Vec::is_empty")]
91    pub refs: Vec<Ref>,
92    pub body: Value,
93    /// Key material of a sealed place: a publish that carries it is
94    /// refused (engines publish to plain places only).
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub ck_wrapped: Option<String>,
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub epoch: Option<u32>,
99    /// `collaboration` marks a friction finding (C0 d072c29): it carries
100    /// plaintext `counts` and a `window` and may have no refs.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub about: Option<About>,
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub counts: Option<CollabCounts>,
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub window: Option<Window>,
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "snake_case")]
111pub enum About {
112    Collaboration,
113}
114
115/// The friction signals of a collaboration finding (`enums/friction-signals.json`);
116/// every key optional, unknown keys refused.
117#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
118#[serde(deny_unknown_fields)]
119pub struct CollabCounts {
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub registration_renewed: Option<u32>,
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub wait_timeout: Option<u32>,
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub merge_conflict: Option<u32>,
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub claim_refused: Option<u32>,
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub claim_expired: Option<u32>,
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub gate_reruns: Option<u32>,
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub agent_seconds: Option<u32>,
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub idle_seconds: Option<u32>,
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(deny_unknown_fields)]
140pub struct Window {
141    pub from_ms: u64,
142    pub to_ms: u64,
143}
144
145/// Why a message may not be published (local refusal, before the wire).
146#[derive(Debug, Clone, PartialEq, Eq)]
147pub struct Invalid(pub String);
148
149impl Invalid {
150    /// The named rule of a person-rule refusal (`approval_on_behalf`, …;
151    /// [`super::person_rules`]), `None` for a shape refusal.
152    pub fn rule(&self) -> Option<&str> {
153        let rest = self.0.split_once("reason: ")?.1;
154        rest.split(':').next()
155    }
156}
157
158impl std::fmt::Display for Invalid {
159    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        write!(f, "invalid_message: {}", self.0)
161    }
162}
163
164/// The C0 `sender` of a stored message. The web-only `place_role` (W36)
165/// never reaches an engine, so a sender carrying it is refused like any
166/// other unknown member.
167#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
168#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
169pub enum Sender {
170    Worker {
171        worker_id: String,
172        name: String,
173        owner_handle: String,
174        host_app: String,
175    },
176    Person {
177        handle: String,
178    },
179    System,
180}
181
182/// The sender of a stored message, refused when it is not the C0 shape.
183pub fn sender_of(message: &Value) -> Result<Sender, Invalid> {
184    let sender = message.get("sender").ok_or(Invalid("sender".into()))?;
185    let parsed: Sender =
186        serde_json::from_value(sender.clone()).map_err(|e| Invalid(format!("sender: {e}")))?;
187    if let Sender::Worker { worker_id, .. } = &parsed
188        && !is_worker_id(worker_id)
189    {
190        return Err(Invalid("sender.worker_id".into()));
191    }
192    // Only a worker's message names a worker; a person's or Cloud's never.
193    if !matches!(parsed, Sender::Worker { .. }) && message.get("worker_id").is_some() {
194        return Err(Invalid("worker_id on a message no worker sent".into()));
195    }
196    Ok(parsed)
197}
198
199fn bad(why: impl Into<String>) -> Invalid {
200    Invalid(why.into())
201}
202
203fn chars(value: &Value, field: &str, min: usize, max: usize) -> Result<(), Invalid> {
204    let n = value[field]
205        .as_str()
206        .ok_or_else(|| bad(format!("{field} is required")))?
207        .chars()
208        .count();
209    if (min..=max).contains(&n) {
210        Ok(())
211    } else {
212        Err(bad(format!("{field} must be {min} to {max} characters")))
213    }
214}
215
216fn opt_chars(value: &Value, field: &str, min: usize, max: usize) -> Result<(), Invalid> {
217    if value.get(field).is_some() {
218        chars(value, field, min, max)
219    } else {
220        Ok(())
221    }
222}
223
224fn int(value: &Value, field: &str, min: u64, max: u64, required: bool) -> Result<(), Invalid> {
225    match value.get(field) {
226        None if !required => Ok(()),
227        None => Err(bad(format!("{field} is required"))),
228        Some(v) => v
229            .as_u64()
230            .filter(|n| (min..=max).contains(n))
231            .map(|_| ())
232            .ok_or_else(|| bad(format!("{field} must be an integer {min} to {max}"))),
233    }
234}
235
236fn worker(value: &Value, field: &str, required: bool) -> Result<(), Invalid> {
237    match value.get(field) {
238        None if !required => Ok(()),
239        Some(Value::String(id)) if is_worker_id(id) => Ok(()),
240        _ => Err(bad(format!("{field} must be a worker id"))),
241    }
242}
243
244fn only(body: &Map<String, Value>, allowed: &[&str]) -> Result<(), Invalid> {
245    match body.keys().find(|k| !allowed.contains(&k.as_str())) {
246        Some(extra) => Err(bad(format!("unknown body field {extra}"))),
247        None => Ok(()),
248    }
249}
250
251/// The engine-sent body of each type (server-set fields are refused).
252fn check_body(kind: MessageType, body: &Value) -> Result<(), Invalid> {
253    let map = body
254        .as_object()
255        .ok_or_else(|| bad("body must be an object"))?;
256    match kind {
257        MessageType::Question => {
258            only(map, &["text", "to_worker", "deadline"])?;
259            chars(body, "text", 1, TEXT_MAX)?;
260            worker(body, "to_worker", false)?;
261            int(body, "deadline", 0, u64::MAX, false)
262        }
263        MessageType::Offer => {
264            only(map, &["what", "capability", "eta_minutes", "withdraw"])?;
265            chars(body, "what", 1, SHORT_TEXT_MAX)?;
266            chars(body, "capability", 1, 64)?;
267            int(body, "eta_minutes", 1, 10_080, true)?;
268            match body.get("withdraw") {
269                None | Some(Value::Bool(_)) => Ok(()),
270                _ => Err(bad("withdraw must be true or false")),
271            }
272        }
273        MessageType::Handoff => {
274            only(map, &["to_worker", "resource", "note", "lease_id"])?;
275            worker(body, "to_worker", true)?;
276            chars(body, "resource", 1, 200)?;
277            opt_chars(body, "note", 1, SHORT_TEXT_MAX)?;
278            lease(body, false)
279        }
280        MessageType::Finding => {
281            only(map, &["statement", "evidence"])?;
282            chars(body, "statement", 24, 300)?;
283            match body["evidence"].as_str() {
284                Some("observed" | "stated" | "imported") => Ok(()),
285                _ => Err(bad("evidence must be observed, stated or imported")),
286            }
287        }
288        MessageType::Answer => {
289            only(map, &["text", "accept"])?;
290            chars(body, "text", 1, TEXT_MAX)?;
291            match body.get("accept") {
292                None | Some(Value::Bool(_)) => Ok(()),
293                _ => Err(bad("accept must be true or false")),
294            }
295        }
296        MessageType::Progress => {
297            only(map, &["percentage", "step", "usage"])?;
298            if map.get("percentage").is_none() && map.get("step").is_none() {
299                return Err(bad("progress needs percentage or step"));
300            }
301            int(body, "percentage", 0, 100, false)?;
302            opt_chars(body, "step", 1, 300)
303        }
304    }
305}
306
307fn lease(body: &Value, required: bool) -> Result<(), Invalid> {
308    match body.get("lease_id") {
309        None if !required => Ok(()),
310        Some(Value::String(id))
311            if id.strip_prefix("bl_").is_some_and(|r| {
312                (1..=40).contains(&r.len())
313                    && r.bytes()
314                        .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
315            }) =>
316        {
317            Ok(())
318        }
319        _ => Err(bad("lease_id must be bl_<id>")),
320    }
321}
322
323fn is_msg_id(s: &str) -> bool {
324    s.strip_prefix("msg_").is_some_and(|r| {
325        r.len() == 16
326            && r.bytes()
327                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
328    })
329}
330
331impl Publish {
332    /// The C0 2.0 rules for an engine publish, plain places only.
333    pub fn validate(&self) -> Result<(), Invalid> {
334        if self.schema != BUS_SCHEMA {
335            return Err(bad("schema"));
336        }
337        if !is_ulid(&self.client_msg_id) {
338            return Err(bad("client_msg_id must be a ULID"));
339        }
340        if !is_wire_address(&self.to) {
341            return Err(bad("to must be #<ws>/<vault>, ~<slug> or @wkr_<id>"));
342        }
343        if !is_worker_id(&self.worker_id) {
344            return Err(bad("worker_id"));
345        }
346        for id in [&self.thread_id, &self.reply_to].into_iter().flatten() {
347            if !is_msg_id(id) {
348                return Err(bad("thread_id and reply_to must be msg_ ids"));
349            }
350        }
351        if self.refs.len() > REFS_MAX
352            || self
353                .refs
354                .iter()
355                .any(|r| r.target.is_empty() || r.target.chars().count() > 500)
356        {
357            return Err(bad("refs: at most 10, each 1 to 500 characters"));
358        }
359        if self.body.get("sealed").is_some() {
360            return Err(bad("sealed bodies are not supported"));
361        }
362        let collaboration = self.about.is_some();
363        if collaboration {
364            if self.kind != MessageType::Finding {
365                return Err(bad("about: collaboration is for findings only"));
366            }
367            if self.counts.is_none() || self.window.is_none() {
368                return Err(bad("a collaboration finding needs counts and window"));
369            }
370        } else if self.counts.is_some() || self.window.is_some() {
371            return Err(bad("counts and window need about: collaboration"));
372        }
373        if self.kind == MessageType::Finding && self.refs.is_empty() && !collaboration {
374            return Err(bad("a finding needs at least one ref"));
375        }
376        if self.kind == MessageType::Answer && self.reply_to.is_none() {
377            return Err(bad("an answer needs reply_to"));
378        }
379        if self.ck_wrapped.is_some() || self.epoch.is_some() {
380            return Err(bad("key material on a plain place"));
381        }
382        // An agent's message never speaks for a person (process v1 §7); a
383        // person's own post (validated under the placeholder worker) may.
384        if self.worker_id != PERSON_VALIDATION_WORKER {
385            super::person_rules::check_agent_body(self.kind, &self.body)?;
386        }
387        check_body(self.kind, &self.body)
388    }
389}
390
391/// Crockford base32 upper, 26 characters (ULID layout).
392pub fn is_ulid(s: &str) -> bool {
393    s.len() == 26
394        && s.bytes().all(|b| {
395            b.is_ascii_digit()
396                || (b.is_ascii_uppercase() && !matches!(b, b'I' | b'L' | b'O' | b'U'))
397        })
398}
399
400/// A new ULID: 48-bit ms time, 80 random bits.
401pub fn new_ulid(now_ms: u64) -> String {
402    let mut random = [0u8; 10];
403    let _ = getrandom::fill(&mut random);
404    ulid_of(now_ms, random)
405}
406
407/// The ULID of one local message: its time and 80 bits of
408/// `blake3(seed)`, so a resend after a reconnect keeps its `client_msg_id`
409/// and Cloud deduplicates it.
410pub fn ulid_for(at_ms: u64, seed: &str) -> String {
411    let digest = blake3::hash(seed.as_bytes());
412    let mut bits = [0u8; 10];
413    bits.copy_from_slice(&digest.as_bytes()[..10]);
414    ulid_of(at_ms, bits)
415}
416
417fn ulid_of(ms: u64, low: [u8; 10]) -> String {
418    const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
419    let mut value: u128 = u128::from(ms & 0xFFFF_FFFF_FFFF) << 80;
420    for (i, byte) in low.iter().enumerate() {
421        value |= u128::from(*byte) << (8 * (9 - i));
422    }
423    (0..26)
424        .rev()
425        .map(|i| ALPHABET[((value >> (5 * i)) & 31) as usize] as char)
426        .collect()
427}
428
429/// Cloud-signed Control (R8).
430#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
431#[serde(deny_unknown_fields)]
432pub struct Control {
433    pub id: String,
434    pub place: String,
435    pub target: ControlTarget,
436    #[serde(default, skip_serializing_if = "Option::is_none")]
437    pub worker_id: Option<String>,
438    #[serde(default, rename = "ref", skip_serializing_if = "Option::is_none")]
439    pub target_ref: Option<ControlRef>,
440    pub action: ControlAction,
441    pub reason: String,
442    pub issued_by: IssuedBy,
443    pub created_at: u64,
444    #[serde(default, skip_serializing_if = "Option::is_none")]
445    pub lifted_at: Option<u64>,
446    pub key_id: String,
447    pub signature: String,
448}
449
450#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
451#[serde(rename_all = "snake_case")]
452pub enum ControlTarget {
453    Worker,
454    Bus,
455}
456
457#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(rename_all = "snake_case")]
459pub enum ControlAction {
460    Hold,
461    Stop,
462    Resume,
463    Veto,
464}
465
466#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
467#[serde(deny_unknown_fields)]
468pub struct ControlRef {
469    pub kind: String,
470    pub id: String,
471}
472
473#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
474#[serde(deny_unknown_fields)]
475pub struct IssuedBy {
476    pub kind: String,
477    pub user_id: String,
478    /// Display name of the issuer (≤ 64; C0 b000ffd), covered by the
479    /// signature like every other member.
480    #[serde(default, skip_serializing_if = "Option::is_none")]
481    pub label: Option<String>,
482}
483
484/// Why a control frame is ignored (counted `sig_invalid` or `invalid`).
485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486pub enum ControlRejection {
487    /// Shape breaks the contract (target/worker_id, veto without ref,
488    /// issued/lifted mismatch).
489    Invalid,
490    /// Unknown key, a key without purpose `control`, or a bad signature.
491    SigInvalid,
492}
493
494/// Cloud keys a control may be signed with: `key_id` → public key of
495/// purpose `control` (from the E13 key set).
496pub type ControlKeys = BTreeMap<String, VerifyingKey>;
497
498impl Control {
499    /// Check shape and signature (`domain ‖ canonical_json(control without
500    /// signature)`, vector `control.vectors.json`). `lifted` is the frame's
501    /// `state == lifted`.
502    pub fn verify(&self, lifted: bool, keys: &ControlKeys) -> Result<(), ControlRejection> {
503        let shape_ok = (self.target == ControlTarget::Worker) == self.worker_id.is_some()
504            && (self.action != ControlAction::Veto || self.target_ref.is_some())
505            && lifted == self.lifted_at.is_some()
506            && (2..=500).contains(&self.reason.chars().count())
507            && self.issued_by.kind == "person";
508        if !shape_ok {
509            return Err(ControlRejection::Invalid);
510        }
511        let key = keys.get(&self.key_id).ok_or(ControlRejection::SigInvalid)?;
512        let value = serde_json::to_value(self).map_err(|_| ControlRejection::Invalid)?;
513        let input =
514            lean_ctx_protocol::cloud::signing_input_without_signature(CONTROL_DOMAIN, &value)
515                .map_err(|_| ControlRejection::Invalid)?;
516        let mut sig = [0u8; 64];
517        hex::decode_to_slice(&self.signature, &mut sig)
518            .map_err(|_| ControlRejection::SigInvalid)?;
519        key.verify(&input, &Signature::from_bytes(&sig))
520            .map_err(|_| ControlRejection::SigInvalid)
521    }
522}
523
524/// Presence of a local worker on one place (SPEC-ENGINE §3.7.3).
525#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
526#[serde(rename_all = "snake_case")]
527pub enum PresenceState {
528    Active,
529    Idle,
530    Held,
531}
532
533#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
534#[serde(deny_unknown_fields)]
535pub struct PresenceEntry {
536    pub worker_id: String,
537    pub role: String,
538    pub state: PresenceState,
539    /// QN0: the worker's name and its Instance, so another Instance can
540    /// show who is working (display only, never used to authorize).
541    #[serde(default, skip_serializing_if = "Option::is_none")]
542    pub display_name: Option<String>,
543    #[serde(default, skip_serializing_if = "Option::is_none")]
544    pub instance_id: Option<String>,
545    #[serde(default, skip_serializing_if = "Option::is_none")]
546    pub instance_name: Option<String>,
547}
548
549/// The names a `presence.update` may carry besides the worker id (all
550/// optional; a Cloud that does not send them leaves every one `None`).
551/// Display only: bounded single lines, never used to address or authorize.
552#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
553pub struct PresenceNames {
554    /// `agent` | `person`.
555    #[serde(default, skip_serializing_if = "Option::is_none")]
556    pub kind: Option<String>,
557    #[serde(default, skip_serializing_if = "Option::is_none")]
558    pub display_name: Option<String>,
559    #[serde(default, skip_serializing_if = "Option::is_none")]
560    pub session_name: Option<String>,
561    #[serde(default, skip_serializing_if = "Option::is_none")]
562    pub instance_id: Option<String>,
563    #[serde(default, skip_serializing_if = "Option::is_none")]
564    pub instance_name: Option<String>,
565    /// h7b team presence: the linked account's name of the person the
566    /// worker belongs to (set by Cloud, never by an Instance), the short
567    /// name of the machine and what the worker is working on. Cloud relays
568    /// them to members of the same team only.
569    #[serde(default, skip_serializing_if = "Option::is_none")]
570    pub person_name: Option<String>,
571    #[serde(default, skip_serializing_if = "Option::is_none")]
572    pub machine_name: Option<String>,
573    #[serde(default, skip_serializing_if = "Option::is_none")]
574    pub working_on: Option<String>,
575}
576
577/// What a worker's `presence.update` adds for its team (h7b), sent only
578/// after the `hello.ack` names `presence_identity` and while
579/// `[cloud] presence_names` is on. Display only. Both members are always
580/// sent (`null` when unknown), so a status that was cleared replaces the
581/// old line whether Cloud replaces or merges the entry.
582#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
583pub struct PresenceIdentity {
584    #[serde(default)]
585    pub machine_name: Option<String>,
586    #[serde(default)]
587    pub working_on: Option<String>,
588}
589
590/// The machine name a team sees for an Instance label: the label as it is
591/// when it reads like a name ("Yves's laptop") or is an IP address (never
592/// cut into a meaningless first octet), else only the first part of a host
593/// name, so `build-01.corp.example.com` and `yves-mac.local` become
594/// `build-01` and `yves-mac` and no domain leaves the machine. Used for
595/// every name an Instance sends about itself (`instance_name` in the
596/// hello and in `presence.update`, and `machine_name`).
597pub fn machine_name(label: &str) -> Option<String> {
598    let label = label.trim();
599    let short =
600        if label.chars().any(char::is_whitespace) || label.parse::<std::net::IpAddr>().is_ok() {
601            label
602        } else {
603            label.split('.').next().unwrap_or_default()
604        };
605    bounded_line(short, PRESENCE_NAME_CHARS).map(str::to_owned)
606}
607
608/// `value` trimmed when it is a non-empty single line of at most `max`
609/// characters, else none.
610pub fn bounded_line(value: &str, max: usize) -> Option<&str> {
611    let value = value.trim();
612    (!value.is_empty() && value.chars().count() <= max && !value.chars().any(char::is_control))
613        .then_some(value)
614}
615
616/// What a worker is working on, as its team sees it: the first line of
617/// the status the agent wrote itself, with every absolute path cut to its
618/// last part (`/Users/ada/src/acme/login.rs` → `login.rs`) and secrets
619/// replaced by `redact_text` (the same redaction `ctx_agent` exports use),
620/// then cut to `PRESENCE_NAME_CHARS` characters without an ellipsis.
621/// Redaction runs on the whole line before the cut, so a secret that
622/// straddles the cut is never sent half.
623pub fn working_on(status: &str) -> Option<String> {
624    let first = status.lines().map(str::trim).find(|l| !l.is_empty())?;
625    let redacted = lean_ctx::core::redaction::redact_text(&without_paths(first));
626    let cut: String = redacted.chars().take(PRESENCE_NAME_CHARS).collect();
627    bounded_line(&cut, PRESENCE_NAME_CHARS).map(str::to_owned)
628}
629
630/// `line` with each absolute path or `file:` URL cut to its last part; words
631/// are rejoined with single spaces.
632///
633/// Privacy first: a path starts at a `/`, `\`, `~/`, `~user/`, `$NAME/`, `\\` or a
634/// drive (`C:\`, `C:/`) anywhere in a word, whatever stands before it, as
635/// long as that is no name character (`--set=a=/…`, `path:/…`, `grün=/…`,
636/// `"/…`, `(/…`) or only a short flag (`-v/…`, `-I/…`). Relative paths
637/// (`src/main.rs`, `./x`), ratios (`1/2`), a lone `/` and URLs start none.
638/// From the start of a path everything through the last separator in the
639/// rest of its segment goes, and only the final part stays. The segment ends
640/// before the next word that starts a path, flag or URL of its own or a shell
641/// operator, so folder names with any number of spaces
642/// (`C:\Users\ada\OneDrive - Acme Bank\proj\x.rs` → `x.rs`) and quotes inside
643/// a quoted path leave nothing behind. A relative word in the same segment
644/// goes too (`/repo/a.md src/b.rs` → `b.rs`): cutting too much is the safe
645/// side for a line the whole team sees.
646fn without_paths(line: &str) -> String {
647    let words: Vec<&str> = line.split_whitespace().collect();
648    let mut out = Vec::with_capacity(words.len());
649    let mut next = 0;
650    while let Some(&word) = words.get(next) {
651        next += 1;
652        let Some((prefix, start)) = path_start(word) else {
653            out.push(word.to_owned());
654            continue;
655        };
656        let segment_end = words[next..]
657            .iter()
658            .position(|more| ends_segment(more))
659            .map_or(words.len(), |at| next + at);
660        let through = words[next..segment_end]
661            .iter()
662            .rposition(|more| more.contains(['/', '\\']))
663            .map_or(next, |at| next + at + 1);
664        let mut path = word[start..].to_owned();
665        for more in &words[next..through] {
666            path.push(' ');
667            path.push_str(more);
668        }
669        next = through;
670        out.push(format!("{prefix}{}", last_part(&path)));
671    }
672    out.join(" ")
673}
674
675/// Where the first absolute path in `word` starts, with what stands before
676/// it (a `file://` scheme is dropped from that prefix, and all after it is
677/// the path, host form `file://nas/share/…` too); none for a word
678/// without one and for a URL of any other scheme.
679fn path_start(word: &str) -> Option<(&str, usize)> {
680    if let Some(scheme) = word.find("://") {
681        let name = &word[..scheme];
682        if !name.to_ascii_lowercase().ends_with("file") {
683            return None;
684        }
685        let path = scheme + "://".len();
686        return (path < word.len()).then_some((&word[..scheme - "file".len()], path));
687    }
688    let mut before: Option<char> = None;
689    for (at, c) in word.char_indices() {
690        let free = before.is_none_or(|b| !is_name_char(b) || is_short_flag(&word[..at]));
691        if free && starts_path(&word[at..]) {
692            return Some((&word[..at], at));
693        }
694        before = Some(c);
695    }
696    None
697}
698
699/// Whether `rest` begins with an absolute Unix, home (`~/`, `~user/`),
700/// Windows root, UNC or drive-letter path.
701fn starts_path(rest: &str) -> bool {
702    let bytes = rest.as_bytes();
703    if matches!(bytes.first(), Some(b'/' | b'\\')) {
704        return bytes.len() > 1;
705    }
706    if let Some(var) = rest.strip_prefix('$') {
707        let name = var
708            .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
709            .unwrap_or(var.len());
710        return name > 0 && matches!(var.as_bytes().get(name), Some(b'/' | b'\\'));
711    }
712    if let Some(home) = rest.strip_prefix('~') {
713        return home
714            .find('/')
715            .is_some_and(|slash| home[..slash].chars().all(is_name_char));
716    }
717    bytes.len() > 2
718        && bytes[0].is_ascii_alphabetic()
719        && bytes[1] == b':'
720        && matches!(bytes[2], b'\\' | b'/')
721}
722
723/// A character of a name or relative path: a path never starts right
724/// after one (`src/main.rs`, `./x`, `1/2`).
725fn is_name_char(c: char) -> bool {
726    c.is_alphanumeric() || matches!(c, '.' | '_' | '-' | '~')
727}
728
729/// A short flag such as `-v` or `-I` that a path may follow directly.
730fn is_short_flag(prefix: &str) -> bool {
731    prefix
732        .strip_prefix('-')
733        .is_some_and(|name| !name.is_empty() && name.chars().all(|c| c.is_ascii_alphabetic()))
734}
735
736/// Whether `word` begins something new after a path: a path, flag or URL of
737/// its own, or a shell operator.
738fn ends_segment(word: &str) -> bool {
739    let flag = word
740        .strip_prefix('-')
741        .and_then(|rest| rest.chars().next())
742        .is_some_and(|c| c == '-' || c.is_alphanumeric());
743    flag || word.contains("://")
744        || matches!(word, "|" | "||" | "&&" | ";" | ">" | ">>")
745        || path_start(word).is_some()
746}
747
748/// The part of `path` after its last separator; when only closing quotes or
749/// punctuation follow that separator (`acme\`, `acme/"`), the last named
750/// part before it with them.
751fn last_part(path: &str) -> String {
752    let closes = |c: char| {
753        matches!(
754            c,
755            '"' | '\'' | '`' | ')' | ']' | '>' | '}' | ',' | '.' | ';' | ':' | '!' | '?'
756        )
757    };
758    let mut parts = path.rsplit(['/', '\\']);
759    let last = parts.next().unwrap_or_default();
760    if !last.trim_matches(closes).is_empty() {
761        return last.to_owned();
762    }
763    let name = parts
764        .find(|part| !part.trim_matches(closes).is_empty())
765        .unwrap_or("…");
766    format!("{name}{last}")
767}
768
769/// Longest name kept from a presence frame, in characters.
770const PRESENCE_NAME_CHARS: usize = 128;
771
772/// The optional names of a `presence.update` frame; a field that is no
773/// bounded single line is dropped, an unknown `kind` too.
774pub fn presence_names(value: &Value) -> PresenceNames {
775    let line = |field: &str| {
776        value[field]
777            .as_str()
778            .map(str::trim)
779            .filter(|v| {
780                !v.is_empty()
781                    && v.chars().count() <= PRESENCE_NAME_CHARS
782                    && !v.chars().any(char::is_control)
783            })
784            .map(str::to_owned)
785    };
786    PresenceNames {
787        kind: line("kind").filter(|k| matches!(k.as_str(), "agent" | "person")),
788        display_name: line("display_name"),
789        session_name: line("session_name"),
790        instance_id: line("instance_id"),
791        instance_name: line("instance_name"),
792        person_name: line("person_name"),
793        machine_name: line("machine_name"),
794        working_on: line("working_on"),
795    }
796}
797
798/// The frames the engine reads; others are ignored by the relay.
799#[derive(Debug, Clone, PartialEq)]
800pub enum Inbound {
801    HelloAck(Value),
802    Stored {
803        client_msg_id: String,
804        id: String,
805        seq: u64,
806        thread_id: String,
807    },
808    Deliver(Value),
809    Presence {
810        address: String,
811        worker_id: String,
812        role: String,
813        state: PresenceState,
814        at: u64,
815        /// The optional names a Cloud relays with the presence.
816        names: PresenceNames,
817    },
818    Control {
819        lifted: bool,
820        control: Box<Control>,
821    },
822    PlaceDenied {
823        place: String,
824        code: String,
825    },
826    Resync {
827        place: String,
828    },
829    Error {
830        client_msg_id: Option<String>,
831        code: String,
832        reason: Option<String>,
833        /// A `quota_exceeded` frame's optional quota fields (`resource`,
834        /// `limit`, `used`, `reset_at`, `retry_after_s`), only those of the
835        /// expected type; `None` when the frame carries none.
836        quota: Option<Box<Value>>,
837    },
838    Ping,
839    /// The person answered a consent in the browser (§3.8.2 step 4).
840    ConsentAnswered {
841        consent_id: String,
842    },
843    /// C0 2.2: a task of a followed vault changed.
844    TaskEvent(Box<super::task_events::TaskEvent>),
845    /// §37: a plan of a followed vault has a new version (`plan.advanced`).
846    /// A hint only: nothing reaches an agent before the version is pulled
847    /// and its signature verified.
848    PlanAdvanced(Box<super::plan_events::PlanAdvanced>),
849    /// §37: a team decision of a followed vault changed (`decision.changed`).
850    DecisionChanged(Box<super::plan_events::DecisionChanged>),
851    /// A place's log grew (`log.advanced`): background sync tails it now.
852    /// `purge` (priority `purge`) skips the local debounce.
853    LogAdvanced {
854        place: String,
855        purge: bool,
856    },
857    /// A place's trust (members, keys) moved (`trust.advanced`).
858    TrustAdvanced {
859        place: String,
860    },
861    /// The effective policy of this instance has a new version
862    /// (`policy.advanced`). A hint only: nothing is applied before the
863    /// signed bundle is pulled and verified.
864    PolicyAdvanced {
865        version: u64,
866    },
867    Other(String),
868}
869
870/// The quota fields of an `error` frame that have their C0 type (strings
871/// `resource`/`reset_at`, unsigned `limit`/`used`/`retry_after_s`); a field
872/// of another type is left out, so an odd one never hides the others.
873fn quota_fields(frame: &Value) -> Option<Box<Value>> {
874    let mut out = serde_json::Map::new();
875    for (field, string) in [
876        ("resource", true),
877        ("reset_at", true),
878        ("limit", false),
879        ("used", false),
880        ("retry_after_s", false),
881    ] {
882        let value = &frame[field];
883        if field == "retry_after_s" {
884            // Capped here as well: a hostile frame never reaches time math.
885            if let Some(s) = value.as_u64() {
886                let capped = s.min(crate::error::RETRY_AFTER_CAP_S);
887                out.insert(field.to_string(), Value::from(capped));
888            }
889        } else if (string && value.is_string()) || (!string && value.is_u64()) {
890            out.insert(field.to_string(), value.clone());
891        }
892    }
893    (!out.is_empty()).then(|| Box::new(Value::Object(out)))
894}
895
896/// Parse one text frame (flat `{t, ...body}`).
897pub fn parse_frame(text: &str) -> Result<Inbound, Invalid> {
898    let value: Value = serde_json::from_str(text).map_err(|e| bad(format!("frame: {e}")))?;
899    let t = value["t"]
900        .as_str()
901        .ok_or_else(|| bad("frame without t"))?
902        .to_string();
903    let s = |field: &str| -> Result<String, Invalid> {
904        value[field]
905            .as_str()
906            .map(str::to_string)
907            .ok_or_else(|| bad(format!("{t}: {field}")))
908    };
909    let n = |field: &str| -> Result<u64, Invalid> {
910        value[field]
911            .as_u64()
912            .ok_or_else(|| bad(format!("{t}: {field}")))
913    };
914    Ok(match t.as_str() {
915        "hello.ack" => Inbound::HelloAck(value),
916        "message.stored" => Inbound::Stored {
917            client_msg_id: s("client_msg_id")?,
918            id: s("id")?,
919            seq: n("seq")?,
920            thread_id: s("thread_id")?,
921        },
922        "message.deliver" => Inbound::Deliver(value),
923        "presence.update" => Inbound::Presence {
924            address: s("address")?,
925            worker_id: s("worker_id")?,
926            role: s("role")?,
927            state: serde_json::from_value(value["state"].clone())
928                .map_err(|_| bad("presence.update: state"))?,
929            at: n("at")?,
930            names: presence_names(&value),
931        },
932        "control" => {
933            let lifted = match value["state"].as_str() {
934                Some("issued") => false,
935                Some("lifted") => true,
936                _ => return Err(bad("control: state")),
937            };
938            let control = serde_json::from_value(value["control"].clone())
939                .map_err(|e| bad(format!("control: {e}")))?;
940            Inbound::Control { lifted, control }
941        }
942        "place.denied" => Inbound::PlaceDenied {
943            place: s("place")?,
944            code: s("code")?,
945        },
946        "resync" => Inbound::Resync { place: s("place")? },
947        "error" => Inbound::Error {
948            client_msg_id: value["client_msg_id"].as_str().map(str::to_string),
949            code: s("code")?,
950            reason: value["reason"].as_str().map(str::to_string),
951            quota: quota_fields(&value),
952        },
953        "ping" => Inbound::Ping,
954        "consent.answered" => Inbound::ConsentAnswered {
955            consent_id: s("consent_id")?,
956        },
957        "task.event" => Inbound::TaskEvent(Box::new(
958            super::task_events::TaskEvent::parse(&value).ok_or_else(|| bad("task.event"))?,
959        )),
960        "plan.advanced" => Inbound::PlanAdvanced(Box::new(
961            super::plan_events::PlanAdvanced::parse(&value).ok_or_else(|| bad("plan.advanced"))?,
962        )),
963        "decision.changed" => Inbound::DecisionChanged(Box::new(
964            super::plan_events::DecisionChanged::parse(&value)
965                .ok_or_else(|| bad("decision.changed"))?,
966        )),
967        "log.advanced" => Inbound::LogAdvanced {
968            place: s("place")?,
969            purge: value["priority"].as_str() == Some("purge"),
970        },
971        "trust.advanced" => Inbound::TrustAdvanced { place: s("place")? },
972        "policy.advanced" => Inbound::PolicyAdvanced {
973            version: n("version")?,
974        },
975        _ => Inbound::Other(t),
976    })
977}
978
979#[cfg(test)]
980#[path = "v2_tests.rs"]
981mod tests;