rmux-proto 0.10.0

RMUX detached IPC protocol DTOs, framing, and wire-safe error types.
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
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
use serde::{Deserialize, Serialize};

use super::CommandOutput;
use crate::{
    PaneId, PaneOutputSubscriptionId, PaneStateSubscriptionId, PaneTarget, PaneTargetRef,
    ResizePaneAdjustment, RmuxError, WindowTarget,
};

/// Response payload for `split-window`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SplitWindowResponse {
    /// The newly created pane target.
    pub pane: PaneTarget,
}

/// Atomic identity returned by the capability-gated SDK split endpoint.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SplitWindowIdentityResponse {
    /// The newly created pane target using its visible `pane-base-index`.
    pub pane: PaneTarget,
    /// The newly created pane's stable daemon-lifetime identity.
    pub pane_id: PaneId,
}

/// Response payload for `swap-pane`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SwapPaneResponse {
    /// The source slot involved in the swap.
    pub source: PaneTarget,
    /// The destination slot involved in the swap.
    pub target: PaneTarget,
}

/// Response payload for `move-pane`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MovePaneResponse {
    /// The pane after it joined the destination window.
    pub target: PaneTarget,
}

/// Response payload for `last-pane`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LastPaneResponse {
    /// The pane that became active.
    pub target: PaneTarget,
}

/// Response payload for `join-pane`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JoinPaneResponse {
    /// The pane after it joined the destination window.
    pub target: PaneTarget,
}

/// Response payload for `break-pane`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BreakPaneResponse {
    /// The pane after it moved into its own window.
    pub target: PaneTarget,
    /// Optional printable output for `break-pane -P`.
    #[serde(default)]
    pub output: Option<CommandOutput>,
}

impl BreakPaneResponse {
    /// Returns the optional printable pane target output.
    #[must_use]
    pub const fn command_output(&self) -> Option<&CommandOutput> {
        self.output.as_ref()
    }
}

/// Response payload for `kill-pane`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KillPaneResponse {
    /// The pane that was removed.
    pub target: PaneTarget,
    /// Whether killing the pane also destroyed its window.
    pub window_destroyed: bool,
}

/// Response payload for `resize-pane`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResizePaneResponse {
    /// The pane that was resized.
    pub target: PaneTarget,
    /// The applied resize semantics.
    pub adjustment: ResizePaneAdjustment,
}

/// Response payload for `display-panes`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DisplayPanesResponse {
    /// The active window that received the overlay.
    pub target: WindowTarget,
    /// The number of pane labels included in the overlay.
    pub pane_count: u32,
}

/// Response payload for `pipe-pane`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PipePaneResponse {
    /// The addressed pane.
    pub target: PaneTarget,
}

/// Response payload for `respawn-pane`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RespawnPaneResponse {
    /// The respawned pane target.
    pub target: PaneTarget,
}

/// Response payload for `select-pane`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SelectPaneResponse {
    /// The pane that became active.
    pub target: PaneTarget,
}

/// Response payload for `send-keys`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SendKeysResponse {
    /// The number of key tokens accepted by the server.
    pub key_count: usize,
}

/// Successful delivery for one target in a pane-input broadcast.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneBroadcastInputSuccess {
    /// Zero-based target index from the request.
    pub target_index: u32,
    /// Resolved pane target that accepted the input.
    pub target: PaneTarget,
    /// Stable pane identity observed while resolving the target.
    pub pane_id: Option<PaneId>,
}

/// Failed delivery for one target in a pane-input broadcast.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneBroadcastInputFailure {
    /// Zero-based target index from the request.
    pub target_index: u32,
    /// Original target that failed to receive the input.
    pub target: PaneTargetRef,
    /// Per-pane protocol error.
    pub error: RmuxError,
}

/// Response payload for a daemon-side pane-input broadcast.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneBroadcastInputResponse {
    /// Number of key/text tokens accepted per successful target.
    pub key_count: usize,
    /// Targets that accepted the input, in request order.
    pub successes: Vec<PaneBroadcastInputSuccess>,
    /// Targets that rejected the input, in request order.
    pub failures: Vec<PaneBroadcastInputFailure>,
}

/// Response payload for SDK pane option mutations.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneOptionSetResponse {
    /// Stable pane id resolved by the daemon.
    pub pane_id: PaneId,
    /// Canonical option name.
    pub name: String,
    /// Exact explicit value before the mutation.
    pub old_value: Option<String>,
    /// Exact explicit value after the mutation.
    pub new_value: Option<String>,
    /// Whether the explicit value changed.
    pub changed: bool,
}

/// Response payload for SDK pane option lookups.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneOptionGetResponse {
    /// Stable pane id resolved by the daemon.
    pub pane_id: PaneId,
    /// Canonical option name.
    pub name: String,
    /// Exact pane-local explicit value.
    pub value: Option<String>,
}

/// Explicit pane option entry included in pane-state snapshots.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneOptionEntry {
    /// Canonical option name.
    pub name: String,
    /// Exact explicit option value rendered by the daemon.
    pub value: String,
}

/// Source labels for best-effort foreground fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ForegroundFieldSource {
    /// Read from the foreground process or foreground process group.
    Process,
    /// Read from the root pane process.
    RootProcess,
    /// Read from the terminal OSC 7 path.
    Osc7,
    /// Read from the pane launch profile.
    Profile,
    /// Read from the session environment.
    Environment,
    /// Read from RMUX's runtime window-name cache.
    RuntimeName,
}

/// Per-field source report for best-effort foreground state.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ForegroundSourcesDto {
    /// Source for `pid`.
    #[serde(default)]
    pub pid: Option<ForegroundFieldSource>,
    /// Source for `command`.
    #[serde(default)]
    pub command: Option<ForegroundFieldSource>,
    /// Source for `cwd`.
    #[serde(default)]
    pub cwd: Option<ForegroundFieldSource>,
    /// Source for `exe`.
    #[serde(default)]
    pub exe: Option<ForegroundFieldSource>,
}

/// Best-effort foreground process state for a pane.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ForegroundStateDto {
    /// Foreground or root process id, when knowable.
    #[serde(default)]
    pub pid: Option<u32>,
    /// Executable command name, when knowable.
    #[serde(default)]
    pub command: Option<String>,
    /// Current working directory, when knowable.
    #[serde(default)]
    pub cwd: Option<String>,
    /// Executable path, when knowable.
    #[serde(default)]
    pub exe: Option<String>,
    /// Per-field source labels.
    #[serde(default)]
    pub sources: ForegroundSourcesDto,
}

/// Initial or rebased pane-state snapshot.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneStateSnapshot {
    /// Global pane-state journal revision at snapshot time.
    pub revision: u64,
    /// Current pane title when requested.
    #[serde(default)]
    pub title: Option<String>,
    /// Current explicit pane-local options when requested.
    #[serde(default)]
    pub options: Vec<PaneOptionEntry>,
    /// Best-effort foreground state when requested.
    #[serde(default)]
    pub foreground: Option<ForegroundStateDto>,
}

/// Terminal reason for a pane-state stream close event.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum PaneStateClosedReason {
    /// The pane process exited and the pane was removed.
    Exited,
    /// The pane process died but remain-on-exit kept the pane around.
    DiedKept,
    /// The pane was killed by an explicit RMUX operation.
    Killed,
}

/// One revisioned pane-state event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum PaneStateEventDto {
    /// The pane title changed.
    TitleChanged {
        /// Global pane-state revision.
        revision: u64,
        /// Stable pane id.
        pane_id: PaneId,
        /// Previous title.
        old_title: String,
        /// New title.
        new_title: String,
    },
    /// A pane-local option was set or replaced.
    OptionSet {
        /// Global pane-state revision.
        revision: u64,
        /// Stable pane id.
        pane_id: PaneId,
        /// Canonical option name.
        name: String,
        /// Previous explicit value.
        old_value: Option<String>,
        /// New explicit value.
        new_value: String,
    },
    /// A pane-local option was unset.
    OptionUnset {
        /// Global pane-state revision.
        revision: u64,
        /// Stable pane id.
        pane_id: PaneId,
        /// Canonical option name.
        name: String,
        /// Previous explicit value.
        old_value: Option<String>,
    },
    /// Best-effort foreground state changed.
    ForegroundChanged {
        /// Global pane-state revision.
        revision: u64,
        /// Stable pane id.
        pane_id: PaneId,
        /// Previous foreground state.
        old_state: ForegroundStateDto,
        /// New foreground state.
        new_state: ForegroundStateDto,
    },
    /// The pane reached a terminal state for this subscription.
    Closed {
        /// Global pane-state revision.
        revision: u64,
        /// Stable pane id.
        pane_id: PaneId,
        /// Terminal close reason.
        reason: PaneStateClosedReason,
    },
}

/// Response payload for subscribing to revisioned pane-state events.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SubscribePaneStateResponse {
    /// The newly allocated subscription identifier.
    pub subscription_id: PaneStateSubscriptionId,
    /// Stable pane identity for the subscribed pane.
    pub pane_id: PaneId,
    /// Atomic initial snapshot.
    pub snapshot: PaneStateSnapshot,
}

/// Response payload for unsubscribing from pane-state events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnsubscribePaneStateResponse {
    /// The requested subscription identifier.
    pub subscription_id: PaneStateSubscriptionId,
    /// Whether a live subscription was removed.
    pub removed: bool,
}

/// Response payload for a pane-state cursor request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneStateCursorResponse {
    /// The polled subscription identifier.
    pub subscription_id: PaneStateSubscriptionId,
    /// Events delivered in strictly increasing revision order.
    pub events: Vec<PaneStateEventDto>,
    /// Revision callers should use as the next `after_revision` cursor.
    pub next_revision: u64,
}

/// Response payload for a pane-state subscription lag.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneStateLagResponse {
    /// The polled subscription identifier.
    pub subscription_id: PaneStateSubscriptionId,
    /// The stale cursor revision that fell behind retention.
    pub missed_from_revision: u64,
    /// Oldest retained revision after the gap.
    pub resume_revision: u64,
    /// Atomic rebased snapshot.
    pub snapshot: PaneStateSnapshot,
}

/// Response payload for a one-shot foreground state request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneForegroundStateResponse {
    /// Stable pane id resolved by the daemon.
    pub pane_id: PaneId,
    /// Journal revision observed when sampling.
    pub revision: u64,
    /// Best-effort foreground state. `None` means the pane disappeared.
    pub state: Option<ForegroundStateDto>,
}

/// Serializable pane-output cursor state returned by subscription endpoints.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneOutputCursor {
    /// The next output sequence the cursor expects.
    pub next_sequence: u64,
    /// Total output events this cursor has skipped after explicit gaps.
    pub missed_events: u64,
}

/// One pane-output event delivered through a subscription cursor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneOutputEvent {
    /// Monotonic per-pane output sequence.
    pub sequence: u64,
    /// Raw pane output bytes.
    pub bytes: Vec<u8>,
}

/// Recent live bytes included with a lag notice.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneRecentOutput {
    /// Retained recent raw pane output bytes.
    pub bytes: Vec<u8>,
    /// Oldest output sequence contributing retained bytes.
    pub oldest_sequence: Option<u64>,
    /// Newest output sequence contributing retained bytes.
    pub newest_sequence: Option<u64>,
}

/// Explicit report for a subscription cursor that fell behind retention.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneOutputLagNotice {
    /// Sequence the subscriber expected before lag was detected.
    pub expected_sequence: u64,
    /// Oldest retained sequence where the subscriber can resume.
    pub resume_sequence: u64,
    /// Number of output events skipped by this lag notice.
    pub missed_events: u64,
    /// Newest output sequence appended when lag was detected.
    pub newest_sequence: u64,
    /// Bounded recent live output available at lag detection time.
    pub recent: PaneRecentOutput,
}

/// Response payload for subscribing to live pane-output events.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SubscribePaneOutputResponse {
    /// The newly allocated subscription identifier.
    pub subscription_id: PaneOutputSubscriptionId,
    /// The resolved target at subscription time.
    pub target: PaneTarget,
    /// Stable pane identity for the subscribed pane.
    pub pane_id: PaneId,
    /// Initial cursor state.
    pub cursor: PaneOutputCursor,
}

/// Response payload for unsubscribing from live pane-output events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnsubscribePaneOutputResponse {
    /// The requested subscription identifier.
    pub subscription_id: PaneOutputSubscriptionId,
    /// Whether a live subscription was removed by this request.
    pub removed: bool,
}

/// Response payload for polling a live pane-output subscription cursor.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneOutputCursorResponse {
    /// The polled subscription identifier.
    pub subscription_id: PaneOutputSubscriptionId,
    /// Cursor state after this poll.
    pub cursor: PaneOutputCursor,
    /// Output events delivered in ascending sequence order.
    pub events: Vec<PaneOutputEvent>,
    /// Whether this response stopped at the server-side batch cap.
    pub limited: bool,
}

/// Response payload for a pane-output subscription lag notice.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneOutputLagResponse {
    /// The polled subscription identifier.
    pub subscription_id: PaneOutputSubscriptionId,
    /// Cursor state after applying the lag notice.
    pub cursor: PaneOutputCursor,
    /// Detailed gap report.
    pub lag: PaneOutputLagNotice,
}

/// Why a raw pane stream emitted a new authoritative keyframe.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum PaneRawRebaseReason {
    /// Initial authoritative boundary created when the stream opens.
    Initial,
    /// The consumer fell behind the bounded output ring.
    Lag,
    /// Pane geometry changed without a corresponding output byte.
    Resize,
    /// Retained terminal history was explicitly cleared.
    ClearHistory,
    /// An incomplete parser sequence expired.
    ParserStateExpired,
    /// The terminal state was reset.
    TerminalReset,
    /// Another cold-path transcript mutation invalidated continuation.
    TranscriptMutation,
    /// The pane process generation changed.
    GenerationChanged,
}

/// Completeness report for a bounded raw recovery keyframe.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneRecoveryCoverage {
    /// Total scrollback rows retained by the daemon at the capture boundary.
    pub history_rows_total: u64,
    /// Newest whole scrollback rows represented by the keyframe.
    pub history_rows_included: u64,
    /// Whether terminal metadata carried by the keyframe is lossless.
    ///
    /// `true` guarantees exact reconstruction of stored title, OSC 7 path,
    /// title-stack, and hyperlink values. `false` means at least one recovery
    /// metadata value was omitted, shortened to fit a byte budget, or stripped
    /// of control characters for safe OSC replay. This is independent of the
    /// history-row coverage above; the visible cell grid remains authoritative.
    pub metadata_complete: bool,
}

impl PaneRecoveryCoverage {
    /// Returns whether every retained scrollback row is represented.
    #[must_use]
    pub const fn history_complete(self) -> bool {
        self.history_rows_included >= self.history_rows_total
    }
}

/// Complete raw-emulator recovery state delivered in-band.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneRawRebase {
    /// Stream-local epoch stamped onto subsequent raw byte events.
    pub epoch: u64,
    /// Pane process generation observed by the atomic boundary.
    pub generation: u64,
    /// Cold-path invalidation revision observed by the atomic boundary.
    pub invalidation_revision: u64,
    /// First pane-output sequence not represented by this keyframe.
    pub next_sequence: u64,
    /// Terminal width represented by the keyframe.
    pub cols: u16,
    /// Terminal height represented by the keyframe.
    pub rows: u16,
    /// ANSI bytes that reset and reconstruct a compatible terminal emulator.
    pub keyframe: Vec<u8>,
    /// Whether the captured pane is currently using its alternate screen.
    pub alternate: bool,
    /// Explicit report for bounded scrollback and terminal metadata.
    pub coverage: PaneRecoveryCoverage,
    /// Optional typed snapshot requested by an inspection-oriented consumer.
    pub snapshot: Option<PaneSnapshotResponse>,
    /// Cause of this rebase.
    pub reason: PaneRawRebaseReason,
}

/// One raw byte event tied to a preceding rebase epoch.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneRawBytes {
    /// Stream-local epoch established by the latest raw rebase.
    pub epoch: u64,
    /// Monotonic pane-output sequence.
    pub sequence: u64,
    /// Exact output bytes published for this sequence.
    pub bytes: Vec<u8>,
}

/// One OSC 8 hyperlink referenced by a structured pane surface.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneSurfaceHyperlink {
    /// Non-zero hyperlink inner ID stored by visible cells.
    pub id: u32,
    /// OSC 8 target URI associated with `id`.
    pub uri: String,
}

/// Application-defined OSC 10/11/12 colours.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneSurfaceDynamicColors {
    /// OSC 10 default foreground colour, when defined by the application.
    pub foreground: Option<String>,
    /// OSC 11 default background colour, when defined by the application.
    pub background: Option<String>,
    /// OSC 12 cursor colour, when defined by the application.
    pub cursor: Option<String>,
}

/// Authoritative structured pane state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneSurfaceSnapshot {
    /// Visible pane width in terminal columns.
    pub cols: u16,
    /// Visible pane height in terminal rows.
    pub rows: u16,
    /// Row-major visible cells, exactly `cols * rows` long.
    pub cells: Vec<PaneSnapshotCell>,
    /// URI metadata keyed by the non-zero hyperlink IDs stored in `cells`.
    pub hyperlinks: Vec<PaneSurfaceHyperlink>,
    /// Current cursor state.
    pub cursor: PaneSnapshotCursor,
    /// Terminal title observed at this boundary.
    pub title: String,
    /// Terminal-reported working-directory path.
    pub path: String,
    /// Application-defined OSC 10/11/12 colours.
    pub dynamic_colors: PaneSurfaceDynamicColors,
    /// Whether title, path, and visible-cell hyperlink metadata was copied
    /// completely into this transport-bounded snapshot.
    pub metadata_complete: bool,
    /// Raw terminal mode bitset.
    pub mode_bits: u32,
    /// Whether the alternate screen is active.
    pub alternate: bool,
    /// Inclusive top row of the scrolling region.
    pub scroll_top: u32,
    /// Inclusive bottom row of the scrolling region.
    pub scroll_bottom: u32,
    /// Number of retained scrollback rows.
    pub history_size: u64,
    /// Bytes retained by the terminal history representation.
    pub history_bytes: u64,
    /// Monotonic pane-grid revision shared with `PaneSnapshotResponse`.
    pub revision: u64,
}

/// A self-contained surface frame; no earlier patch is required to apply it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneSurfaceFrame {
    /// Stream-local epoch established by the latest surface reset.
    pub epoch: u64,
    /// Monotonic revision of the complete surface projection.
    pub revision: u64,
    /// First pane-output sequence not represented by this atomic surface.
    pub next_output_sequence: u64,
    /// Complete authoritative surface represented by this frame.
    pub snapshot: PaneSurfaceSnapshot,
}

/// Pane lifecycle observations that do not terminate the logical stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum PaneStreamLifecycleEvent {
    /// The current child process exited after its output reached EOF.
    ///
    /// A kept pane may later be respawned on the same subscription.
    ProcessExited {
        /// Exact output-ring sequence occupied by the EOF marker when it was
        /// still retained. `None` means lifecycle was recovered across an
        /// invalidation or retention gap; the adjacent rebase is authoritative
        /// for raw sequence continuation.
        output_sequence: Option<u64>,
    },
}

/// Distinguishes logical pane removal from subscription termination.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum PaneStreamEndReason {
    /// The logical pane resource was removed.
    PaneRemoved,
    /// The caller no longer has permission to observe the pane.
    AccessRevoked,
    /// The bounded subscription could not keep up.
    SlowConsumer,
    /// The idle subscription lease expired.
    SubscriptionExpired,
    /// The underlying detached transport was lost.
    TransportLost,
    /// The daemon could not materialize the requested projection.
    ProjectionFailed,
}

/// One item in either recoverable pane projection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum PaneStreamEvent {
    /// Authoritative raw-emulator reset and reconstruction payload.
    RawRebase(Box<PaneRawRebase>),
    /// Exact raw output following the latest rebase.
    RawBytes(PaneRawBytes),
    /// Complete authoritative surface establishing a new epoch.
    SurfaceReset(Box<PaneSurfaceFrame>),
    /// Self-contained authoritative surface update.
    SurfacePatch(Box<PaneSurfaceFrame>),
    /// Non-terminal process lifecycle observation.
    Lifecycle(PaneStreamLifecycleEvent),
    /// Typed terminal or subscription termination.
    End(PaneStreamEndReason),
}

/// Atomic initial event and already-reserved pane stream subscription.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SubscribePaneStreamResponse {
    /// Opaque stream subscription allocated by the daemon.
    pub subscription_id: PaneOutputSubscriptionId,
    /// Resolved pane slot at subscription time.
    pub target: PaneTarget,
    /// Stable pane identity at subscription time.
    pub pane_id: PaneId,
    /// Initial authoritative event.
    pub event: PaneStreamEvent,
}

/// Batched recoverable pane stream events.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneStreamCursorResponse {
    /// Polled stream subscription.
    pub subscription_id: PaneOutputSubscriptionId,
    /// Events delivered in stream order.
    pub events: Vec<PaneStreamEvent>,
    /// Whether this response stopped at the server-side batch cap.
    pub limited: bool,
}

/// Result of explicitly closing a recoverable pane stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct UnsubscribePaneStreamResponse {
    /// Requested stream subscription.
    pub subscription_id: PaneOutputSubscriptionId,
    /// Whether a live stream was removed.
    pub removed: bool,
}

/// One captured pane cell on the daemon snapshot wire.
///
/// Cells are produced from rmux-core's structured `ScreenCellView`, so the
/// glyph text, recorded display width, and padding flag travel verbatim
/// across the wire. Padding cells (the trailing column of a wide glyph)
/// carry `width = 0` and `padding = true`; their `text` field carries the
/// space sentinel rmux-core uses to represent owned padding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneSnapshotCell {
    /// Recorded glyph text payload.
    pub text: String,
    /// Recorded display width of the leading glyph; `0` for padding cells.
    pub width: u8,
    /// Whether this cell is wide-glyph padding for the preceding column.
    pub padding: bool,
    /// Raw cell attribute bitset.
    pub attributes: u16,
    /// Raw foreground colour encoding.
    pub fg: i32,
    /// Raw background colour encoding.
    pub bg: i32,
    /// Raw underline colour encoding.
    pub us: i32,
    /// Hyperlink inner ID.
    pub link: u32,
}

/// Captured cursor position on the daemon snapshot wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneSnapshotCursor {
    /// Zero-based cursor row within the visible viewport.
    pub row: u16,
    /// Zero-based cursor column within the visible viewport.
    pub col: u16,
    /// Whether the cursor is visible according to the live mode bits.
    pub visible: bool,
    /// Raw cursor style value.
    pub style: u32,
}

/// Response payload for the daemon-backed pane snapshot endpoint.
///
/// `cells` is row-major with `row * cols + col` indexing and exactly
/// `cols * rows` entries. The daemon-derived `revision` is non-zero for
/// every captured live pane and changes whenever any observable field
/// (cells, cursor, output_sequence, history bytes/lines, pane id) changes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaneSnapshotResponse {
    /// Visible pane width in terminal columns.
    pub cols: u16,
    /// Visible pane height in terminal rows.
    pub rows: u16,
    /// Row-major cells, `cols * rows` long.
    pub cells: Vec<PaneSnapshotCell>,
    /// Captured cursor coordinates and state.
    pub cursor: PaneSnapshotCursor,
    /// Daemon-derived revision counter for this captured state.
    pub revision: u64,
}

/// Response payload for `list-panes`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListPanesResponse {
    /// The pre-rendered stdout bytes for the CLI.
    pub output: CommandOutput,
}

impl ListPanesResponse {
    /// Returns the reusable stdout payload for the list command.
    #[must_use]
    pub fn command_output(&self) -> &CommandOutput {
        &self.output
    }
}