bmux_plugin_sdk 0.0.1-alpha.1

Plugin SDK for bmux — the types and traits plugin authors need
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! Plugin context types and the [`ServiceCaller`] trait.
//!
//! These types are passed to plugin methods by the host runtime.  The struct
//! fields carry everything a plugin might need — from the immediate command
//! name and arguments to the full service registry and host metadata.
//!
//! # Which fields matter?
//!
//! Most plugins only touch a handful of fields.  The rest are available for
//! advanced introspection or cross-plugin service calls.
//!
//! | Importance | Fields |
//! |------------|--------|
//! | **Always used** | `plugin_id`, `command`, `arguments` (commands) / `request` (services) |
//! | **For host API calls** | `services`, `host_kernel_bridge` (used internally by `HostRuntimeApi`) |
//! | **For introspection** | `registered_plugins`, `enabled_plugins`, `available_capabilities` |
//! | **Advanced** | `plugin_search_roots`, `settings`, `plugin_settings_map` |

use crate::{
    HostConnectionInfo, HostMetadata, PluginError, RegisteredService, Result, ServiceRequest,
    decode_service_message, encode_service_message,
};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

// ── Serde helpers for toml::Value over binary codecs ─────────────────────────
//
// `toml::Value` requires `deserialize_any` which is unsupported by
// non-self-describing formats like bincode/bmux_codec.  These modules
// serialize values as JSON text strings so they survive the binary round-trip.

mod toml_value_option {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    #[allow(clippy::ref_option)] // serde `with` modules require `&T` for the field type
    pub fn serialize<S: Serializer>(
        value: &Option<toml::Value>,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        let text: Option<String> = value
            .as_ref()
            .map(serde_json::to_string)
            .transpose()
            .map_err(serde::ser::Error::custom)?;
        text.serialize(serializer)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Option<toml::Value>, D::Error> {
        let text: Option<String> = Option::deserialize(deserializer)?;
        text.map(|s| serde_json::from_str(&s))
            .transpose()
            .map_err(serde::de::Error::custom)
    }
}

mod toml_value_map {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::collections::BTreeMap;

    pub fn serialize<S: Serializer>(
        map: &BTreeMap<String, toml::Value>,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        let text_map: BTreeMap<String, String> = map
            .iter()
            .map(|(k, v)| serde_json::to_string(v).map(|s| (k.clone(), s)))
            .collect::<Result<_, _>>()
            .map_err(serde::ser::Error::custom)?;
        text_map.serialize(serializer)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<BTreeMap<String, toml::Value>, D::Error> {
        let text_map: BTreeMap<String, String> = BTreeMap::deserialize(deserializer)?;
        text_map
            .into_iter()
            .map(|(k, s)| {
                serde_json::from_str(&s)
                    .map(|v| (k, v))
                    .map_err(serde::de::Error::custom)
            })
            .collect()
    }
}

/// Serializable summary of a registered plugin, carried through command and
/// lifecycle contexts so plugins can introspect the full plugin registry
/// without re-scanning the filesystem.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RegisteredPluginInfo {
    pub id: String,
    pub display_name: String,
    pub version: String,
    pub bundled_static: bool,
    pub required_capabilities: Vec<String>,
    pub provided_capabilities: Vec<String>,
    pub commands: Vec<String>,
    #[serde(default)]
    pub command_schemas: Vec<crate::PluginCommand>,
}

/// A keybinding that is active for the current command invocation context.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActiveKeybinding {
    /// Binding scope, such as `global`, `scroll`, or the active mode id.
    pub scope: String,
    /// Human-readable chord, such as `Ctrl-A q`.
    pub chord: String,
    /// Canonical action string dispatched by this binding.
    pub action: String,
}

/// Context passed to [`RustPlugin::activate`] and [`RustPlugin::deactivate`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NativeLifecycleContext {
    /// The plugin's own ID (e.g. `"bmux.clipboard"`).
    pub plugin_id: String,
    /// Capabilities this plugin declared as required in its manifest.
    #[serde(default)]
    pub required_capabilities: Vec<String>,
    /// Capabilities this plugin provides to other plugins.
    #[serde(default)]
    pub provided_capabilities: Vec<String>,
    /// Registered services visible to this plugin for cross-plugin calls.
    #[serde(default)]
    pub services: Vec<RegisteredService>,
    /// All capabilities available in the current host environment.
    #[serde(default)]
    pub available_capabilities: Vec<String>,
    /// IDs of all currently enabled plugins.
    #[serde(default)]
    pub enabled_plugins: Vec<String>,
    /// Filesystem roots where plugin manifests are discovered.
    #[serde(default)]
    pub plugin_search_roots: Vec<String>,
    /// Summary of all registered plugins (for introspection).
    #[serde(default)]
    pub registered_plugins: Vec<RegisteredPluginInfo>,
    /// Host runtime metadata (product name, version, API version).
    pub host: HostMetadata,
    /// Host connection paths (config dir, runtime dir, data dir, state dir).
    pub connection: HostConnectionInfo,
    /// Plugin-specific settings from the host configuration.
    #[serde(default, with = "toml_value_option")]
    pub settings: Option<toml::Value>,
    /// Settings map for all plugins (keyed by plugin ID).
    #[serde(default, with = "toml_value_map")]
    pub plugin_settings_map: BTreeMap<String, toml::Value>,
    /// Opaque handle for dispatching calls to the host kernel (internal use).
    #[serde(default)]
    pub host_kernel_bridge: Option<HostKernelBridge>,
}

/// Context passed to [`RustPlugin::run_command`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NativeCommandContext {
    /// The plugin's own ID (e.g. `"bmux.clipboard"`).
    pub plugin_id: String,
    /// The command name being invoked (e.g. `"hello"`, `"list-windows"`).
    pub command: String,
    /// Positional and flag arguments passed to the command.
    pub arguments: Vec<String>,
    /// Capabilities this plugin declared as required in its manifest.
    #[serde(default)]
    pub required_capabilities: Vec<String>,
    /// Capabilities this plugin provides to other plugins.
    #[serde(default)]
    pub provided_capabilities: Vec<String>,
    /// Registered services visible to this plugin for cross-plugin calls.
    #[serde(default)]
    pub services: Vec<RegisteredService>,
    /// All capabilities available in the current host environment.
    #[serde(default)]
    pub available_capabilities: Vec<String>,
    /// IDs of all currently enabled plugins.
    #[serde(default)]
    pub enabled_plugins: Vec<String>,
    /// Filesystem roots where plugin manifests are discovered.
    #[serde(default)]
    pub plugin_search_roots: Vec<String>,
    /// Summary of all registered plugins (for introspection).
    #[serde(default)]
    pub registered_plugins: Vec<RegisteredPluginInfo>,
    /// Keybindings active for this command invocation, if the host has an
    /// interactive keymap context.
    #[serde(default)]
    pub active_keybindings: Vec<ActiveKeybinding>,
    /// Host runtime metadata (product name, version, API version).
    pub host: HostMetadata,
    /// Host connection paths (config dir, runtime dir, data dir, state dir).
    pub connection: HostConnectionInfo,
    /// Plugin-specific settings from the host configuration.
    #[serde(default, with = "toml_value_option")]
    pub settings: Option<toml::Value>,
    /// Settings map for all plugins (keyed by plugin ID).
    #[serde(default, with = "toml_value_map")]
    pub plugin_settings_map: BTreeMap<String, toml::Value>,
    /// Identifier of the client that issued this command (the
    /// connected-client id, not a plugin id). `None` for
    /// server-internal invocations where no specific client is
    /// associated.
    #[serde(default)]
    pub caller_client_id: Option<uuid::Uuid>,
    /// How the host dispatched this command.
    ///
    /// Plugins use this to decide whether writing to `stdout` is
    /// safe. For [`NativeCommandInvocationSource::Cli`] the host
    /// stdout is the user's terminal in cooked mode and writes are
    /// appropriate. For
    /// [`NativeCommandInvocationSource::AttachKeybinding`] the host
    /// terminal is in raw mode rendering a TUI; direct writes would
    /// corrupt pane content and plugins should return their output as
    /// structured data (or stay silent and rely on host-side state
    /// observation).
    #[serde(default)]
    pub invocation_source: NativeCommandInvocationSource,
    /// Opaque handle for dispatching calls to the host kernel (internal use).
    #[serde(default)]
    pub host_kernel_bridge: Option<HostKernelBridge>,
}

/// How a plugin command was dispatched by the host.
///
/// This tells the plugin which surfaces are safe to write to:
/// `stdout`/`stderr` are TTY-safe for [`Self::Cli`], but the same
/// writes corrupt pane rendering when the host is in attach mode
/// ([`Self::AttachKeybinding`]).
///
/// The default is [`Self::Unknown`] so pre-existing serialized
/// contexts (or hosts that haven't been updated) round-trip
/// without changing behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum NativeCommandInvocationSource {
    /// The invocation source was not communicated by the host. Plugins
    /// should treat this as "assume stdout may be a TTY in raw mode"
    /// and avoid direct writes for safety.
    #[default]
    Unknown,
    /// Dispatched from a standalone CLI invocation
    /// (`bmux <plugin> <command>`). The host stdout is an ordinary
    /// terminal or pipe; `println!` is appropriate.
    Cli,
    /// Dispatched from a keybinding while the host is rendering the
    /// attach TUI in raw mode. Plugins must not write to stdout/stderr.
    AttachKeybinding,
    /// Dispatched via host-internal automation (tests, bridges). The
    /// plugin should follow the same silence rules as
    /// [`Self::AttachKeybinding`].
    Internal,
}

/// Context passed to [`RustPlugin::invoke_service`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NativeServiceContext {
    /// The plugin's own ID (e.g. `"bmux.clipboard"`).
    pub plugin_id: String,
    /// The inbound service request (interface ID, operation, payload).
    pub request: ServiceRequest,
    /// Capabilities this plugin declared as required in its manifest.
    #[serde(default)]
    pub required_capabilities: Vec<String>,
    /// Capabilities this plugin provides to other plugins.
    #[serde(default)]
    pub provided_capabilities: Vec<String>,
    /// Registered services visible to this plugin for cross-plugin calls.
    #[serde(default)]
    pub services: Vec<RegisteredService>,
    /// All capabilities available in the current host environment.
    #[serde(default)]
    pub available_capabilities: Vec<String>,
    /// IDs of all currently enabled plugins.
    #[serde(default)]
    pub enabled_plugins: Vec<String>,
    /// Filesystem roots where plugin manifests are discovered.
    #[serde(default)]
    pub plugin_search_roots: Vec<String>,
    /// Host runtime metadata (product name, version, API version).
    pub host: HostMetadata,
    /// Host connection paths (config dir, runtime dir, data dir, state dir).
    pub connection: HostConnectionInfo,
    /// Plugin-specific settings from the host configuration.
    #[serde(default, with = "toml_value_option")]
    pub settings: Option<toml::Value>,
    /// Settings map for all plugins (keyed by plugin ID).
    #[serde(default, with = "toml_value_map")]
    pub plugin_settings_map: BTreeMap<String, toml::Value>,
    /// Identifier of the client that issued this service request (the
    /// connected-client id, not a plugin id). `None` for
    /// server-internal invocations where no specific client is
    /// associated (e.g. CLI subcommands without an attached session).
    #[serde(default)]
    pub caller_client_id: Option<uuid::Uuid>,
    /// Opaque handle for dispatching calls to the host kernel (internal use).
    #[serde(default)]
    pub host_kernel_bridge: Option<HostKernelBridge>,
}

// ── Host kernel bridge (opaque FFI handle) ───────────────────────────────────

type HostKernelBridgeFn = unsafe extern "C" fn(
    input_ptr: *const u8,
    input_len: usize,
    output_ptr: *mut u8,
    output_capacity: usize,
    output_len: *mut usize,
) -> i32;

/// Opaque handle to a host kernel bridge function pointer.
///
/// Used internally by the service dispatch machinery. Plugin authors
/// do not interact with this type directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct HostKernelBridge(u64);

impl HostKernelBridge {
    #[must_use]
    pub fn from_fn(pointer: HostKernelBridgeFn) -> Self {
        Self(pointer as usize as u64)
    }

    /// Invoke the kernel bridge function pointer.
    ///
    /// # Safety
    ///
    /// The caller must ensure the bridge pointer is still valid (i.e. the host
    /// process has not been terminated or the function unmapped).
    pub fn invoke(
        self,
        input_ptr: *const u8,
        input_len: usize,
        output_ptr: *mut u8,
        output_capacity: usize,
        output_len: *mut usize,
    ) -> i32 {
        #[allow(clippy::cast_possible_truncation)]
        // pointer was stored as u64 for serialization; fits in usize on supported 64-bit targets
        let bridge: HostKernelBridgeFn = unsafe { std::mem::transmute(self.0 as usize) };
        unsafe {
            bridge(
                input_ptr,
                input_len,
                output_ptr,
                output_capacity,
                output_len,
            )
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HostKernelBridgeRequest {
    pub payload: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HostKernelBridgeResponse {
    pub payload: Vec<u8>,
}

/// Capability required for host-dispatched core CLI command execution.
pub const CORE_CLI_COMMAND_CAPABILITY: &str = "bmux.commands";
/// Service interface for host-dispatched core CLI command execution.
pub const CORE_CLI_COMMAND_INTERFACE_V1: &str = "cli-command/v1";
/// Service operation for executing a core CLI command path.
pub const CORE_CLI_COMMAND_RUN_PATH_OPERATION_V1: &str = "run_path";
/// Service operation for executing a plugin command.
pub const CORE_CLI_COMMAND_RUN_PLUGIN_OPERATION_V1: &str = "run_plugin";
/// Marker prefix for host-kernel bridge CLI command payloads.
pub const CORE_CLI_BRIDGE_MAGIC_V1: &[u8] = b"BMUXCMD1";
/// Marker prefix for host-kernel bridge plugin command payloads.
pub const PLUGIN_CLI_BRIDGE_MAGIC_V1: &[u8] = b"BMUXPLG1";
/// Protocol version for `CoreCliCommandRequest`/`CoreCliCommandResponse`.
pub const CORE_CLI_BRIDGE_PROTOCOL_V1: u16 = 1;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CoreCliCommandRequest {
    pub protocol_version: u16,
    pub command_path: Vec<String>,
    pub arguments: Vec<String>,
}

impl CoreCliCommandRequest {
    #[must_use]
    pub const fn new(command_path: Vec<String>, arguments: Vec<String>) -> Self {
        Self {
            protocol_version: CORE_CLI_BRIDGE_PROTOCOL_V1,
            command_path,
            arguments,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CoreCliCommandResponse {
    pub protocol_version: u16,
    pub exit_code: i32,
    #[serde(default)]
    pub error: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PluginCliCommandRequest {
    pub protocol_version: u16,
    pub plugin_id: String,
    pub command_name: String,
    pub arguments: Vec<String>,
}

impl PluginCliCommandRequest {
    #[must_use]
    pub const fn new(plugin_id: String, command_name: String, arguments: Vec<String>) -> Self {
        Self {
            protocol_version: CORE_CLI_BRIDGE_PROTOCOL_V1,
            plugin_id,
            command_name,
            arguments,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PluginCliCommandResponse {
    pub protocol_version: u16,
    pub exit_code: i32,
    pub error: Option<String>,
}

impl PluginCliCommandResponse {
    #[must_use]
    pub const fn new(exit_code: i32) -> Self {
        Self {
            protocol_version: CORE_CLI_BRIDGE_PROTOCOL_V1,
            exit_code,
            error: None,
        }
    }

    #[must_use]
    pub const fn failed(exit_code: i32, error: String) -> Self {
        Self {
            protocol_version: CORE_CLI_BRIDGE_PROTOCOL_V1,
            exit_code,
            error: Some(error),
        }
    }
}

impl CoreCliCommandResponse {
    #[must_use]
    pub const fn new(exit_code: i32) -> Self {
        Self {
            protocol_version: CORE_CLI_BRIDGE_PROTOCOL_V1,
            exit_code,
            error: None,
        }
    }

    #[must_use]
    pub const fn failed(exit_code: i32, error: String) -> Self {
        Self {
            protocol_version: CORE_CLI_BRIDGE_PROTOCOL_V1,
            exit_code,
            error: Some(error),
        }
    }
}

/// Encode a host-kernel bridge payload representing an in-process core CLI
/// command invocation request.
///
/// # Errors
///
/// Returns an error when serialization fails.
pub fn encode_host_kernel_bridge_cli_command_payload(
    request: &CoreCliCommandRequest,
) -> Result<Vec<u8>> {
    let mut payload = CORE_CLI_BRIDGE_MAGIC_V1.to_vec();
    payload.extend(encode_service_message(request)?);
    Ok(payload)
}

/// Decode a host-kernel bridge payload for in-process core CLI command
/// invocation.
///
/// Returns `Ok(None)` when the payload is not a CLI-command bridge payload.
///
/// # Errors
///
/// Returns an error when the payload has the CLI prefix but cannot be decoded.
pub fn decode_host_kernel_bridge_cli_command_payload(
    payload: &[u8],
) -> Result<Option<CoreCliCommandRequest>> {
    if !payload.starts_with(CORE_CLI_BRIDGE_MAGIC_V1) {
        return Ok(None);
    }
    let encoded = &payload[CORE_CLI_BRIDGE_MAGIC_V1.len()..];
    let request: CoreCliCommandRequest = decode_service_message(encoded)?;
    if request.protocol_version != CORE_CLI_BRIDGE_PROTOCOL_V1 {
        return Err(PluginError::ServiceProtocol {
            details: format!(
                "unsupported core CLI bridge request protocol version: {}",
                request.protocol_version
            ),
        });
    }
    Ok(Some(request))
}

/// Encode a host-kernel bridge payload representing an in-process plugin
/// command invocation request.
///
/// # Errors
///
/// Returns an error when serialization fails.
pub fn encode_host_kernel_bridge_plugin_command_payload(
    request: &PluginCliCommandRequest,
) -> Result<Vec<u8>> {
    let mut payload = PLUGIN_CLI_BRIDGE_MAGIC_V1.to_vec();
    payload.extend(encode_service_message(request)?);
    Ok(payload)
}

/// Decode a host-kernel bridge payload for in-process plugin command
/// invocation.
///
/// Returns `Ok(None)` when the payload is not a plugin-command bridge payload.
///
/// # Errors
///
/// Returns an error when the payload has the plugin prefix but cannot be decoded.
pub fn decode_host_kernel_bridge_plugin_command_payload(
    payload: &[u8],
) -> Result<Option<PluginCliCommandRequest>> {
    if !payload.starts_with(PLUGIN_CLI_BRIDGE_MAGIC_V1) {
        return Ok(None);
    }
    let encoded = &payload[PLUGIN_CLI_BRIDGE_MAGIC_V1.len()..];
    let request: PluginCliCommandRequest = decode_service_message(encoded)?;
    if request.protocol_version != CORE_CLI_BRIDGE_PROTOCOL_V1 {
        return Err(PluginError::ServiceProtocol {
            details: format!(
                "unsupported plugin CLI bridge request protocol version: {}",
                request.protocol_version
            ),
        });
    }
    Ok(Some(request))
}

#[cfg(test)]
mod tests {
    use super::{
        CORE_CLI_BRIDGE_PROTOCOL_V1, CoreCliCommandRequest, PluginCliCommandRequest,
        decode_host_kernel_bridge_cli_command_payload,
        decode_host_kernel_bridge_plugin_command_payload,
        encode_host_kernel_bridge_cli_command_payload,
        encode_host_kernel_bridge_plugin_command_payload,
    };

    #[test]
    fn cli_bridge_payload_round_trip_preserves_request() {
        let request = CoreCliCommandRequest::new(
            vec!["logs".to_string(), "path".to_string()],
            vec!["--json".to_string()],
        );
        let encoded =
            encode_host_kernel_bridge_cli_command_payload(&request).expect("request should encode");
        let decoded = decode_host_kernel_bridge_cli_command_payload(&encoded)
            .expect("payload should decode")
            .expect("payload should be recognized");
        assert_eq!(decoded, request);
    }

    #[test]
    fn cli_bridge_payload_ignores_unknown_prefix() {
        let decoded = decode_host_kernel_bridge_cli_command_payload(b"not-a-cli-bridge-payload")
            .expect("decode should succeed");
        assert!(decoded.is_none());
    }

    #[test]
    fn cli_bridge_payload_rejects_unsupported_protocol_version() {
        let mut request = CoreCliCommandRequest::new(Vec::new(), Vec::new());
        request.protocol_version = CORE_CLI_BRIDGE_PROTOCOL_V1 + 1;
        let encoded =
            encode_host_kernel_bridge_cli_command_payload(&request).expect("request should encode");
        let error = decode_host_kernel_bridge_cli_command_payload(&encoded)
            .expect_err("decode should fail for unsupported protocol version");
        assert!(
            error
                .to_string()
                .contains("unsupported core CLI bridge request protocol version")
        );
    }

    #[test]
    fn core_cli_response_failed_carries_error() {
        let response = super::CoreCliCommandResponse::failed(7, "boom".to_string());
        let encoded = super::encode_service_message(&response).expect("response should encode");
        let decoded: super::CoreCliCommandResponse =
            super::decode_service_message(&encoded).expect("response should decode");

        assert_eq!(decoded.exit_code, 7);
        assert_eq!(decoded.error.as_deref(), Some("boom"));
    }

    #[test]
    fn plugin_cli_bridge_payload_round_trip_preserves_request() {
        let request = PluginCliCommandRequest::new(
            "bmux.windows".to_string(),
            "new-window".to_string(),
            vec!["--name".to_string(), "work".to_string()],
        );
        let encoded = encode_host_kernel_bridge_plugin_command_payload(&request)
            .expect("request should encode");
        let decoded = decode_host_kernel_bridge_plugin_command_payload(&encoded)
            .expect("payload should decode")
            .expect("payload should be recognized");
        assert_eq!(decoded, request);
    }

    #[test]
    fn plugin_cli_bridge_payload_ignores_unknown_prefix() {
        let decoded =
            decode_host_kernel_bridge_plugin_command_payload(b"not-a-plugin-bridge-payload")
                .expect("decode should succeed");
        assert!(decoded.is_none());
    }

    #[test]
    fn plugin_cli_bridge_payload_rejects_unsupported_protocol_version() {
        let mut request = PluginCliCommandRequest::new(
            "bmux.windows".to_string(),
            "new-window".to_string(),
            Vec::new(),
        );
        request.protocol_version = CORE_CLI_BRIDGE_PROTOCOL_V1 + 1;
        let encoded = encode_host_kernel_bridge_plugin_command_payload(&request)
            .expect("request should encode");
        let error = decode_host_kernel_bridge_plugin_command_payload(&encoded)
            .expect_err("decode should fail for unsupported protocol version");
        assert!(
            error
                .to_string()
                .contains("unsupported plugin CLI bridge request protocol version")
        );
    }
}