objectiveai-sdk 2.2.15

ObjectiveAI SDK, definitions, and utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! Laboratory-host channel envelopes.
//!
//! Every machine runs ONE resident `objectiveai-laboratory` HOST
//! process per state, serving ALL of that machine's laboratories. The
//! host dials OUT to each configured daemon's `/laboratory` WebSocket.
//! The wire there is:
//!
//! 1. **[`HostIdentify`]** — the FIRST text frame, before any
//!    authorization: the host's state, its [machine
//!    identity](crate::machine::MachineIdentity), and the FULL list of
//!    laboratories it serves (one [`Identify`] each).
//! 2. The standard `AuthEnvelope` (`{"signature": …}`) — authorization
//!    strictly FOLLOWS identity.
//! 3. Then a correlated request/response protocol: the daemon sends
//!    [`ChannelRequest`]s (the [`super::RequestPayload`]
//!    vocabulary, verbatim, with `laboratory_id` addressing the lab)
//!    and the host answers with [`ChannelResponse`]s — plus
//!    uncorrelated host→daemon [`HostNotification`]s whenever the
//!    host's laboratory set changes (create/delete), so every
//!    connected daemon's view stays current without scanning.
//! 4. The HOST-initiated lane: the host sends a
//!    [`HostCommandRequest`] (its OWN id space, host-minted) to run a
//!    CLI command on the daemon, answered by a MULTI-FRAME stream of
//!    [`HostCommandResponse`]s sharing that id — grammar
//!    `Ack (Item|Error)* Done`. The exact same exchange the
//!    API↔daemon reverse channel carries as its `Command` payloads,
//!    mirrored here because the two channels stay naive to each
//!    other's vocabulary (see [`super::RequestPayload`]'s module
//!    docs).
//!
//! The daemon reaches laboratories in-process: the conduit and the
//! `laboratories` commands call the resident laboratory registry
//! directly (`LaboratoryRegistry::forward` / `::list`), which forwards
//! over the owning host's `/laboratory` WS and correlates the reply.
//! There is no local-vs-remote split: whichever host serves the
//! laboratory serves the traffic, one code path, wherever it runs —
//! machine identity is the only provenance.

use indexmap::IndexMap;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// One bind mount in a laboratory's identity.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.IdentifyMount")]
pub struct IdentifyMount {
    pub host: String,
    pub container: String,
}

/// One laboratory's spec, as carried by [`HostIdentify`] and by
/// [`HostNotification::LaboratoryCreated`]. Mirrors the `laboratories
/// create` spec so `laboratories list` can echo it verbatim.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.Identify")]
pub struct Identify {
    /// The RAW, state-agnostic laboratory id — never prefixed or
    /// namespaced (the host's state scopes its container NAMEs, but
    /// the identity on this wire is the bare id).
    pub id: String,
    pub image: crate::laboratories::LaboratoryImage,
    pub mounts: Vec<IdentifyMount>,
    pub env: Vec<[String; 2]>,
    pub cwd: String,
    /// Unix seconds when the laboratory container was created, from
    /// podman's own container record. Optional + defaulted so frames
    /// from hosts predating this field still parse.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(extend("omitempty" = true))]
    pub created_at: Option<i64>,
    /// For agent laboratories: the full id of the agent the
    /// laboratory derives from. `None` for user-created laboratories.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(extend("omitempty" = true))]
    pub agent_full_id: Option<String>,
    /// For plugin laboratories: the plugin's canonical coordinate
    /// trio (owner/name lowercased, version verbatim — the repo's
    /// `v`-prefixed git tag). `None` for every other laboratory.
    /// Optional + defaulted so frames from hosts predating this field
    /// still parse (the `created_at` precedent).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(extend("omitempty" = true))]
    pub plugin: Option<IdentifyPlugin>,
    /// For EPHEMERAL laboratories (agent and plugin): the
    /// agent-completion response id the laboratory serves — its id
    /// embeds it, and its lifetime is its single MCP connection's.
    /// `None` for regular laboratories. Optional + defaulted so
    /// frames from hosts predating this field still parse.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(extend("omitempty" = true))]
    pub response_id: Option<String>,
    /// Whether the laboratory's container is RUNNING right now. The
    /// lifecycle starts and stops containers on demand, and the host
    /// re-announces on every transition
    /// ([`HostNotification::LaboratoryUpdated`]), so consumers hold
    /// live state. Defaulted so frames from hosts predating this
    /// field still parse (as not-running).
    #[serde(default)]
    pub running: bool,
}

/// A plugin laboratory's canonical coordinate trio, as carried by
/// [`Identify::plugin`]: owner/name lowercased, version verbatim (it
/// IS the repo's `v`-prefixed, case-sensitive git tag) — exactly the
/// identity the laboratory host derived the laboratory id and image
/// tag from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.IdentifyPlugin")]
pub struct IdentifyPlugin {
    pub owner: String,
    pub name: String,
    pub version: String,
}

/// The `/laboratory` connection's FIRST frame: who this HOST is. Sent
/// BEFORE the `AuthEnvelope` — identity always precedes authorization.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.HostIdentify")]
pub struct HostIdentify {
    /// The state this host serves (its podman container names and
    /// locks are scoped to it). The daemon rejects hosts identifying a
    /// state other than its own.
    pub state: String,
    /// The machine this host runs on — the stable hashed id is the
    /// only provenance a laboratory has (there is no local-vs-remote).
    pub machine: crate::machine::MachineIdentity,
    /// EVERY laboratory this host serves right now, the full set. A
    /// reconnect re-sends the current set; later changes arrive as
    /// [`HostNotification`]s.
    pub laboratories: Vec<Identify>,
}

/// Daemon → host over the `/laboratory` WS: one correlated request.
/// `payload` is the reverse-attach vocabulary verbatim — the host is a
/// mini-conduit for all of its machine's laboratories.
///
/// `payload` is NESTED, never flattened: several payload variants
/// (e.g. `laboratory_create`) carry their own `id` field, which a
/// flatten would collide with the envelope's correlation `id` —
/// serialization emits the duplicate key, deserialization rejects it,
/// and the frame is silently dropped as forward-compat skip.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.ChannelRequest")]
pub struct ChannelRequest {
    /// Correlation id, minted by the daemon; echoed by the response.
    pub id: String,
    /// The laboratory this request addresses. `None` only for ops that
    /// are host-level rather than lab-level. The daemon stamps it in
    /// `LaboratoryRegistry::forward`; the host demuxes on it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(extend("omitempty" = true))]
    pub laboratory_id: Option<String>,
    /// The originating request's headers (e.g.
    /// `X-OBJECTIVEAI-RESPONSE-ID`, which keys the host's per-session
    /// MCP connections).
    pub headers: IndexMap<String, String>,
    pub payload: super::RequestPayload,
}

/// Host → daemon: the reply to a [`ChannelRequest`], correlated by
/// `id`. `payload` nested for the same collision reason as
/// [`ChannelRequest`].
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.ChannelResponse")]
pub struct ChannelResponse {
    pub id: String,
    pub payload: super::ResponsePayload,
}

// ── Wire framing ────────────────────────────────────────────────
//
// Chunk-bearing frames (`ImportWrite` requests, successful
// `ExportRead` replies) ride the BINARY sandwich of
// [`crate::binary_frame`]: the envelope's normal JSON (whose `data`
// field serde skips) is the header, the raw bytes follow. The choice
// is VARIANT-keyed — those variants are always binary, even with an
// empty payload — so both ends share one unambiguous rule. Everything
// else stays a plain JSON text frame.

impl ChannelRequest {
    fn wire_payload(&self) -> Option<&[u8]> {
        match &self.payload {
            super::RequestPayload::ImportWrite(req) => Some(&req.data),
            _ => None,
        }
    }

    /// Serialize for the wire: text for ordinary frames, the binary
    /// sandwich for chunk-bearing ones.
    pub fn to_wire(
        &self,
    ) -> Result<crate::binary_frame::WireFrame, serde_json::Error> {
        let header = serde_json::to_string(self)?;
        Ok(match self.wire_payload() {
            None => crate::binary_frame::WireFrame::Text(header),
            Some(payload) => crate::binary_frame::WireFrame::Binary(
                crate::binary_frame::encode(&header, payload),
            ),
        })
    }

    /// Parse a BINARY wire frame. `None` for anything that isn't a
    /// well-formed sandwich around a chunk-bearing request (dropped by
    /// receivers, the forward-compat posture).
    pub fn from_binary(frame: &[u8]) -> Option<Self> {
        let (header, payload) = crate::binary_frame::decode(frame)?;
        let mut parsed: Self = serde_json::from_str(header).ok()?;
        match &mut parsed.payload {
            super::RequestPayload::ImportWrite(req) => {
                req.data = payload.to_vec();
                Some(parsed)
            }
            _ => None,
        }
    }
}

impl ChannelResponse {
    fn wire_payload(&self) -> Option<&[u8]> {
        match &self.payload {
            // Both chunk-bearing replies: an export streams a live
            // container, a build drains a parked archive, and BOTH
            // carry their bytes out of band (the field is
            // `serde(skip)` — omitting a variant here silently ships
            // empty chunks).
            super::ResponsePayload::ExportRead(super::JsonRpcResult::Ok {
                result,
            })
            | super::ResponsePayload::BuildRead(super::JsonRpcResult::Ok {
                result,
            }) => Some(&result.data),
            _ => None,
        }
    }

    /// Serialize for the wire: text for ordinary frames, the binary
    /// sandwich for chunk-bearing ones.
    pub fn to_wire(
        &self,
    ) -> Result<crate::binary_frame::WireFrame, serde_json::Error> {
        let header = serde_json::to_string(self)?;
        Ok(match self.wire_payload() {
            None => crate::binary_frame::WireFrame::Text(header),
            Some(payload) => crate::binary_frame::WireFrame::Binary(
                crate::binary_frame::encode(&header, payload),
            ),
        })
    }

    /// Parse a BINARY wire frame. `None` for anything that isn't a
    /// well-formed sandwich around a chunk-bearing reply.
    pub fn from_binary(frame: &[u8]) -> Option<Self> {
        let (header, payload) = crate::binary_frame::decode(frame)?;
        let mut parsed: Self = serde_json::from_str(header).ok()?;
        match &mut parsed.payload {
            super::ResponsePayload::ExportRead(super::JsonRpcResult::Ok {
                result,
            })
            | super::ResponsePayload::BuildRead(super::JsonRpcResult::Ok {
                result,
            }) => {
                result.data = payload.to_vec();
                Some(parsed)
            }
            _ => None,
        }
    }
}

/// Host → daemon, UNCORRELATED: the host's laboratory set (or a
/// served laboratory's live file tree) changed. The daemon's pump
/// tries [`ChannelResponse`] first (it has `id`), then this —
/// notifications never carry a correlation id. Sent to EVERY daemon
/// the host is connected to, so all views stay current.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.HostNotification")]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum HostNotification {
    /// A laboratory was created on this host.
    #[schemars(title = "LaboratoryCreated")]
    LaboratoryCreated { laboratory: Identify },
    /// A laboratory's identity CHANGED — today that means its
    /// `running` state flipped (the lifecycle started or stopped its
    /// container). Daemons upsert exactly like `LaboratoryCreated`,
    /// so list subscribers hold live state.
    #[schemars(title = "LaboratoryUpdated")]
    LaboratoryUpdated { laboratory: Identify },
    /// A laboratory was deleted from this host.
    #[schemars(title = "LaboratoryDeleted")]
    LaboratoryDeleted { id: String },
    /// One live file-tree event from a laboratory this host watches:
    /// the host proxies the container MCP's `/filetree` SSE verbatim —
    /// every event it receives is forwarded here, unsolicited, to every
    /// connected daemon (which folds it into its own materialized tree
    /// and re-emits it on `/laboratories/{id}/filetree`). On attach the
    /// host sends a synthesized [`Snapshot`](crate::laboratories::filetree::FileTreeEvent::Snapshot)
    /// per watched laboratory, so a late-connecting daemon starts
    /// current — the same snapshot-then-deltas contract as the lab
    /// endpoint itself.
    #[schemars(title = "LaboratoryFiletree")]
    LaboratoryFiletree {
        id: String,
        event: crate::laboratories::filetree::FileTreeEvent,
    },
    /// A served laboratory's container MCP emitted a
    /// `tools/list_changed` or `resources/list_changed` on the session
    /// owned by `(this channel, response_id)`. Sent ONLY to the owning
    /// daemon channel, never broadcast — the session (and its
    /// daemon-side notifier) exists only there. The daemon relays it
    /// up the matching reverse channel; without this hop, container
    /// list-changed events would be silently dropped.
    #[schemars(title = "McpListChanged")]
    McpListChanged {
        /// The host-authoritative laboratory id.
        id: String,
        /// The owning session's agent-completion response id.
        response_id: String,
        kind: McpListChangedKind,
    },
}

/// Which catalog changed, for [`HostNotification::McpListChanged`] — a
/// deliberate LOCAL twin of the reverse channel's
/// `client_objectiveai_mcp.client_request.McpListChangedKind` (the two
/// vocabularies never import each other; the `CommandFrame` precedent).
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema,
)]
#[schemars(rename = "laboratories.daemon.McpListChangedKind")]
#[serde(rename_all = "snake_case")]
pub enum McpListChangedKind {
    Tools,
    Resources,
}

/// Host → daemon over the `/laboratory` WS: execute a CLI command on
/// the DAEMON on behalf of a plugin whose MCP server runs host-side —
/// the host-initiated twin of the reverse channel's `Command` payload,
/// working identically. Correlation `id` is HOST-minted and lives in
/// its own id space, unrelated to [`ChannelRequest`] ids (which the
/// daemon mints).
///
/// EVERY field is REQUIRED — no defaults, no header bags:
/// - `identity`: the calling agent's identity.
/// - `plugin`: the coordinates of the plugin whose MCP server
///   originated the command. The daemon stamps this trio on the
///   command's scope (this authenticated channel is, like the
///   conduit, a deliberate exception to "never trust wire plugin
///   identity") so the plugin run-gates apply.
/// - `request`: the typed CLI command to run.
///
/// Answered by a MULTI-FRAME reply: one [`HostCommandResponse`] per
/// event, sharing this request's `id`, streamed as items arrive —
/// grammar `Ack (Item|Error)* Done`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.HostCommandRequest")]
pub struct HostCommandRequest {
    /// Correlation id, minted by the HOST; echoed by every reply
    /// frame.
    pub id: String,
    pub identity: crate::identity::Identity,
    pub plugin: crate::mcp::server::Plugin,
    pub request: crate::cli::command::Request,
}

/// Daemon → host: one frame of the MULTI-FRAME reply to a
/// [`HostCommandRequest`], correlated by `id` — the only exchange on
/// this wire where one request id is answered by many frames.
///
/// Wire: `{"id":…,"frame":"item","item":{…}}` — `frame` is
/// [`CommandFrame`]'s tag, flattened beside the id (no field
/// collision: the frame carries no `id` of its own).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.HostCommandResponse")]
pub struct HostCommandResponse {
    pub id: String,
    #[serde(flatten)]
    pub frame: CommandFrame,
}

/// One frame of a [`HostCommandRequest`] exchange. The grammar is
/// `Ack (Item|Error)* Done` — mirroring the reverse channel's
/// `client_objectiveai_mcp.server_response.CommandFrame` (a deliberate
/// LOCAL twin: the two channels never import each other's vocabulary):
///
/// - [`CommandFrame::Ack`] — ALWAYS the opening frame, sent the
///   moment the daemon picks the request up, BEFORE the run starts.
/// - [`CommandFrame::Item`] — one typed command-output item, sent AS
///   IT ARRIVES (never collected, never delayed).
/// - [`CommandFrame::Error`] — a start failure or a stream error.
///   NON-terminal: the stream may keep yielding after one.
/// - [`CommandFrame::Done`] — ALWAYS the final frame, error or no.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.CommandFrame")]
#[serde(tag = "frame", rename_all = "snake_case")]
pub enum CommandFrame {
    Ack,
    Item {
        item: crate::cli::command::ResponseItem,
    },
    Error { error: String },
    Done,
}

// ── Per-plugin Postgres tunnel ───────────────────────────────────
//
// A plugin container connects to `OBJECTIVEAI_POSTGRES_URL` (a
// per-plugin TCP port the HOST listens on); the host tunnels those
// RAW Postgres wire bytes over this same `/laboratory` WS to the
// owning daemon, which dials its OWN configured Postgres as a client
// and pipes opaquely. The daemon binds no port. Auth/isolation is
// Postgres-native (the per-plugin compartment role); the frames below
// are a dumb byte pipe — they never parse the pgwire protocol, so a
// client's SSL negotiation rides through end to end.
//
// One `stream_id` (HOST-minted UUID) per plugin TCP connection. The
// control frames are TEXT; the byte payload is a BINARY sandwich
// (`crate::binary_frame`, header `{stream_id}`, raw bytes after).
// Disjoint serde tag key `"postgres"` keeps them out of the
// `HostNotification` (`type`) and `HostCommandRequest` parses.

/// Host → daemon control frames for a Postgres tunnel stream.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.HostPostgres")]
#[serde(tag = "postgres", rename_all = "snake_case")]
pub enum HostPostgres {
    /// A container opened a Postgres connection — the daemon should
    /// dial its cluster and attach this stream.
    Open { stream_id: String },
    /// The container socket ended (or the host is tearing the stream
    /// down); the daemon drops its Postgres socket for `stream_id`.
    Close { stream_id: String },
}

/// Daemon → host control frame for a Postgres tunnel stream — the
/// only direction-specific control frame (data rides [`PostgresData`]
/// both ways).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.DaemonPostgres")]
#[serde(tag = "postgres", rename_all = "snake_case")]
pub enum DaemonPostgres {
    /// Postgres EOF, a dial failure, or connection teardown; the host
    /// drops the container socket for `stream_id`.
    Close { stream_id: String },
}

/// Raw Postgres bytes for one tunnel stream, flowing in BOTH
/// directions. Rides the [`crate::binary_frame`] sandwich: the JSON
/// header carries `stream_id` (its `bytes` field is `#[serde(skip)]`),
/// the raw payload follows out of band.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[schemars(rename = "laboratories.daemon.PostgresData")]
pub struct PostgresData {
    pub stream_id: String,
    /// Raw Postgres wire bytes — never in the JSON header; rides the
    /// binary frame's payload.
    #[serde(skip)]
    pub bytes: Vec<u8>,
}

impl PostgresData {
    /// Serialize as the binary sandwich: `[u32 len][JSON header][raw
    /// bytes]`.
    pub fn to_wire(
        &self,
    ) -> Result<crate::binary_frame::WireFrame, serde_json::Error> {
        let header = serde_json::to_string(self)?;
        Ok(crate::binary_frame::WireFrame::Binary(
            crate::binary_frame::encode(&header, &self.bytes),
        ))
    }

    /// Parse a BINARY wire frame into a `PostgresData`. `None` for a
    /// malformed sandwich or a header that isn't this type (a
    /// `ChannelResponse`/`ChannelRequest` sandwich carries `id` /
    /// `payload`, so it won't deserialize here).
    pub fn from_binary(frame: &[u8]) -> Option<Self> {
        let (header, payload) = crate::binary_frame::decode(frame)?;
        let mut parsed: Self = serde_json::from_str(header).ok()?;
        parsed.bytes = payload.to_vec();
        Some(parsed)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The daemon's inbound demux tries [`ChannelResponse`] first,
    /// then [`HostCommandRequest`], then [`HostNotification`] — a
    /// command request must never satisfy the earlier parses.
    #[test]
    fn host_command_request_is_not_a_channel_response() {
        let request = HostCommandRequest {
            id: "cmd-1".to_string(),
            identity: Default::default(),
            plugin: crate::mcp::server::Plugin {
                owner: "acme".to_string(),
                name: "widgets".to_string(),
                version: "1.2.3".to_string(),
            },
            request: crate::cli::command::Request::Update(
                crate::cli::command::update::Request {
                    path_type: crate::cli::command::update::Path::Update,
                    base: crate::cli::command::RequestBase {
                        jq: None,
                        python: None,
                        timeout_seconds: None,
                        max_tokens: None,
                    },
                },
            ),
        };
        let text = serde_json::to_string(&request).unwrap();
        assert!(serde_json::from_str::<ChannelResponse>(&text).is_err());
        let parsed: HostCommandRequest = serde_json::from_str(&text).unwrap();
        assert_eq!(parsed.id, "cmd-1");
        assert_eq!(parsed.plugin.owner, "acme");
    }

    /// Frame tags ride flattened beside the envelope id.
    #[test]
    fn host_command_response_wire_shape() {
        let ack = HostCommandResponse {
            id: "cmd-1".to_string(),
            frame: CommandFrame::Ack,
        };
        assert_eq!(
            serde_json::to_string(&ack).unwrap(),
            r#"{"id":"cmd-1","frame":"ack"}"#,
        );
        let error = HostCommandResponse {
            id: "cmd-1".to_string(),
            frame: CommandFrame::Error {
                error: "boom".to_string(),
            },
        };
        assert_eq!(
            serde_json::to_string(&error).unwrap(),
            r#"{"id":"cmd-1","frame":"error","error":"boom"}"#,
        );
        let done: HostCommandResponse =
            serde_json::from_str(r#"{"id":"cmd-1","frame":"done"}"#).unwrap();
        assert!(matches!(done.frame, CommandFrame::Done));
    }

    /// A `HostPostgres::Open` text frame must satisfy NONE of the
    /// earlier demux parses (its `"postgres"` tag is disjoint from
    /// `id`/`payload`/`type`).
    #[test]
    fn host_postgres_open_is_disjoint() {
        let open = HostPostgres::Open {
            stream_id: "pg-1".to_string(),
        };
        let text = serde_json::to_string(&open).unwrap();
        assert_eq!(text, r#"{"postgres":"open","stream_id":"pg-1"}"#);
        assert!(serde_json::from_str::<ChannelResponse>(&text).is_err());
        assert!(serde_json::from_str::<ChannelRequest>(&text).is_err());
        assert!(serde_json::from_str::<HostCommandRequest>(&text).is_err());
        assert!(serde_json::from_str::<HostNotification>(&text).is_err());
    }

    /// `PostgresData` round-trips through the binary sandwich, and a
    /// `ChannelResponse` sandwich is NOT mistaken for one (its header
    /// carries `id`/`payload`, not `stream_id`).
    #[test]
    fn postgres_data_binary_round_trip() {
        let data = PostgresData {
            stream_id: "pg-1".to_string(),
            bytes: vec![0, 1, 2, 255, 254],
        };
        let crate::binary_frame::WireFrame::Binary(frame) = data.to_wire().unwrap()
        else {
            panic!("PostgresData must serialize as a binary sandwich");
        };
        let parsed = PostgresData::from_binary(&frame).unwrap();
        assert_eq!(parsed.stream_id, "pg-1");
        assert_eq!(parsed.bytes, vec![0, 1, 2, 255, 254]);
        // A chunk-bearing ChannelResponse sandwich must not parse here.
        let chan = ChannelResponse {
            id: "c-1".to_string(),
            payload: super::super::ResponsePayload::ExportRead(
                super::super::JsonRpcResult::Ok {
                    result: super::super::ExportChunk {
                        data: vec![9, 9, 9],
                        eof: false,
                    },
                },
            ),
        };
        let crate::binary_frame::WireFrame::Binary(chan_frame) =
            chan.to_wire().unwrap()
        else {
            panic!("chunk-bearing ChannelResponse is binary");
        };
        assert!(PostgresData::from_binary(&chan_frame).is_none());
    }
}