Skip to main content

mlua_swarm_server/operator_ws/
protocol.rs

1//! Wire format (= S↔C JSON message schema) for `WS /v1/operators/:sid/ws`.
2//!
3//! `ServerMsg` = 4 messages the server pushes to the client (Ask / HookBefore /
4//! HookAfter / Spawn).
5//! `ClientMsg` = 4 messages the client replies with (Answer / HookAck / SpawnAck / SpawnHalt).
6//!
7//! ## Layer 2 audit (issue #7): halt vs error separation across verbs
8//!
9//! `spawn_halt` was added to disambiguate a controlled halt from a real
10//! worker error on the `spawn_ack` axis. The other client verbs were
11//! audited for the same shape:
12//!
13//! - **`answer`** (SeniorBridge.ask reply): carries `value` only — no
14//!   ok / failure axis exists. A "halt during a question" would already
15//!   be expressible by replying with a value that the middleware treats
16//!   as an abort signal (e.g. `null` or a domain-specific sentinel).
17//!   No sibling `answer_halt` is added.
18//! - **`hook_ack`** (SpawnHook.before OK/NG): `ok = false` here is a
19//!   genuine gate rejection — that is the entire purpose of the hook,
20//!   not a mix-signal. There is no confusion to fix; no `hook_halt` is
21//!   added.
22//! - **`spawn_ack`**: the subject of layer 1. `spawn_halt` handles it.
23//! For the parent module's message-flow figure, see the doc of `mod.rs`.
24//!
25//! `PendingReply` is the intermediate representation delivered over the internal
26//! `oneshot` reply channel, used to resolve a `ClientMsg` (arriving from a client)
27//! against the session's pending `HashMap` keyed by `req_id`.
28//! See `session::WSOperatorSession::resolve_pending` for details.
29
30use mlua_swarm::WorkerBinding;
31use serde::{Deserialize, Serialize};
32use serde_json::Value;
33
34// parent_req_id schema field carry: the engine middleware does not fire the
35// true nested-ask case (another ask running mid-ask), so this stays None.
36// The field is kept for schema compatibility; when a middleware extension
37// starts firing the true nested case, it can be reintroduced via task_local
38// or similar.
39pub(super) fn current_parent_req_id() -> Option<String> {
40    None
41}
42
43pub(super) fn default_ok_true() -> bool {
44    true
45}
46
47/// Server → client push messages on `WS /v1/operators/:sid/ws`. Each variant
48/// pairs with a `ClientMsg` reply carrying the same `req_id` (except
49/// `HookAfter`, which is fire-and-forget).
50#[derive(Debug, Serialize)]
51#[serde(tag = "type", rename_all = "snake_case")]
52pub enum ServerMsg {
53    /// `SeniorBridge.ask` request.
54    Ask {
55        /// Correlation key the client must echo back in `ClientMsg::Answer`.
56        req_id: String,
57        /// Reserved for nested-ask correlation; currently always `None`
58        /// (see [`current_parent_req_id`]).
59        #[serde(skip_serializing_if = "Option::is_none")]
60        parent_req_id: Option<String>,
61        /// Task the question originates from.
62        task_id: String,
63        /// Free-form question payload produced by the engine middleware.
64        question: Value,
65    },
66    /// `SpawnHook.before` request (= the client returns OK / NG via ack).
67    HookBefore {
68        /// Correlation key the client must echo back in `ClientMsg::HookAck`.
69        req_id: String,
70        /// Reserved for nested-ask correlation; currently always `None`.
71        #[serde(skip_serializing_if = "Option::is_none")]
72        parent_req_id: Option<String>,
73        /// Task whose spawn is being gated.
74        task_id: String,
75        /// Agent ref about to be spawned.
76        agent: String,
77        /// 1-based dispatch attempt counter for this agent step.
78        attempt: u32,
79    },
80    /// `SpawnHook.after` notification (= no client ack, fire-and-forget).
81    HookAfter {
82        /// Correlation key (informational only — no reply is expected).
83        req_id: String,
84        /// Reserved for nested-ask correlation; currently always `None`.
85        #[serde(skip_serializing_if = "Option::is_none")]
86        parent_req_id: Option<String>,
87        /// Task the spawn belonged to.
88        task_id: String,
89        /// Agent ref that was spawned.
90        agent: String,
91        /// 1-based dispatch attempt counter for this agent step.
92        attempt: u32,
93        /// Worker result payload observed after the spawn completed.
94        result: Value,
95    },
96    /// `Operator.execute` request (= delegates the whole spawn to an external
97    /// Operator, via `OperatorDelegateMiddleware`). The client replies with the
98    /// `WorkerResult`-equivalent (= value + ok) in `spawn_ack`.
99    ///
100    /// **Thin control channel** (the Spawn thin-control axis): the server sends only
101    /// the `capability_token`. `system_prompt` / `prompt` are NOT carried in the
102    /// WS payload. The MainAI (WS Client) forwards the token to the SubAgent,
103    /// and the SubAgent hits `/v1/worker/prompt` + `/v1/worker/result` itself
104    /// with `Authorization: Bearer <capability_token>` — fetching prompt /
105    /// system and posting the result (= heavy payloads go over HTTP; WS stays
106    /// purely thin control).
107    ///
108    /// `capability_token` is `CapToken::encode()` form (= URL-safe base64 of
109    /// serde_json): a session token with `Role::Worker` + `["*"]` scopes + 600s
110    /// TTL. The HMAC sig is verified server-side by `verify_token_for_task` —
111    /// a self-contained capability token (= no server lookup required).
112    ///
113    /// `directive` (= immediate instruction for the MainAI; fix for observation #7):
114    /// Under thin-push discipline, if the payload were only routing fields, the
115    /// MainAI (a large LLM) would fire the drift "I have a token → I should
116    /// fetch it myself" / "I got the prompt → I should embed it literally into
117    /// the SubAgent" 100% of the time (= bias accumulation across 50–100 parallel
118    /// agents dulls decisions). To structurally remove this drift, a literal
119    /// instruction text — "launch a SubAgent, hand it the token + endpoint, and
120    /// let the SubAgent do the fetch / execution / post" — is explicitly embedded
121    /// into the payload (= implicit convention → literal statement).
122    ///
123    /// This field carries **natural-language text intended for the MainAI to read**
124    /// (= not a JSON schema target for parsing). See
125    /// `operator_ws::session::default_spawn_directive()` for the server-side
126    /// default text.
127    Spawn {
128        /// Correlation key the client must echo back in `ClientMsg::SpawnAck`.
129        req_id: String,
130        /// Reserved for nested-ask correlation; currently always `None`.
131        #[serde(skip_serializing_if = "Option::is_none")]
132        parent_req_id: Option<String>,
133        /// Task the delegated spawn belongs to.
134        task_id: String,
135        /// Agent ref the Operator is asked to execute.
136        agent: String,
137        /// 1-based dispatch attempt counter for this agent step.
138        attempt: u32,
139        /// `CapToken::encode()` form Bearer credential for the worker HTTP
140        /// endpoints (see the variant doc above for the thin-control contract).
141        capability_token: String,
142        /// Short handle (= `wh-XXXXXXXX`, 12 chars). An alternate Bearer path
143        /// paired with `capability_token`. When `/v1/worker/submit` receives a
144        /// handle in Bearer, the server resolves nonce → `task_id` via the
145        /// `worker_handles` map (the short-handle switchover — removes
146        /// base64 copy-paste accidents). SubAgents (mse-worker) should use
147        /// **this field** instead of `capability_token` as the recommended path.
148        #[serde(skip_serializing_if = "Option::is_none")]
149        worker_handle: Option<String>,
150        /// Worker binding resolved from the Blueprint at compile time. `None`
151        /// never reaches the wire on the WS thin path (compile-time gate,
152        /// see `Operator::requires_worker_binding`), but the field stays
153        /// optional for forward compatibility.
154        #[serde(skip_serializing_if = "Option::is_none")]
155        worker: Option<WorkerBinding>,
156        /// Literal natural-language instruction for the MainAI (see the
157        /// variant doc above for why this is embedded in the payload).
158        directive: String,
159    },
160}
161
162/// Client → server reply messages on `WS /v1/operators/:sid/ws`. Each variant
163/// resolves the pending oneshot registered under its `req_id`
164/// (see [`super::session::WSOperatorSession::resolve_pending`]).
165#[derive(Debug, Deserialize)]
166#[serde(tag = "type", rename_all = "snake_case")]
167pub enum ClientMsg {
168    /// Reply to `ServerMsg::Ask` (`SeniorBridge.ask` result).
169    Answer {
170        /// Correlation key copied from the originating `ServerMsg::Ask`.
171        req_id: String,
172        /// Answer payload returned to the engine middleware.
173        value: Value,
174    },
175    /// Ack for `SpawnHook.before`. `ok=false` rejects the spawn
176    /// (= `MainAIMiddleware` converts it into `SpawnError::RejectedByMiddleware`).
177    /// `reason` propagates as `Err(reason)`.
178    HookAck {
179        /// Correlation key copied from the originating `ServerMsg::HookBefore`.
180        req_id: String,
181        /// `true` allows the spawn; `false` rejects it.
182        ok: bool,
183        /// Optional rejection reason surfaced to the engine when `ok=false`.
184        #[serde(default)]
185        reason: Option<String>,
186    },
187    /// Ack for `Operator.execute` (Spawn). `value = WorkerResult.value`,
188    /// `ok = WorkerResult.ok`. When `error` is `Some`, the `Operator` returns
189    /// it as `WorkerError`.
190    ///
191    /// After the thin-path switch (= the thin-control axis): if the MainAI returns this ack
192    /// **after** the SubAgent has hit HTTP `/v1/worker/result`, the server-side
193    /// dispatch path can complete with both the `Final` in `output_tail` and
194    /// this ack's `value` aligned. Sending an empty JSON `{}` for `value` makes
195    /// the `task.last_result` written by the HTTP path (= `post_result`)
196    /// canonical (= the ack-side `value` is duplicate / informational).
197    SpawnAck {
198        /// Correlation key copied from the originating `ServerMsg::Spawn`.
199        req_id: String,
200        /// `WorkerResult.value` equivalent; empty `{}` defers to the HTTP-path
201        /// result (see the variant doc above).
202        #[serde(default)]
203        value: Value,
204        /// `WorkerResult.ok` equivalent; defaults to `true` when omitted.
205        #[serde(default = "default_ok_true")]
206        ok: bool,
207        /// When `Some`, the Operator surfaces it as a `WorkerError`.
208        #[serde(default)]
209        error: Option<String>,
210    },
211    /// Controlled halt for the current spawn (issue #7). Distinct from
212    /// `SpawnAck { ok: false, error: Some(_) }`, which is the fail-loud
213    /// path for real worker errors. `spawn_halt` signals the operator's
214    /// intent to end the current spawn as a normal termination:
215    ///
216    /// - The step return value is `WorkerResult { value: <halt marker>,
217    ///   ok: true }` — no `WorkerError` is raised, so log level stays
218    ///   `info` and downstream retry logic doesn't fire.
219    /// - The optional `value` payload is merged into the halt marker
220    ///   under `value`, so partial results reach `final_ctx` verbatim.
221    /// - `reason` is a human-readable log line.
222    ///
223    /// The halt marker written to ctx has the shape:
224    /// ```json
225    /// { "halted": true, "reason": "<reason or null>", "value": <payload or {}> }
226    /// ```
227    /// Blueprint flows that need to short-circuit downstream steps on
228    /// halt can `branch` on `$.<step_out>.halted`.
229    ///
230    /// **Scope note**: this halts one spawn, not the whole swarm. For
231    /// swarm-wide cancellation see `swarm_cancel`.
232    SpawnHalt {
233        /// Correlation key copied from the originating `ServerMsg::Spawn`.
234        req_id: String,
235        /// Optional partial ctx value to carry into `WorkerResult.value`.
236        /// Merged under the `value` key of the halt marker; defaults to `{}`.
237        #[serde(default)]
238        value: Value,
239        /// Optional human-readable halt reason (for logs). Included in
240        /// the halt marker under `reason`.
241        #[serde(default)]
242        reason: Option<String>,
243    },
244}
245
246/// Intermediate representation for the session's `req_id` ↔ oneshot reply
247/// channel. The resolved form of `ClientMsg` looked up on the session side by
248/// `req_id` (= runtime-only, not wire format).
249pub(super) enum PendingReply {
250    /// Answer (return `Value` of `SeniorBridge.ask`).
251    Answer(Value),
252    /// `hook_ack` (OK / NG for `before`).
253    HookAck { ok: bool, reason: Option<String> },
254    /// `spawn_ack` (return of `Operator.execute` = `WorkerResult`-equivalent).
255    SpawnAck {
256        value: Value,
257        ok: bool,
258        error: Option<String>,
259    },
260    /// `spawn_halt` — controlled halt for the current spawn (issue #7).
261    /// See the `ClientMsg::SpawnHalt` doc for semantics.
262    SpawnHalt {
263        value: Value,
264        reason: Option<String>,
265    },
266}