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///
215/// The one exception is [`Request::ListSessions`]: a transport-level probe the
216/// server answers, not an `Agent` method.
217///
218/// Inbound payloads carry user **content**, not an `AgentMessage`: a remote peer
219/// must not be able to inject an `Assistant`/`ToolResult` message and impersonate
220/// the model. The session wraps content as a user message, exactly as
221/// `Agent::run` does. `GetHistory` is a read: it carries no payload and its
222/// answer comes back as [`AgentEvent::History`]
223/// (with the other replies — [`AgentEvent::Ack`],
224/// and [`AgentEvent::Error`] — alongside it).
225/// These reply variants are never *streamed*: they answer a specific request,
226/// which the transport correlates (an in-process oneshot today, the envelope's
227/// `reply_to` on the wire).
228#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
229#[serde(tag = "type", rename_all = "snake_case")]
230pub enum Request {
231    /// Start a turn: persist the text as a user message and run the loop until
232    /// it stops. The run's progress and result stream back as [`AgentEvent`]s.
233    Submit { text: String },
234
235    /// Append `content` to the conversation *without* starting a turn (recorded
236    /// now if idle, or at the next turn boundary if a run is in flight). The
237    /// "tell, don't ask" delivery mode — `Agent::notify`.
238    Notify { content: String },
239
240    /// Inject `content` at the next turn boundary of the in-flight run — a soft
241    /// interrupt that does not cancel the run. Formerly `Steer`; `"steer"`
242    /// still deserializes here.
243    #[serde(alias = "steer")]
244    Interrupt { content: String },
245
246    /// Wake the session: run `content` as a turn **even if it is idle** (mid-run
247    /// it rides the follow-up channel instead). Formerly `FollowUp`;
248    /// `"follow_up"` still deserializes here.
249    /// `"follow_up"` still deserializes here.
250    #[serde(alias = "follow_up")]
251    Wake { content: String },
252
253    /// Cancel the in-flight run (and any retry/backoff wait). Idempotent.
254    Cancel,
255
256    /// Swap the model for subsequent turns.
257    SetModel { model: String },
258
259    /// Set the reasoning effort, or clear it (`None` = send nothing).
260    SetEffort { effort: Option<String> },
261
262    /// Summarize the older prefix of the conversation now, optionally focused
263    /// by `instructions`.
264    Compact { instructions: Option<String> },
265
266    /// Toggle plan mode. The actor flips the agent's shared `PlanModeHandle`
267    /// (removing mutating tools + mutating `bash`) and recomposes the system
268    /// prompt. Infallible — replies [`AgentEvent::Ack`].
269    SetPlanMode { on: bool },
270
271    /// Ask a side question (`/btw`): answer `text` tool-free, from the current
272    /// context, WITHOUT recording it. A read — carries user content, names no
273    /// `AgentMessage` (see the enum doc above). Reply:
274    /// [`AgentEvent::SideAnswer`]. A `SideAsk` arriving mid-run is answered from
275    /// the latest turn-boundary snapshot (like `GetHistory`), not refused.
276    SideAsk { text: String },
277    /// Read back the conversation so far. Reply:
278    /// [`AgentEvent::History`].
279    GetHistory,
280
281    /// A compact read of the session's latest activity — the text of its most
282    /// recent assistant message — WITHOUT shipping the transcript (unlike
283    /// [`Request::GetHistory`]). A `member`-style peek: the reply is one small
284    /// string, not the whole history. Reply: [`AgentEvent::Status`].
285    Status,
286
287    /// Ask the **transport** for the sessions a server serves — serve order,
288    /// root first. The one request that names no `Agent` method: an in-process
289    /// session has no roster, so the actor answers it with [`AgentEvent::Ack`]
290    /// (like [`Request::Unknown`]); a socket server intercepts it and replies
291    /// [`AgentEvent::Sessions`].
292    ListSessions,
293
294    /// Ask the **transport** for the model catalog the provider advertises
295    /// (`streamfn::list_models`). Mirrors [`Request::ListSessions`]: it names
296    /// no `Agent` method, so an in-process session answers it with
297    /// [`crate::event::AgentEvent::Ack`] (like [`Request::Unknown`]); a socket
298    /// server intercepts it and replies [`crate::event::AgentEvent::Models`].
299    ListModels,
300
301    /// Define a worker **on a served peer** (§8, S4). Like [`Request::ListSessions`]
302    /// it names no `Agent` method: a socket server intercepts it and asks an
303    /// injected handler to build a session, replying [`AgentEvent::Spawned`] with
304    /// its address (or a correlated [`AgentEvent::Error`]). Mirrors the CLI's
305    /// worker spec, so a peer can customize the worker's model, role, tool set,
306    /// `read_only`, `effort`, and provider. An in-process session has no
307    /// factory, so the actor answers
308    /// it with [`AgentEvent::Error`].
309    Define {
310        /// The worker's address; auto-assigned (`w1`, `w2`, …) when absent.
311        name: Option<String>,
312        /// Model id override; `None` inherits the server's model.
313        model: Option<String>,
314        /// Role text appended to the worker's system prompt.
315        role: Option<String>,
316        /// Tool allow-list; `None` = the full default set.
317        tools: Option<Vec<String>>,
318        /// Provider base URL override; `None` inherits the server's.
319        base_url: Option<String>,
320        /// Provider API key override; `None` inherits the server's.
321        api_key: Option<String>,
322        /// Enforce read-only for the defined worker (D1/D2); default false.
323        #[serde(default)]
324        read_only: bool,
325        /// Reasoning-effort override (D3); `None` inherits, synonyms clear.
326        #[serde(default)]
327        effort: Option<String>,
328    },
329
330    /// Forward-compatibility catch-all: an older peer must skip a request it
331    /// does not understand rather than fail the connection.
332    #[serde(other)]
333    Unknown,
334}
335
336/// Versioned, addressed envelope around a [`Request`] or an [`AgentEvent`].
337///
338/// Generic over the body so the same frame carries either direction: the
339/// request-to-a-session frame and the event-from-a-session frame have identical
340/// headers. The body is `#[serde(flatten)]`ed, so on the wire a frame is one
341/// flat JSON object — `{"v":1,"id":7,"session":"s1","type":"cancel"}`.
342#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
343pub struct Frame<P> {
344    /// Protocol major version ([`PROTOCOL_VERSION`]).
345    pub v: u32,
346    /// Sender-assigned id, monotonic per connection; answers echo it in
347    /// `reply_to`.
348    pub id: u64,
349    /// The request this frame answers, if any. Streaming events that are not
350    /// direct replies leave it absent.
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub reply_to: Option<u64>,
353    /// The session this frame concerns — the target of a request, the origin of
354    /// an event. The whole addressing scheme.
355    pub session: SessionId,
356    /// The sender's address, when it is not the transport's own client (an
357    /// in-process handle leaves it unset; an A2A peer sets its `"agent:<id>"`).
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub sender: Option<SessionId>,
360    #[serde(flatten)]
361    pub body: P,
362}
363
364impl<P> Frame<P> {
365    /// A fresh top-level frame at the current version, not a reply.
366    pub fn new(id: u64, session: SessionId, body: P) -> Self {
367        Self {
368            v: PROTOCOL_VERSION,
369            id,
370            reply_to: None,
371            session,
372            sender: None,
373            body,
374        }
375    }
376}
377
378/// A client-to-session frame.
379pub type RequestFrame = Frame<Request>;
380/// A session-to-client frame.
381pub type EventFrame = Frame<AgentEvent>;
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386    use crate::event::{TodoItem, TodoStatus};
387    use serde::de::DeserializeOwned;
388    use serde_json::json;
389
390    fn roundtrip<P>(p: P, expected_tag: &str)
391    where
392        P: Serialize + DeserializeOwned + PartialEq + std::fmt::Debug,
393    {
394        let v = serde_json::to_value(&p).unwrap();
395        assert_eq!(v["type"], expected_tag);
396        let back: P = serde_json::from_value(v).unwrap();
397        assert_eq!(back, p);
398    }
399
400    #[test]
401    fn request_roundtrip_all_variants() {
402        roundtrip(Request::Submit { text: "hi".into() }, "submit");
403        roundtrip(Request::Cancel, "cancel");
404        roundtrip(Request::SetModel { model: "m1".into() }, "set_model");
405        roundtrip(
406            Request::SetEffort {
407                effort: Some("high".into()),
408            },
409            "set_effort",
410        );
411        roundtrip(Request::SetEffort { effort: None }, "set_effort");
412        roundtrip(
413            Request::Compact {
414                instructions: Some("focus on the parser".into()),
415            },
416            "compact",
417        );
418        roundtrip(Request::Compact { instructions: None }, "compact");
419        roundtrip(Request::SetPlanMode { on: true }, "set_plan_mode");
420        roundtrip(Request::Notify { content: "n".into() }, "notify");
421        roundtrip(Request::Interrupt { content: "i".into() }, "interrupt");
422        roundtrip(Request::Wake { content: "w".into() }, "wake");
423        roundtrip(Request::SideAsk { text: "why?".into() }, "side_ask");
424        roundtrip(Request::Status, "status");
425        roundtrip(Request::ListSessions, "list_sessions");
426        roundtrip(Request::ListModels, "list_models");
427        roundtrip(
428            Request::Define {
429                name: Some("w1".into()),
430                model: Some("m".into()),
431                role: Some("reviewer".into()),
432                tools: Some(vec!["read".into()]),
433                base_url: Some("http://w/v1".into()),
434                api_key: Some("k".into()),
435                read_only: true,
436                effort: Some("high".into()),
437            },
438            "define",
439        );
440        roundtrip(
441            Request::Define {
442                name: None,
443                model: None,
444                role: None,
445                tools: None,
446                base_url: None,
447                api_key: None,
448                read_only: false,
449                effort: None,
450            },
451            "define",
452        );
453    }
454
455    #[test]
456    fn list_models_roundtrips_and_session_info_carries_effort_and_window() {
457        roundtrip(Request::ListModels, "list_models");
458
459        let info = SessionInfo {
460            id: SessionId::new("root"),
461            model: Some("m1".into()),
462            effort: Some("high".into()),
463            context_window: Some(200_000),
464            state: MemberState::Idle,
465        };
466        let v = serde_json::to_value(&info).unwrap();
467        assert_eq!(v["effort"], "high");
468        assert_eq!(v["context_window"], 200_000);
469        assert_eq!(serde_json::from_value::<SessionInfo>(v).unwrap(), info);
470
471        // Absent effort/window round-trip to None (older peer / unset) ...
472        let bare: SessionInfo = serde_json::from_value(json!({"id": "w1"})).unwrap();
473        assert!(bare.effort.is_none() && bare.context_window.is_none());
474        // ... and `skip_serializing_if` keeps them OFF the wire when None.
475        let out = serde_json::to_value(SessionInfo {
476            id: SessionId::new("w1"),
477            model: None,
478            effort: None,
479            context_window: None,
480            state: MemberState::Idle,
481        })
482        .unwrap();
483        assert!(out.get("effort").is_none() && out.get("context_window").is_none());
484    }
485
486    #[test]
487    fn legacy_verb_tags_deserialize_to_canonical_variants() {
488        let steer: Request = serde_json::from_str(r#"{"type":"steer","content":"s"}"#).unwrap();
489        assert_eq!(steer, Request::Interrupt { content: "s".into() });
490        let follow: Request = serde_json::from_str(r#"{"type":"follow_up","content":"f"}"#).unwrap();
491        assert_eq!(follow, Request::Wake { content: "f".into() });
492    }
493
494    #[test]
495    fn request_unknown_tag_is_caught_not_fatal() {
496        let back: Request = serde_json::from_str(r#"{"type":"from_the_future"}"#).unwrap();
497        assert_eq!(back, Request::Unknown);
498    }
499
500    #[test]
501    fn is_inbound_marks_only_the_delivery_verbs() {
502        assert!(is_inbound(&Request::Notify { content: "x".into() }));
503        assert!(is_inbound(&Request::Interrupt { content: "x".into() }));
504        assert!(is_inbound(&Request::Wake { content: "x".into() }));
505        assert!(!is_inbound(&Request::Submit { text: "x".into() }));
506        assert!(!is_inbound(&Request::GetHistory));
507        assert!(!is_inbound(&Request::Status));
508        assert!(!is_inbound(&Request::SideAsk { text: "x".into() }));
509        assert!(!is_inbound(&Request::SetPlanMode { on: true }));
510        assert!(!is_inbound(&Request::Cancel));
511        assert!(!is_inbound(&Request::ListSessions));
512        assert!(!is_inbound(&Request::ListModels));
513        assert!(!is_inbound(&Request::Define {
514            name: None,
515            model: None,
516            role: None,
517            tools: None,
518            base_url: None,
519            api_key: None,
520            read_only: false,
521            effort: None,
522        }));
523    }
524
525    #[test]
526    fn frame_flattens_body_and_omits_absent_reply_to() {
527        let f = Frame::new(7, SessionId::new("s1"), Request::Cancel);
528        let v = serde_json::to_value(&f).unwrap();
529        assert_eq!(
530            v,
531            json!({"v": PROTOCOL_VERSION, "id": 7, "session": "s1", "type": "cancel"})
532        );
533        let back: Frame<Request> = serde_json::from_value(v).unwrap();
534        assert_eq!(back, f);
535    }
536
537    #[test]
538    fn frame_carries_reply_to_and_an_event_body() {
539        let f = EventFrame {
540            v: PROTOCOL_VERSION,
541            id: 8,
542            reply_to: Some(7),
543            session: SessionId::from("s1"),
544            sender: None,
545            body: AgentEvent::AgentEnd,
546        };
547        let v = serde_json::to_value(&f).unwrap();
548        assert_eq!(
549            v,
550            json!({"v": PROTOCOL_VERSION, "id": 8, "reply_to": 7, "session": "s1", "type": "agent_end"})
551        );
552        // `AgentEvent` is not `PartialEq` (see event.rs); compare re-serialized
553        // JSON, matching that module's round-trip convention.
554        let back: EventFrame = serde_json::from_value(v.clone()).unwrap();
555        assert_eq!(serde_json::to_value(&back).unwrap(), v);
556    }
557
558    #[test]
559    fn frame_carries_a_todo_event_body() {
560        let f = EventFrame {
561            v: PROTOCOL_VERSION,
562            id: 9,
563            reply_to: None,
564            session: SessionId::from("s1"),
565            sender: None,
566            body: AgentEvent::Todo {
567                todos: vec![TodoItem {
568                    content: "write tests".into(),
569                    status: TodoStatus::Pending,
570                }],
571            },
572        };
573        let v = serde_json::to_value(&f).unwrap();
574        assert_eq!(
575            v,
576            json!({
577                "v": PROTOCOL_VERSION, "id": 9, "session": "s1", "type": "todo",
578                "todos": [{"content": "write tests", "status": "pending"}],
579            })
580        );
581        let back: EventFrame = serde_json::from_value(v.clone()).unwrap();
582        assert_eq!(serde_json::to_value(&back).unwrap(), v);
583    }
584
585    #[test]
586    fn session_id_serializes_transparently() {
587        assert_eq!(
588            serde_json::to_value(SessionId::new("abc")).unwrap(),
589            json!("abc")
590        );
591        assert_eq!(SessionId::new("abc").as_str(), "abc");
592        assert_eq!(SessionId::new("abc").to_string(), "abc");
593        assert_eq!(SessionId::from("x"), SessionId(String::from("x")));
594        assert_eq!(SessionId::user().as_str(), USER);
595        assert_eq!(SessionId::agent("abc").as_str(), "agent:abc");
596    }
597}