Skip to main content

kian_plugin/hooks/sidecar/
frame.rs

1//! The stdio ABI frames (PLUGIN-SPEC §7.1–§7.2, v1).
2//!
3//! Newline-delimited compact JSON objects with **closed shapes**: field
4//! names, order and presence are exactly the §7.2 table, checked by the
5//! golden tests byte-for-byte. The epoch rule lives here as the single
6//! source: a `hook` frame for a drain-phase hook **must** carry `epoch`,
7//! an admission frame **must omit the key entirely** — no `null`, no
8//! sentinel, no `0` (§7.2).
9//!
10//! Reply decoding is deny-unknown-fields and bound-checks every audit
11//! string (`note` ≤ 256, `reason`/`message` ≤ 512, §7.2): a violation
12//! is a malformed speech defect, never a panic and never a silent
13//! truncation that would smuggle unbounded bytes upward.
14
15use serde_json::Value;
16
17use super::super::ids::HookId;
18use super::super::registry::ReplyErrCode;
19use super::super::views::FrameInfo;
20
21/// §7.2's `note` bound.
22pub const NOTE_MAX_BYTES: usize = 256;
23/// §7.2's `reason` / `message` bound.
24pub const REASON_MAX_BYTES: usize = 512;
25
26// ---------------------------------------------------------------------
27// S→P frames
28// ---------------------------------------------------------------------
29
30/// The `hello` frame (§7.2, §7.3 step 1): the server's identity
31/// statement — manifest canonical path, plugin name/version, abi — plus
32/// the declared sets and the two bounds the child must respect.
33#[derive(Debug, Clone, PartialEq)]
34pub struct Hello {
35    pub manifest: String,
36    pub name: String,
37    pub version: String,
38    pub abi: u32,
39    pub hooks: Vec<String>,
40    pub capabilities: Vec<String>,
41    pub deadline_default_ms: u64,
42    pub max_frame_bytes: usize,
43}
44
45impl Hello {
46    /// Compact one-line JSON in §7.2's field order.
47    pub fn encode(&self) -> String {
48        let mut out = String::with_capacity(256);
49        out.push_str("{\"v\":1,\"manifest\":");
50        push_json_string(&mut out, &self.manifest);
51        out.push_str(",\"plugin\":{\"name\":");
52        push_json_string(&mut out, &self.name);
53        out.push_str(",\"version\":");
54        push_json_string(&mut out, &self.version);
55        out.push_str("},\"abi\":");
56        out.push_str(&self.abi.to_string());
57        out.push_str(",\"hooks\":");
58        push_json_string_array(&mut out, &self.hooks);
59        out.push_str(",\"capabilities\":");
60        push_json_string_array(&mut out, &self.capabilities);
61        out.push_str(",\"deadline_default_ms\":");
62        out.push_str(&self.deadline_default_ms.to_string());
63        out.push_str(",\"max_frame_bytes\":");
64        out.push_str(&self.max_frame_bytes.to_string());
65        out.push('}');
66        out
67    }
68}
69
70/// The `bye` frame (§7.2): the empty object, nothing else.
71pub fn encode_bye() -> String {
72    "{}".to_string()
73}
74
75/// A server→plugin `err` frame (§7.2 allows the direction; the runner
76/// uses it only in tests and diagnostics today — refusal and quarantine
77/// travel as process death plus audit lines, not as err frames).
78pub fn encode_err(id: Option<&str>, code: ReplyErrCode, message: &str) -> String {
79    let mut out = String::with_capacity(96);
80    out.push('{');
81    if let Some(id) = id {
82        out.push_str("\"id\":");
83        push_json_string(&mut out, id);
84        out.push(',');
85    }
86    out.push_str("\"code\":");
87    push_json_string(&mut out, code.as_str());
88    out.push_str(",\"message\":");
89    push_json_string(&mut out, message);
90    out.push('}');
91    out
92}
93
94/// Why a `hook` frame could not be built: the epoch rule's local guard.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct FrameError {
97    pub message: String,
98}
99
100/// The `hook` frame (§7.2): full target identity (`session`, `worker`,
101/// `seq`), a fresh dispatch id, the per-dispatch deadline, the mode and
102/// the §3.2 payload. `epoch` rides the frame — never the payload — and
103/// only for drain-phase hooks.
104#[derive(Debug, Clone, PartialEq)]
105pub struct HookFrame {
106    pub id: String,
107    pub hook: HookId,
108    pub session: String,
109    pub worker: String,
110    pub seq: u64,
111    pub epoch: Option<u64>,
112    pub deadline_ms: u64,
113    pub mode: &'static str,
114    pub payload: Value,
115}
116
117impl HookFrame {
118    /// Builds a frame from the in-process dispatch identity. The epoch
119    /// rule is enforced here: drain-phase hooks require a frame with an
120    /// epoch, admission hooks must not carry one (§7.2) — a caller that
121    /// gets this wrong is refused, not silently repaired.
122    pub fn new(
123        hook: HookId,
124        frame: &FrameInfo,
125        id: String,
126        deadline_ms: u64,
127        payload: Value,
128    ) -> Result<Self, FrameError> {
129        let drain_phase = hook.class().is_drain_phase();
130        let epoch = frame.epoch;
131        match (drain_phase, epoch) {
132            (true, Some(_)) => {}
133            (true, None) => {
134                return Err(FrameError {
135                    message: format!(
136                        "hook `{hook}` is drain-phase: its frame requires an epoch (§7.2)"
137                    ),
138                });
139            }
140            (false, Some(_)) => {
141                return Err(FrameError {
142                    message: format!(
143                        "hook `{hook}` runs before a drain exists: its frame must omit `epoch` (§7.2)"
144                    ),
145                });
146            }
147            (false, None) => {}
148        }
149        Ok(Self {
150            id,
151            hook: hook.clone(),
152            session: frame.session.0.to_string(),
153            worker: frame.worker.clone(),
154            seq: frame.seq,
155            epoch,
156            deadline_ms,
157            mode: mode_str(hook.mode()),
158            payload,
159        })
160    }
161
162    /// Compact one-line JSON in §7.2's field order, `epoch` present
163    /// only when `Some`.
164    pub fn encode(&self) -> String {
165        let mut out = String::with_capacity(256);
166        out.push_str("{\"id\":");
167        push_json_string(&mut out, &self.id);
168        out.push_str(",\"hook\":");
169        push_json_string(&mut out, &self.hook.to_string());
170        out.push_str(",\"session\":");
171        push_json_string(&mut out, &self.session);
172        out.push_str(",\"worker\":");
173        push_json_string(&mut out, &self.worker);
174        out.push_str(",\"seq\":");
175        out.push_str(&self.seq.to_string());
176        if let Some(epoch) = self.epoch {
177            out.push_str(",\"epoch\":");
178            out.push_str(&epoch.to_string());
179        }
180        out.push_str(",\"deadline_ms\":");
181        out.push_str(&self.deadline_ms.to_string());
182        out.push_str(",\"mode\":");
183        push_json_string(&mut out, self.mode);
184        out.push_str(",\"payload\":");
185        out.push_str(&serde_json::to_string(&self.payload).unwrap_or_default());
186        out.push('}');
187        out
188    }
189}
190
191fn mode_str(mode: super::super::ids::HookMode) -> &'static str {
192    match mode {
193        super::super::ids::HookMode::Emit => "emit",
194        super::super::ids::HookMode::Flow => "flow",
195        super::super::ids::HookMode::Bail => "bail",
196    }
197}
198
199// ---------------------------------------------------------------------
200// P→S frames
201// ---------------------------------------------------------------------
202
203/// The `ready` frame (§7.2, §7.3 step 2): the child's identity
204/// restatement, compared by the runner for exact identity equality and
205/// set-equal `hooks`/`capabilities`.
206#[derive(Debug, Clone, PartialEq)]
207pub struct Ready {
208    pub manifest: String,
209    pub name: String,
210    pub version: String,
211    pub abi: u32,
212    pub hooks: Vec<String>,
213    pub capabilities: Vec<String>,
214}
215
216/// A plugin→server reply frame: `ack`, `flow`, `bail` or `err`, with
217/// the closed shapes of §7.2.
218#[derive(Debug, Clone, PartialEq)]
219pub enum ReplyFrame {
220    Ack { note: Option<String> },
221    FlowNext,
222    FlowStop { reason: String },
223    BailNone,
224    BailDeny { reason: String },
225    Err { code: ReplyErrCode, message: String },
226}
227
228impl ReplyFrame {
229    /// Canonical compact JSON with the frame `id` prepended, in §7.2's
230    /// field order. The reference child and the golden tests share this
231    /// encoder, so the wire shape has exactly one spelling.
232    pub fn encode(&self, id: &str) -> String {
233        let mut out = String::with_capacity(128);
234        out.push_str("{\"id\":");
235        push_json_string(&mut out, id);
236        match self {
237            ReplyFrame::Ack { note } => {
238                out.push_str(",\"ack\":true");
239                if let Some(note) = note {
240                    out.push_str(",\"note\":");
241                    push_json_string(&mut out, note);
242                }
243            }
244            ReplyFrame::FlowNext => out.push_str(",\"flow\":\"next\""),
245            ReplyFrame::FlowStop { reason } => {
246                out.push_str(",\"flow\":\"stop\",\"reason\":");
247                push_json_string(&mut out, reason);
248            }
249            ReplyFrame::BailNone => out.push_str(",\"bail\":null"),
250            ReplyFrame::BailDeny { reason } => {
251                out.push_str(",\"bail\":{\"decision\":\"deny\",\"reason\":");
252                push_json_string(&mut out, reason);
253                out.push('}');
254            }
255            ReplyFrame::Err { code, message } => {
256                out.push_str(",\"code\":");
257                push_json_string(&mut out, code.as_str());
258                out.push_str(",\"message\":");
259                push_json_string(&mut out, message);
260            }
261        }
262        out.push('}');
263        out
264    }
265}
266
267/// Why a P→S line is not a legal frame.
268#[derive(Debug, Clone, PartialEq, Eq)]
269pub enum DecodeError {
270    /// Not JSON, not an object, or a shape violation — the speech
271    /// defect `err:malformed` classifies from (§7.2, §11.1).
272    Malformed(String),
273}
274
275impl DecodeError {
276    fn malformed(message: impl Into<String>) -> Self {
277        DecodeError::Malformed(message.into())
278    }
279}
280
281/// Decodes a `ready` line (§7.3 step 2). Structural violations are
282/// malformed — the runner maps identity mismatches to the typed
283/// refusals (`ready_mismatch` / `abi_mismatch`) itself, after decoding.
284pub fn decode_ready(line: &str) -> Result<Ready, DecodeError> {
285    let v: Value = serde_json::from_str(line).map_err(|e| DecodeError::malformed(e.to_string()))?;
286    let obj = v
287        .as_object()
288        .ok_or_else(|| DecodeError::malformed("ready is not an object"))?;
289    for key in obj.keys() {
290        if !matches!(
291            key.as_str(),
292            "v" | "manifest" | "plugin" | "abi" | "hooks" | "capabilities"
293        ) {
294            return Err(DecodeError::malformed(format!(
295                "ready carries unknown key `{key}` (closed shape)"
296            )));
297        }
298    }
299    if obj.get("v").and_then(Value::as_u64) != Some(1) {
300        return Err(DecodeError::malformed("ready v must be 1"));
301    }
302    let string_field = |name: &str| -> Result<String, DecodeError> {
303        obj.get(name)
304            .and_then(Value::as_str)
305            .map(str::to_string)
306            .ok_or_else(|| DecodeError::malformed(format!("ready.{name} must be a string")))
307    };
308    let manifest = string_field("manifest")?;
309    let plugin = obj
310        .get("plugin")
311        .and_then(Value::as_object)
312        .ok_or_else(|| DecodeError::malformed("ready.plugin must be an object"))?;
313    if plugin.len() != 2 || !plugin.contains_key("name") || !plugin.contains_key("version") {
314        return Err(DecodeError::malformed(
315            "ready.plugin must be exactly {name, version}",
316        ));
317    }
318    let name = plugin
319        .get("name")
320        .and_then(Value::as_str)
321        .ok_or_else(|| DecodeError::malformed("ready.plugin.name must be a string"))?
322        .to_string();
323    let version = plugin
324        .get("version")
325        .and_then(Value::as_str)
326        .ok_or_else(|| DecodeError::malformed("ready.plugin.version must be a string"))?
327        .to_string();
328    let abi = obj
329        .get("abi")
330        .and_then(Value::as_u64)
331        .and_then(|v| u32::try_from(v).ok())
332        .ok_or_else(|| DecodeError::malformed("ready.abi must be a small integer"))?;
333    let str_array = |name: &str| -> Result<Vec<String>, DecodeError> {
334        let arr = obj
335            .get(name)
336            .and_then(Value::as_array)
337            .ok_or_else(|| DecodeError::malformed(format!("ready.{name} must be an array")))?;
338        arr.iter()
339            .map(|item| {
340                item.as_str().map(str::to_string).ok_or_else(|| {
341                    DecodeError::malformed(format!("ready.{name} entries are strings"))
342                })
343            })
344            .collect()
345    };
346    Ok(Ready {
347        manifest,
348        name,
349        version,
350        abi,
351        hooks: str_array("hooks")?,
352        capabilities: str_array("capabilities")?,
353    })
354}
355
356/// Decodes a reply line (`ack` / `flow` / `bail` / `err`) for dispatch
357/// `expected_id`. A reply carrying any other id is **not** an error
358/// here — the runner treats it as `protocol_violation` (§7.4) and the
359/// caller needs to see the stray id to say so; this function returns
360/// the frame's own id alongside (`None` only on an id-less `err`, the
361/// one shape §7.2 allows to omit it — attribution falls back to the
362/// single in-flight dispatch).
363pub fn decode_reply(line: &str) -> Result<(Option<String>, ReplyFrame), DecodeError> {
364    let v: Value = serde_json::from_str(line).map_err(|e| DecodeError::malformed(e.to_string()))?;
365    let obj = v
366        .as_object()
367        .ok_or_else(|| DecodeError::malformed("reply is not an object"))?
368        .clone();
369    let is_err = obj.contains_key("code");
370    let id = match obj.get("id") {
371        Some(Value::String(s)) => Some(s.clone()),
372        None if is_err => None,
373        None => return Err(DecodeError::malformed("reply.id must be a string")),
374        Some(_) => return Err(DecodeError::malformed("reply.id must be a string")),
375    };
376    let shape_keys: Vec<&String> = obj
377        .keys()
378        .filter(|k| {
379            matches!(
380                k.as_str(),
381                "ack" | "flow" | "bail" | "code" | "message" | "note" | "reason"
382            )
383        })
384        .collect();
385    // An err is the flat `{"id"?,"code","message"}` shape (§7.2); the
386    // other three are one-key shapes with their own optional fields.
387    let is_err = obj.contains_key("code");
388    if is_err {
389        if obj.contains_key("ack") || obj.contains_key("flow") || obj.contains_key("bail") {
390            return Err(DecodeError::malformed("reply mixes err with a reply shape"));
391        }
392    } else {
393        let strict: Vec<&String> = obj
394            .keys()
395            .filter(|k| matches!(k.as_str(), "ack" | "flow" | "bail"))
396            .collect();
397        if strict.len() != 1 {
398            return Err(DecodeError::malformed(
399                "reply carries exactly one of ack / flow / bail / err",
400            ));
401        }
402    }
403    for key in obj.keys() {
404        if !matches!(
405            key.as_str(),
406            "id" | "ack" | "note" | "flow" | "reason" | "bail" | "code" | "message"
407        ) {
408            return Err(DecodeError::malformed(format!(
409                "reply carries unknown key `{key}` (closed shape)"
410            )));
411        }
412    }
413    let bounded = |s: &str, max: usize, what: &str| -> Result<String, DecodeError> {
414        if s.len() > max {
415            return Err(DecodeError::malformed(format!(
416                "{what} exceeds the {max}-byte audit-string bound"
417            )));
418        }
419        // §7.2's defense-in-depth redaction: the server redacts audit
420        // strings again before they are logged or persisted — a plugin
421        // cannot be trusted to redact. Control characters have no
422        // legitimate place in an audit string; the byte bound is
423        // enforced above.
424        Ok(if s.bytes().any(|b| b < 0x20 || b == 0x7f) {
425            s.chars()
426                .map(|c| if c.is_control() { '·' } else { c })
427                .collect()
428        } else {
429            s.to_string()
430        })
431    };
432    let frame = if is_err {
433        if obj.len() != usize::from(id.is_some()) + 2 {
434            return Err(DecodeError::malformed(
435                "err must be exactly {id?, code, message}",
436            ));
437        }
438        let code = obj
439            .get("code")
440            .and_then(Value::as_str)
441            .and_then(parse_err_code)
442            .ok_or_else(|| {
443                DecodeError::malformed("err.code is outside the closed set — itself malformed")
444            })?;
445        let message = obj
446            .get("message")
447            .and_then(Value::as_str)
448            .ok_or_else(|| DecodeError::malformed("err.message must be a string"))?;
449        ReplyFrame::Err {
450            code,
451            message: bounded(message, REASON_MAX_BYTES, "err.message")?,
452        }
453    } else {
454        match shape_keys[0].as_str() {
455            "ack" => {
456                if obj.get("ack") != Some(&Value::Bool(true)) {
457                    return Err(DecodeError::malformed("ack must be literal true"));
458                }
459                let note = match obj.get("note") {
460                    None => None,
461                    Some(Value::String(s)) => Some(bounded(s, NOTE_MAX_BYTES, "ack.note")?),
462                    Some(_) => return Err(DecodeError::malformed("ack.note must be a string")),
463                };
464                ReplyFrame::Ack { note }
465            }
466            "flow" => match obj.get("flow").and_then(Value::as_str) {
467                Some("next") => ReplyFrame::FlowNext,
468                Some("stop") => {
469                    let reason = obj
470                        .get("reason")
471                        .and_then(Value::as_str)
472                        .ok_or_else(|| DecodeError::malformed("flow stop requires reason"))?;
473                    ReplyFrame::FlowStop {
474                        reason: bounded(reason, REASON_MAX_BYTES, "flow.reason")?,
475                    }
476                }
477                _ => return Err(DecodeError::malformed("flow must be \"next\" or \"stop\"")),
478            },
479            "bail" => match obj.get("bail") {
480                Some(Value::Null) => ReplyFrame::BailNone,
481                Some(Value::Object(deny)) => {
482                    if deny.len() != 2
483                        || deny.get("decision").and_then(Value::as_str) != Some("deny")
484                        || !deny.contains_key("reason")
485                    {
486                        return Err(DecodeError::malformed(
487                            "bail object must be exactly {decision:\"deny\", reason}",
488                        ));
489                    }
490                    let reason = deny
491                        .get("reason")
492                        .and_then(Value::as_str)
493                        .ok_or_else(|| DecodeError::malformed("bail.reason must be a string"))?;
494                    ReplyFrame::BailDeny {
495                        reason: bounded(reason, REASON_MAX_BYTES, "bail.reason")?,
496                    }
497                }
498                _ => return Err(DecodeError::malformed("bail must be null or a deny object")),
499            },
500            _ => unreachable!("shape_keys filtered above"),
501        }
502    };
503    Ok((id, frame))
504}
505
506fn parse_err_code(code: &str) -> Option<ReplyErrCode> {
507    match code {
508        "deadline" => Some(ReplyErrCode::Deadline),
509        "crashed" => Some(ReplyErrCode::Crashed),
510        "malformed" => Some(ReplyErrCode::Malformed),
511        "unauthorized" => Some(ReplyErrCode::Unauthorized),
512        "unsupported_hook" => Some(ReplyErrCode::UnsupportedHook),
513        "protocol_violation" => Some(ReplyErrCode::ProtocolViolation),
514        _ => None,
515    }
516}
517
518// ---------------------------------------------------------------------
519// JSON string helpers — serde_json's Value escaping with a stable,
520// minimal spelling so goldens pin one byte sequence.
521// ---------------------------------------------------------------------
522
523fn push_json_string(out: &mut String, s: &str) {
524    out.push_str(&serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_string()));
525}
526
527fn push_json_string_array(out: &mut String, items: &[String]) {
528    out.push('[');
529    for (index, item) in items.iter().enumerate() {
530        if index > 0 {
531            out.push(',');
532        }
533        push_json_string(out, item);
534    }
535    out.push(']');
536}
537
538#[cfg(test)]
539mod tests {
540    use super::*;
541
542    #[test]
543    fn err_code_outside_the_set_is_malformed() {
544        let line = r#"{"id":"sc-1","code":"mystery","message":"x"}"#;
545        assert!(decode_reply(line).is_err());
546    }
547
548    #[test]
549    fn audit_string_bounds_are_enforced() {
550        let long = "x".repeat(REASON_MAX_BYTES + 1);
551        let deny = format!(r#"{{"id":"sc-1","bail":{{"decision":"deny","reason":"{long}"}}}}"#);
552        assert!(decode_reply(&deny).is_err());
553        let note = format!(
554            r#"{{"id":"sc-1","ack":true,"note":"{}"}}"#,
555            "y".repeat(NOTE_MAX_BYTES + 1)
556        );
557        assert!(decode_reply(&note).is_err());
558    }
559
560    #[test]
561    fn audit_strings_are_redacted_before_rising() {
562        // §7.2 defense in depth: control characters never ride a
563        // reply's audit strings upward.
564        let (_, frame) = decode_reply(
565            "{\"id\":\"x\",\"bail\":{\"decision\":\"deny\",\"reason\":\"line1\\nline2\\u0007\"}}",
566        )
567        .unwrap();
568        match frame {
569            ReplyFrame::BailDeny { reason } => {
570                assert!(reason.contains('·'), "{reason:?}");
571                assert!(!reason.contains('\n'));
572                assert!(!reason.contains('\u{7}'));
573            }
574            other => panic!("expected deny, got {other:?}"),
575        }
576    }
577
578    #[test]
579    fn reply_shapes_are_closed() {
580        // Two shape keys, an unknown key, a non-literal ack: all malformed.
581        for line in [
582            r#"{"id":"x","ack":true,"flow":"next"}"#,
583            r#"{"id":"x","ack":true,"extra":1}"#,
584            r#"{"id":"x","ack":false}"#,
585            r#"{"id":"x","bail":{"decision":"allow","reason":"y"}}"#,
586            "not json",
587            r#"{"ack":true}"#,
588        ] {
589            assert!(decode_reply(line).is_err(), "{line}");
590        }
591        // The four legal shapes decode.
592        assert_eq!(
593            decode_reply(r#"{"id":"x","ack":true}"#).unwrap().1,
594            ReplyFrame::Ack { note: None }
595        );
596        assert_eq!(
597            decode_reply(r#"{"id":"x","flow":"stop","reason":"off-hours"}"#)
598                .unwrap()
599                .1,
600            ReplyFrame::FlowStop {
601                reason: "off-hours".to_string()
602            }
603        );
604        assert_eq!(
605            decode_reply(r#"{"id":"x","bail":null}"#).unwrap().1,
606            ReplyFrame::BailNone
607        );
608        assert_eq!(
609            decode_reply(r#"{"id":"x","code":"deadline","message":"slow"}"#)
610                .unwrap()
611                .1,
612            ReplyFrame::Err {
613                code: ReplyErrCode::Deadline,
614                message: "slow".to_string()
615            }
616        );
617        // An id-less err is the one legal id omission (§7.2).
618        assert_eq!(
619            decode_reply(r#"{"code":"crashed","message":"gone"}"#)
620                .unwrap()
621                .0,
622            None
623        );
624    }
625
626    #[test]
627    fn ready_is_closed() {
628        assert!(decode_ready("{\"v\":1}").is_err());
629        assert!(decode_ready(r#"{"v":2,"manifest":"/m","plugin":{"name":"a","version":"0.1.0"},"abi":1,"hooks":[],"capabilities":[]}"#).is_err());
630        let ok = decode_ready(
631            r#"{"v":1,"manifest":"/m","plugin":{"name":"a","version":"0.1.0"},"abi":1,"hooks":["tool/pre"],"capabilities":["observe:tool"]}"#,
632        )
633        .unwrap();
634        assert_eq!(ok.name, "a");
635        assert_eq!(ok.hooks, vec!["tool/pre".to_string()]);
636    }
637}