Skip to main content

wcode_harness/
protocol.rs

1//! The kernel's request/event interface — one protocol for every peer.
2//!
3//! The kernel already exposes one half of a protocol: [`AgentEvent`] is a
4//! typed, serializable stream of everything a session does (text deltas, tool
5//! lifecycle, turn boundaries). This module adds the inbound half, [`Request`],
6//! and a versioned, addressed envelope, [`Frame`], so that a client and a peer
7//! become the same kind of thing:
8//!
9//! - a **request** goes into a session's mailbox,
10//! - an **event** comes out of its stream.
11//!
12//! A TUI client, a script, and another session differ only in which address
13//! ([`Frame::session`]) they hold and how they render the stream — not in the
14//! protocol they speak. That is what lets the client seam and the future
15//! agent-to-agent seam share one implementation.
16//!
17//! Transport is deliberately absent: today the seam is an in-process
18//! `tokio::mpsc`; framing and sockets live above the kernel (a future
19//! `wcode-protocol` crate). This module is serde types only, so it adds no
20//! behavior — it is the shape the actor (S1) and the socket (S2) will speak.
21//!
22//! See `docs/interface-protocol-brainstorm.md` for the design and the staged
23//! path that lands these types.
24
25use serde::{Deserialize, Serialize};
26
27use crate::event::AgentEvent;
28
29/// Wire-protocol major version. Bumped only by a breaking change; additive
30/// changes leave it alone. [`Request`] already carries a [`Request::Unknown`]
31/// fallback so an older peer survives a newer request; the matching catch-all
32/// on the event side lands with the actor (S1), where an unknown event can be
33/// handled rather than silently dropped.
34pub const PROTOCOL_VERSION: u32 = 1;
35
36/// The well-known address of the human peer (brainstorm §5.2): the sender an
37/// in-process actor attributes an inbound message to until addressing lands
38/// (S4-2).
39pub const USER: &str = "user";
40
41/// Whether `request` is an A2A inbound message — the delivery verbs a peer sends
42/// (`Notify`/`Interrupt`/`Wake`), as opposed to a local command. The actor runs
43/// its `before_inbound` policy on exactly these.
44pub fn is_inbound(request: &Request) -> bool {
45    matches!(
46        request,
47        Request::Notify { .. } | Request::Interrupt { .. } | Request::Wake { .. }
48    )
49}
50
51/// A session's stable address.
52///
53/// Reuses the id already written in `SessionEntry::Header`, so a session is
54/// reachable by the same name it persists under. Transitively serialized as a
55/// bare string. Newtypes a plain `String` only to keep addressing legible at
56/// call sites — the conventions (the human is `"user"`, a peer is
57/// `"agent:<id>"`) are not encoded in the type yet.
58#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
59#[serde(transparent)]
60pub struct SessionId(pub String);
61
62impl SessionId {
63    pub fn new(id: impl Into<String>) -> Self {
64        Self(id.into())
65    }
66
67    /// The well-known address of the human peer (see [`USER`]).
68    pub fn user() -> Self {
69        Self(USER.to_string())
70    }
71
72    /// A peer session's address: `"agent:<id>"` (§5.2).
73    pub fn agent(id: impl AsRef<str>) -> Self {
74        Self(format!("agent:{}", id.as_ref()))
75    }
76
77    pub fn as_str(&self) -> &str {
78        &self.0
79    }
80}
81
82impl From<String> for SessionId {
83    fn from(id: String) -> Self {
84        Self(id)
85    }
86}
87
88impl From<&str> for SessionId {
89    fn from(id: &str) -> Self {
90        Self(id.to_string())
91    }
92}
93
94impl std::fmt::Display for SessionId {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        f.write_str(&self.0)
97    }
98}
99
100/// A session's run-state — the server-side liveness fact (bug 2).
101///
102/// The wire twin of the TUI's client-local `TeamState`: born at the actor's
103/// `run()` boundary (actor.rs), mirrored into the registry roster, and carried
104/// on [`SessionInfo`] so it RIDES the existing
105/// [`crate::event::AgentEvent::Sessions`] push — no new `Request`/`Reply`
106/// variant is needed for the query (`Request::ListSessions` already returns
107/// `Sessions`; making it `state`-aware is the whole poll path).
108///
109/// serde shape: `snake_case` — `"idle" | "running" | "done" | "failed"`.
110/// `Default = Idle`, so an older server's [`SessionInfo`] (no `state` key)
111/// still deserializes.
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "snake_case")]
114pub enum MemberState {
115    /// Not running and never has — a fresh worker before its first turn.
116    #[default]
117    Idle,
118    /// A run (a `Submit`/`Wake` turn) is in flight right now.
119    Running,
120    /// The last run finished normally; idle but not virgin.
121    Done,
122    /// The last run ended on a run-failure (`StopReason::Error`); sticky
123    /// across the run boundary, cleared by the next start.
124    Failed,
125}
126
127impl MemberState {
128    /// Lowercase label the roster push / `peers` listing render.
129    pub fn label(self) -> &'static str {
130        match self {
131            MemberState::Idle => "idle",
132            MemberState::Running => "running",
133            MemberState::Done => "done",
134            MemberState::Failed => "failed",
135        }
136    }
137}
138
139// Follow-on (not this change): the map from `MemberState` to the TUI's
140// `TeamState` does NOT live here — the harness must not depend on `wcode-tui`
141// (layering). That map, and the glyph styling it drives, is a separate TUI
142// change outside the roster work.
143
144#[cfg(test)]
145mod member_state_tests {
146    use super::*;
147    use serde_json::json;
148
149    #[test]
150    fn serde_is_snake_case() {
151        assert_eq!(
152            serde_json::to_value(MemberState::Running).unwrap(),
153            json!("running")
154        );
155        assert_eq!(
156            serde_json::from_str::<MemberState>("\"failed\"").unwrap(),
157            MemberState::Failed
158        );
159        assert_eq!(MemberState::Done.label(), "done");
160    }
161
162    #[test]
163    fn absent_state_field_defaults_to_idle() {
164        let info: SessionInfo = serde_json::from_value(json!({"id": "agent:w1"})).unwrap();
165        assert_eq!(info.id, SessionId::agent("w1"));
166        assert_eq!(info.state, MemberState::Idle);
167    }
168}
169/// A served session's address plus the little metadata a roster shows: its
170/// **effective model**, **reasoning effort**, and **context window** (each
171/// `None` when the server does not know it). Carried by
172/// [`crate::event::AgentEvent::Sessions`], so a client can label each member by
173/// its own model instead of substituting the root's.
174#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
175pub struct SessionInfo {
176    pub id: SessionId,
177    /// The session's effective model id, when the server knows one (a worker
178    /// registered with its model); `None` for a peer whose model is unknown.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub model: Option<String>,
181    /// The session's effective reasoning effort, when the server knows one (a
182    /// worker set to `high`, a root launched `--effort xhigh`); `None` when
183    /// unset/inherited. Absent on the wire for an older peer.
184    #[serde(default, skip_serializing_if = "Option::is_none")]
185    pub effort: Option<String>,
186    /// The session's context window in tokens, when known (the root's
187    /// `limits::model_limit(base_url, model).context`, else
188    /// `limits::DEFAULT_CONTEXT_WINDOW`). The GAUGE's denominator.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub context_window: Option<u64>,
191    /// Server-side liveness (see [`MemberState`] above). `#[serde(default)]`
192    /// keeps an older peer's `SessionInfo` (no `state` key) round-tripping as
193    /// `Idle`.
194    #[serde(default)]
195    pub state: MemberState,
196}
197
198/// Inbound intent: the requests a session's mailbox accepts.
199///
200/// Every variant maps one-to-one onto an existing [`crate::agent::Agent`]
201/// method, so the current session behavior is expressible without the actor
202/// inventing anything new:
203///
204/// | `Request` | today |
205/// |-----------|-------|
206/// | `Submit` | `Agent::run` |
207/// | `Notify` | `Agent::notify` (append, no turn) |
208/// | `Interrupt` | `Agent::steer` |
209/// | `Wake` | run — a turn even when idle |
210/// | `Cancel` | `Agent::cancel` |
211/// | `SetModel` | `Agent::set_model` |
212/// | `SetEffort` | `Agent::set_effort` |
213/// | `Compact` | `Agent::compact` |
214/// | `Usage` | `crate::stats::session_stats` + `pricing::cost_of` |
215///
216/// The one exception is [`Request::ListSessions`]: a transport-level probe the
217/// server answers, not an `Agent` method.
218///
219/// Inbound payloads carry user **content**, not an `AgentMessage`: a remote peer
220/// must not be able to inject an `Assistant`/`ToolResult` message and impersonate
221/// the model. The session wraps content as a user message, exactly as
222/// `Agent::run` does. `GetHistory` is a read: it carries no payload and its
223/// answer comes back as [`AgentEvent::History`]
224/// (with the other replies — [`AgentEvent::Ack`],
225/// and [`AgentEvent::Error`] — alongside it).
226/// These reply variants are never *streamed*: they answer a specific request,
227/// which the transport correlates (an in-process oneshot today, the envelope's
228/// `reply_to` on the wire).
229#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
230#[serde(tag = "type", rename_all = "snake_case")]
231pub enum Request {
232    /// Start a turn: persist the text as a user message and run the loop until
233    /// it stops. The run's progress and result stream back as [`AgentEvent`]s.
234    Submit { text: String },
235
236    /// Append `content` to the conversation *without* starting a turn (recorded
237    /// now if idle, or at the next turn boundary if a run is in flight). The
238    /// "tell, don't ask" delivery mode — `Agent::notify`.
239    Notify { content: String },
240
241    /// Inject `content` at the next turn boundary of the in-flight run — a soft
242    /// interrupt that does not cancel the run. Formerly `Steer`; `"steer"`
243    /// still deserializes here.
244    #[serde(alias = "steer")]
245    Interrupt { content: String },
246
247    /// Wake the session: run `content` as a turn **even if it is idle** (mid-run
248    /// it rides the follow-up channel instead). Formerly `FollowUp`;
249    /// `"follow_up"` still deserializes here.
250    /// `"follow_up"` still deserializes here.
251    #[serde(alias = "follow_up")]
252    Wake { content: String },
253
254    /// Cancel the in-flight run (and any retry/backoff wait). Idempotent.
255    Cancel,
256
257    /// Swap the model for subsequent turns.
258    SetModel { model: String },
259
260    /// Set the reasoning effort, or clear it (`None` = send nothing).
261    SetEffort { effort: Option<String> },
262
263    /// Summarize the older prefix of the conversation now, optionally focused
264    /// by `instructions`.
265    Compact { instructions: Option<String> },
266
267    /// Toggle plan mode. The actor flips the agent's shared `PlanModeHandle`
268    /// (removing mutating tools + mutating `bash`) and recomposes the system
269    /// prompt. Infallible — replies [`AgentEvent::Ack`].
270    SetPlanMode { on: bool },
271
272    /// Ask a side question (`/btw`): answer `text` tool-free, from the current
273    /// context, WITHOUT recording it. A read — carries user content, names no
274    /// `AgentMessage` (see the enum doc above). Reply:
275    /// [`AgentEvent::SideAnswer`]. A `SideAsk` arriving mid-run is answered from
276    /// the latest turn-boundary snapshot (like `GetHistory`), not refused.
277    SideAsk { text: String },
278    /// Read back the conversation so far. Reply:
279    /// [`AgentEvent::History`].
280    GetHistory,
281
282    /// A compact read of the session's latest activity — the text of its most
283    /// recent assistant message — WITHOUT shipping the transcript (unlike
284    /// [`Request::GetHistory`]). A `member`-style peek: the reply is one small
285    /// string, not the whole history. Reply: [`AgentEvent::Status`].
286    Status,
287
288    /// Read this session's usage report: turns, summed tokens, the cache hit
289    /// rate, per-tool `calls`/`errors`/`result_bytes`, and a `$` cost when the
290    /// model is priced — WITHOUT shipping the transcript (unlike
291    /// [`Request::GetHistory`]). The [`Request::Status`] rationale applies: a
292    /// folded summary, one small payload, no baseline needed on the client.
293    ///
294    /// Answered from the actor's own `Agent`/`SideHandle`, which is where the
295    /// provider lives (`agent.rs:410` `llm: LlmOpts,`), so the actor — not the
296    /// front-end — prices the session. A `Usage` arriving mid-run is answered
297    /// from the turn-boundary snapshot (like `GetHistory`), never deferred.
298    /// Reply: [`AgentEvent::Usage`].
299    ///
300    /// On a remote peer that predates the variant, `#[serde(other)] Unknown`
301    /// catches it and the actor answers `Ack` — read as "unavailable", NOT as
302    /// zero usage (WS-D/WS-E decide the rendering).
303    Usage,
304
305    /// Ask the **transport** for the sessions a server serves — serve order,
306    /// root first. The one request that names no `Agent` method: an in-process
307    /// session has no roster, so the actor answers it with [`AgentEvent::Ack`]
308    /// (like [`Request::Unknown`]); a socket server intercepts it and replies
309    /// [`AgentEvent::Sessions`].
310    ListSessions,
311
312    /// Ask the **transport** for the model catalog the provider advertises
313    /// (`streamfn::list_models`). Mirrors [`Request::ListSessions`]: it names
314    /// no `Agent` method, so an in-process session answers it with
315    /// [`crate::event::AgentEvent::Ack`] (like [`Request::Unknown`]); a socket
316    /// server intercepts it and replies [`crate::event::AgentEvent::Models`].
317    ListModels,
318
319    /// Define a worker **on a served peer** (§8, S4). Like [`Request::ListSessions`]
320    /// it names no `Agent` method: a socket server intercepts it and asks an
321    /// injected handler to build a session, replying [`AgentEvent::Spawned`] with
322    /// its address (or a correlated [`AgentEvent::Error`]). Mirrors the CLI's
323    /// worker spec, so a peer can customize the worker's model, role, tool set,
324    /// `read_only`, `effort`, and provider. An in-process session has no
325    /// factory, so the actor answers
326    /// it with [`AgentEvent::Error`].
327    Define {
328        /// The worker's address; auto-assigned (`w1`, `w2`, …) when absent.
329        name: Option<String>,
330        /// Model id override; `None` inherits the server's model.
331        model: Option<String>,
332        /// Role text appended to the worker's system prompt.
333        role: Option<String>,
334        /// Tool allow-list; `None` = the full default set.
335        tools: Option<Vec<String>>,
336        /// Provider base URL override; `None` inherits the server's.
337        base_url: Option<String>,
338        /// Provider API key override; `None` inherits the server's.
339        api_key: Option<String>,
340        /// Enforce read-only for the defined worker (D1/D2); default false.
341        #[serde(default)]
342        read_only: bool,
343        /// Reasoning-effort override (D3); `None` inherits, synonyms clear.
344        #[serde(default)]
345        effort: Option<String>,
346    },
347
348    /// Forward-compatibility catch-all: an older peer must skip a request it
349    /// does not understand rather than fail the connection.
350    #[serde(other)]
351    Unknown,
352}
353
354/// Versioned, addressed envelope around a [`Request`] or an [`AgentEvent`].
355///
356/// Generic over the body so the same frame carries either direction: the
357/// request-to-a-session frame and the event-from-a-session frame have identical
358/// headers. The body is `#[serde(flatten)]`ed, so on the wire a frame is one
359/// flat JSON object — `{"v":1,"id":7,"session":"s1","type":"cancel"}`.
360#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
361pub struct Frame<P> {
362    /// Protocol major version ([`PROTOCOL_VERSION`]).
363    pub v: u32,
364    /// Sender-assigned id, monotonic per connection; answers echo it in
365    /// `reply_to`.
366    pub id: u64,
367    /// The request this frame answers, if any. Streaming events that are not
368    /// direct replies leave it absent.
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub reply_to: Option<u64>,
371    /// The session this frame concerns — the target of a request, the origin of
372    /// an event. The whole addressing scheme.
373    pub session: SessionId,
374    /// The sender's address, when it is not the transport's own client (an
375    /// in-process handle leaves it unset; an A2A peer sets its `"agent:<id>"`).
376    #[serde(default, skip_serializing_if = "Option::is_none")]
377    pub sender: Option<SessionId>,
378    #[serde(flatten)]
379    pub body: P,
380}
381
382impl<P> Frame<P> {
383    /// A fresh top-level frame at the current version, not a reply.
384    pub fn new(id: u64, session: SessionId, body: P) -> Self {
385        Self {
386            v: PROTOCOL_VERSION,
387            id,
388            reply_to: None,
389            session,
390            sender: None,
391            body,
392        }
393    }
394}
395
396/// A client-to-session frame.
397pub type RequestFrame = Frame<Request>;
398/// A session-to-client frame.
399pub type EventFrame = Frame<AgentEvent>;
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404    use crate::event::{TodoItem, TodoStatus};
405    use serde::de::DeserializeOwned;
406    use serde_json::json;
407
408    fn roundtrip<P>(p: P, expected_tag: &str)
409    where
410        P: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug,
411    {
412        let v = serde_json::to_value(&p).unwrap();
413        assert_eq!(v["type"], expected_tag);
414        let back: P = serde_json::from_value(v).unwrap();
415        assert_eq!(back, p);
416    }
417
418    #[test]
419    fn request_roundtrip_all_variants() {
420        roundtrip(Request::Submit { text: "hi".into() }, "submit");
421        roundtrip(Request::Cancel, "cancel");
422        roundtrip(Request::SetModel { model: "m1".into() }, "set_model");
423        roundtrip(
424            Request::SetEffort {
425                effort: Some("high".into()),
426            },
427            "set_effort",
428        );
429        roundtrip(Request::SetEffort { effort: None }, "set_effort");
430        roundtrip(
431            Request::Compact {
432                instructions: Some("focus on the parser".into()),
433            },
434            "compact",
435        );
436        roundtrip(Request::Compact { instructions: None }, "compact");
437        roundtrip(Request::SetPlanMode { on: true }, "set_plan_mode");
438        roundtrip(Request::Notify { content: "n".into() }, "notify");
439        roundtrip(Request::Interrupt { content: "i".into() }, "interrupt");
440        roundtrip(Request::Wake { content: "w".into() }, "wake");
441        roundtrip(Request::SideAsk { text: "why?".into() }, "side_ask");
442        roundtrip(Request::Status, "status");
443        roundtrip(Request::Usage, "usage");
444        roundtrip(Request::ListSessions, "list_sessions");
445        roundtrip(Request::ListModels, "list_models");
446        roundtrip(
447            Request::Define {
448                name: Some("w1".into()),
449                model: Some("m".into()),
450                role: Some("reviewer".into()),
451                tools: Some(vec!["read".into()]),
452                base_url: Some("http://w/v1".into()),
453                api_key: Some("k".into()),
454                read_only: true,
455                effort: Some("high".into()),
456            },
457            "define",
458        );
459        roundtrip(
460            Request::Define {
461                name: None,
462                model: None,
463                role: None,
464                tools: None,
465                base_url: None,
466                api_key: None,
467                read_only: false,
468                effort: None,
469            },
470            "define",
471        );
472    }
473
474    #[test]
475    fn usage_request_roundtrips_with_costs() {
476        roundtrip(Request::Usage, "usage");
477        roundtrip(
478            AgentEvent::Usage {
479                stats: crate::stats::SessionStats {
480                    turns: 1,
481                    input_tokens: 1_000,
482                    output_tokens: 500,
483                    cache_read_tokens: 400,
484                    cache_turns: 1,
485                    tool_errors: 1,
486                    cost: Some(crate::stats::Cost {
487                        micro_usd: 391,
488                        unpriced_turns: 0,
489                    }),
490                    ..Default::default()
491                },
492            },
493            "usage",
494        );
495        let frame = RequestFrame::new(7, SessionId::new("s1"), Request::Usage);
496        let back: RequestFrame =
497            serde_json::from_value(serde_json::to_value(&frame).unwrap()).unwrap();
498        assert_eq!(back, frame);
499    }
500
501    #[test]
502    fn list_models_roundtrips_and_session_info_carries_effort_and_window() {
503        roundtrip(Request::ListModels, "list_models");
504
505        let info = SessionInfo {
506            id: SessionId::new("root"),
507            model: Some("m1".into()),
508            effort: Some("high".into()),
509            context_window: Some(200_000),
510            state: MemberState::Idle,
511        };
512        let v = serde_json::to_value(&info).unwrap();
513        assert_eq!(v["effort"], "high");
514        assert_eq!(v["context_window"], 200_000);
515        assert_eq!(serde_json::from_value::<SessionInfo>(v).unwrap(), info);
516
517        // Absent effort/window round-trip to None (older peer / unset) ...
518        let bare: SessionInfo = serde_json::from_value(json!({"id": "w1"})).unwrap();
519        assert!(bare.effort.is_none() && bare.context_window.is_none());
520        // ... and `skip_serializing_if` keeps them OFF the wire when None.
521        let out = serde_json::to_value(SessionInfo {
522            id: SessionId::new("w1"),
523            model: None,
524            effort: None,
525            context_window: None,
526            state: MemberState::Idle,
527        })
528        .unwrap();
529        assert!(out.get("effort").is_none() && out.get("context_window").is_none());
530    }
531
532    #[test]
533    fn legacy_verb_tags_deserialize_to_canonical_variants() {
534        let steer: Request = serde_json::from_str(r#"{"type":"steer","content":"s"}"#).unwrap();
535        assert_eq!(steer, Request::Interrupt { content: "s".into() });
536        let follow: Request = serde_json::from_str(r#"{"type":"follow_up","content":"f"}"#).unwrap();
537        assert_eq!(follow, Request::Wake { content: "f".into() });
538    }
539
540    #[test]
541    fn request_unknown_tag_is_caught_not_fatal() {
542        let back: Request = serde_json::from_str(r#"{"type":"from_the_future"}"#).unwrap();
543        assert_eq!(back, Request::Unknown);
544    }
545
546    #[test]
547    fn is_inbound_marks_only_the_delivery_verbs() {
548        assert!(is_inbound(&Request::Notify { content: "x".into() }));
549        assert!(is_inbound(&Request::Interrupt { content: "x".into() }));
550        assert!(is_inbound(&Request::Wake { content: "x".into() }));
551        assert!(!is_inbound(&Request::Submit { text: "x".into() }));
552        assert!(!is_inbound(&Request::GetHistory));
553        assert!(!is_inbound(&Request::Status));
554        assert!(!is_inbound(&Request::Usage));
555        assert!(!is_inbound(&Request::SideAsk { text: "x".into() }));
556        assert!(!is_inbound(&Request::SetPlanMode { on: true }));
557        assert!(!is_inbound(&Request::Cancel));
558        assert!(!is_inbound(&Request::ListSessions));
559        assert!(!is_inbound(&Request::ListModels));
560        assert!(!is_inbound(&Request::Define {
561            name: None,
562            model: None,
563            role: None,
564            tools: None,
565            base_url: None,
566            api_key: None,
567            read_only: false,
568            effort: None,
569        }));
570    }
571
572    #[test]
573    fn frame_flattens_body_and_omits_absent_reply_to() {
574        let f = Frame::new(7, SessionId::new("s1"), Request::Cancel);
575        let v = serde_json::to_value(&f).unwrap();
576        assert_eq!(
577            v,
578            json!({"v": PROTOCOL_VERSION, "id": 7, "session": "s1", "type": "cancel"})
579        );
580        let back: Frame<Request> = serde_json::from_value(v).unwrap();
581        assert_eq!(back, f);
582    }
583
584    #[test]
585    fn frame_carries_reply_to_and_an_event_body() {
586        let f = EventFrame {
587            v: PROTOCOL_VERSION,
588            id: 8,
589            reply_to: Some(7),
590            session: SessionId::from("s1"),
591            sender: None,
592            body: AgentEvent::AgentEnd,
593        };
594        let v = serde_json::to_value(&f).unwrap();
595        assert_eq!(
596            v,
597            json!({"v": PROTOCOL_VERSION, "id": 8, "reply_to": 7, "session": "s1", "type": "agent_end"})
598        );
599        // `AgentEvent` is not `PartialEq` (see event.rs); compare re-serialized
600        // JSON, matching that module's round-trip convention.
601        let back: EventFrame = serde_json::from_value(v.clone()).unwrap();
602        assert_eq!(serde_json::to_value(&back).unwrap(), v);
603    }
604
605    #[test]
606    fn frame_carries_a_todo_event_body() {
607        let f = EventFrame {
608            v: PROTOCOL_VERSION,
609            id: 9,
610            reply_to: None,
611            session: SessionId::from("s1"),
612            sender: None,
613            body: AgentEvent::Todo {
614                todos: vec![TodoItem {
615                    content: "write tests".into(),
616                    status: TodoStatus::Pending,
617                }],
618            },
619        };
620        let v = serde_json::to_value(&f).unwrap();
621        assert_eq!(
622            v,
623            json!({
624                "v": PROTOCOL_VERSION, "id": 9, "session": "s1", "type": "todo",
625                "todos": [{"content": "write tests", "status": "pending"}],
626            })
627        );
628        let back: EventFrame = serde_json::from_value(v.clone()).unwrap();
629        assert_eq!(serde_json::to_value(&back).unwrap(), v);
630    }
631
632    #[test]
633    fn session_id_serializes_transparently() {
634        assert_eq!(
635            serde_json::to_value(SessionId::new("abc")).unwrap(),
636            json!("abc")
637        );
638        assert_eq!(SessionId::new("abc").as_str(), "abc");
639        assert_eq!(SessionId::new("abc").to_string(), "abc");
640        assert_eq!(SessionId::from("x"), SessionId(String::from("x")));
641        assert_eq!(SessionId::user().as_str(), USER);
642        assert_eq!(SessionId::agent("abc").as_str(), "agent:abc");
643    }
644}