Skip to main content

openbutler_protocol/
envelope.rs

1//! Envelope rules: requests, responses, and unsolicited events.
2//!
3//! Frames are UTF-8 JSON + `\n`. One socket carries both responses and events;
4//! receivers distinguish them by the presence of `event` versus `id` + `ok`.
5//! Every request carries a version, a correlation id, and an action; payloads
6//! ride as flattened extra keys (the TypeScript index signature), which is how
7//! `workspaceKey` and every action parameter travel.
8
9use serde::de::Error as _;
10use serde::{Deserialize, Deserializer, Serialize};
11use serde_json::{Map, Value};
12
13use crate::constants::{DAEMON_PROTOCOL_VERSION, MAX_ACTION_LENGTH, MAX_ID_LENGTH};
14use crate::error::ValidationError;
15use crate::runtime::RuntimeViewData;
16use crate::session::{SessionPatch, SessionSnapshotData};
17
18/// Counts JS string length: UTF-16 code units, exactly like
19/// `String.prototype.length`. A byte count here would reject ids the
20/// TypeScript gate accepts and split the two implementations.
21pub fn js_length(value: &str) -> usize {
22    value.chars().map(char::len_utf16).sum()
23}
24
25/// Request frame (client → host): `{version, id, action, ...payload}`.
26///
27/// `bindingKey` is one of the flattened payload keys and is omitted on
28/// `attach` — the host issues it, the client adopts it, and every later
29/// session-bound request echoes it.
30#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
31pub struct DaemonRequest {
32    pub version: u32,
33    pub id: String,
34    pub action: String,
35    #[serde(flatten)]
36    pub payload: Map<String, Value>,
37}
38
39impl DaemonRequest {
40    /// Builds a request at the current protocol version.
41    pub fn new(id: impl Into<String>, action: impl Into<String>) -> Self {
42        Self {
43            version: DAEMON_PROTOCOL_VERSION,
44            id: id.into(),
45            action: action.into(),
46            payload: Map::new(),
47        }
48    }
49
50    /// Attaches one payload key.
51    pub fn with(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
52        self.payload.insert(key.into(), value.into());
53        self
54    }
55
56    /// Reads a payload key.
57    pub fn get(&self, key: &str) -> Option<&Value> {
58        self.payload.get(key)
59    }
60}
61
62/// Host-side request gate (`isDaemonRequest`): version match, `id` and
63/// `action` each 1..=64 JS string length units.
64pub fn validate_request(request: &DaemonRequest) -> Result<(), ValidationError> {
65    if request.version != DAEMON_PROTOCOL_VERSION {
66        return Err(ValidationError::WrongVersion {
67            expected: DAEMON_PROTOCOL_VERSION,
68            actual: request.version,
69        });
70    }
71    let id = js_length(&request.id);
72    if !(1..=MAX_ID_LENGTH).contains(&id) {
73        return Err(ValidationError::InvalidIdLength { actual: id });
74    }
75    let action = js_length(&request.action);
76    if !(1..=MAX_ACTION_LENGTH).contains(&action) {
77        return Err(ValidationError::InvalidActionLength { actual: action });
78    }
79    Ok(())
80}
81
82/// Response frame: success carries `result`, failure carries `error`.
83///
84/// The two shapes are told apart by which key exists, never by `ok` alone —
85/// exactly like the TypeScript union, and the tagged representation here makes
86/// a half-and-half frame impossible to express.
87#[derive(Debug, Clone, PartialEq, Serialize)]
88#[serde(untagged)]
89pub enum DaemonResponse {
90    Success {
91        version: u32,
92        id: String,
93        ok: bool,
94        result: Value,
95    },
96    Failure {
97        version: u32,
98        id: String,
99        ok: bool,
100        error: String,
101    },
102}
103
104impl<'de> Deserialize<'de> for DaemonResponse {
105    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
106    where
107        D: Deserializer<'de>,
108    {
109        let value = Value::deserialize(deserializer)?;
110        let object = value
111            .as_object()
112            .ok_or_else(|| D::Error::custom("response must be an object"))?;
113        let version = object
114            .get("version")
115            .and_then(Value::as_u64)
116            .and_then(|version| u32::try_from(version).ok())
117            .ok_or_else(|| D::Error::custom("response version must be an integer"))?;
118        let id = object
119            .get("id")
120            .and_then(Value::as_str)
121            .ok_or_else(|| D::Error::custom("response id must be a string"))?
122            .to_owned();
123        let ok = object
124            .get("ok")
125            .and_then(Value::as_bool)
126            .ok_or_else(|| D::Error::custom("response ok must be a boolean"))?;
127        let has_result = object.contains_key("result");
128        let has_error = object.contains_key("error");
129        match (has_result, has_error, ok) {
130            (true, false, true) => Ok(DaemonResponse::Success {
131                version,
132                id,
133                ok,
134                result: object.get("result").cloned().unwrap_or(Value::Null),
135            }),
136            (false, true, false) => {
137                let error = object
138                    .get("error")
139                    .and_then(Value::as_str)
140                    .ok_or_else(|| D::Error::custom("response error must be a string"))?
141                    .to_owned();
142                Ok(DaemonResponse::Failure {
143                    version,
144                    id,
145                    ok,
146                    error,
147                })
148            }
149            _ => Err(D::Error::custom(
150                ValidationError::MalformedResponse.to_string(),
151            )),
152        }
153    }
154}
155
156impl DaemonResponse {
157    /// The correlation id this response settles.
158    pub fn id(&self) -> &str {
159        match self {
160            DaemonResponse::Success { id, .. } | DaemonResponse::Failure { id, .. } => id,
161        }
162    }
163
164    /// The protocol version this response carries.
165    pub fn version(&self) -> u32 {
166        match self {
167            DaemonResponse::Success { version, .. } | DaemonResponse::Failure { version, .. } => {
168                *version
169            }
170        }
171    }
172}
173
174/// Client-side response gate (`isBasicResponse`): the response must echo the
175/// requested version, and a success with `ok:false` (or a failure with
176/// `ok:true`) is malformed.
177pub fn validate_response(
178    response: &DaemonResponse,
179    expected_version: u32,
180) -> Result<(), ValidationError> {
181    if response.version() != expected_version {
182        return Err(ValidationError::ResponseVersionMismatch {
183            expected: expected_version,
184            actual: response.version(),
185        });
186    }
187    match response {
188        DaemonResponse::Success { ok, .. } if !*ok => Err(ValidationError::MalformedResponse),
189        DaemonResponse::Failure { ok, .. } if *ok => Err(ValidationError::MalformedResponse),
190        _ => Ok(()),
191    }
192}
193
194/// Unsolicited host → client frame. Distinguished from a response by the
195/// `event` key.
196#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
197#[serde(tag = "event", rename_all = "lowercase")]
198pub enum DaemonEvent {
199    /// Full session state; also pushed right after `attach` with the same
200    /// window as the response.
201    Snapshot {
202        version: u32,
203        snapshot: SessionSnapshotData,
204        runtime: RuntimeViewData,
205    },
206    /// Incremental session state.
207    Patch { version: u32, patch: SessionPatch },
208    /// Owner-directed message. An empty title with content is promoted into
209    /// the transcript by clients; a titled one is a transient notice.
210    Notification {
211        version: u32,
212        title: String,
213        message: String,
214    },
215}
216
217impl DaemonEvent {
218    pub fn version(&self) -> u32 {
219        match self {
220            Self::Snapshot { version, .. }
221            | Self::Patch { version, .. }
222            | Self::Notification { version, .. } => *version,
223        }
224    }
225}
226
227/// Client-side event gate: unsolicited frames must speak the requested version.
228pub fn validate_event(event: &DaemonEvent, expected_version: u32) -> Result<(), ValidationError> {
229    if event.version() != expected_version {
230        return Err(ValidationError::ResponseVersionMismatch {
231            expected: expected_version,
232            actual: event.version(),
233        });
234    }
235    Ok(())
236}
237
238/// The notification frame as its own named shape (the TypeScript
239/// `DaemonNotification` alias); clients use it for owner messages only, never
240/// for model conversation patches.
241pub type DaemonNotification = DaemonEvent;