micromux-control 0.4.2

Micromux is a local process supervisor with a terminal UI
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
//! The control wire protocol: newline-delimited JSON request/response envelopes.
//!
//! Domain payloads (`ServiceSnapshot`, `HealthAttempt`, `LogLine`, `SessionChange`,
//! `ServiceCommandAck`, `DynamicServiceAck`, `ReconcileReceipt`, `ResolvedEnvironment`,
//! `ServiceEvent`, and `DynamicServiceParams`) are the stable core types reused directly — no DTO
//! mirror.
//! The session and the proxy accept peers that speak the same major protocol version, so
//! additive payload changes do not orphan already-running sessions.

use base64::Engine as _;
use micromux::{
    DynamicServiceAck, DynamicServiceParams, HealthAttempt, Lease, LogLine, LogRunSummary,
    ReconcileReceipt, ResolvedEnvironment, ServiceCommandAck, ServiceEvent, ServiceID,
    ServiceSnapshot, SessionChange,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// The current control protocol version.
///
/// Bump the minor for additive changes (new optional/defaulted fields, new tools that reuse
/// existing requests), and bump the major for incompatible request/response semantics.
pub const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 18);

/// The first protocol revision whose sessions answer [`Request::GetEvents`].
pub const EVENTS_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 3);

/// The first protocol revision whose sessions answer [`Request::GetEnvironment`].
pub const ENVIRONMENT_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 15);

/// The first protocol revision whose sessions answer [`Request::SendInput`] and
/// [`Request::ResizeTerminal`].
pub const TERMINAL_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::new(3, 18);

/// The largest paste one [`Request::SendInput`] carries.
///
/// Its base64 encoding, about a third larger, must fit one [`crate::MAX_FRAME_BYTES`] frame with
/// room for the envelope, so it stays below the in-process TUI's [`micromux::MAX_PTY_PASTE_BYTES`].
pub const MAX_REMOTE_PASTE_BYTES: usize = 512 * 1024;

const _: () = assert!(
    MAX_REMOTE_PASTE_BYTES.div_ceil(3) * 4 + 64 * 1024 <= crate::MAX_FRAME_BYTES,
    "a maximal remote paste must fit one control frame"
);

pub(crate) const fn supports_versioned_subscriptions(version: ProtocolVersion) -> bool {
    version.major() == PROTOCOL_VERSION.major() && version.minor() >= 7
}

/// A typed control protocol version.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ProtocolVersion {
    major: u16,
    minor: u16,
}

impl ProtocolVersion {
    /// Build a protocol version from major/minor components.
    #[must_use]
    pub const fn new(major: u16, minor: u16) -> Self {
        Self { major, minor }
    }

    /// Major compatibility line.
    #[must_use]
    pub const fn major(self) -> u16 {
        self.major
    }

    /// Additive revision within one major line.
    #[must_use]
    pub const fn minor(self) -> u16 {
        self.minor
    }

    /// Return whether two peers can speak the same protocol.
    #[must_use]
    pub const fn is_compatible_with(self, peer: Self) -> bool {
        self.major == peer.major
    }

    /// Return whether a peer speaking this version understands everything `revision` added.
    ///
    /// That holds on the same major line at `revision`'s minor or a later one.
    #[must_use]
    pub const fn supports(self, revision: Self) -> bool {
        self.major == revision.major && self.minor >= revision.minor
    }
}

impl std::fmt::Display for ProtocolVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}", self.major(), self.minor())
    }
}

/// A request from a client (the `micromux ctl` CLI or the MCP proxy) to a session's control server.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub enum Request {
    /// Return session identity and metadata.
    Describe,
    /// List every service with its current snapshot.
    ///
    /// This response is not paged. A roster that exceeds the protocol frame budget returns
    /// [`ErrorCode::LimitExceeded`].
    ListServices,
    /// Return one service by stable id or human-readable name.
    ///
    /// Exact ids take precedence; duplicate display names resolve to the first service.
    GetService {
        /// Service id or display name.
        service: ServiceID,
    },
    /// Return recent log records for a service.
    GetLogs {
        /// Target service.
        service: ServiceID,
        /// Specific disk-retained run generation to read. Omit to read the bounded visible log
        /// stream.
        run_generation: Option<u64>,
        /// Bound the result to the most recent records.
        tail: Option<usize>,
    },
    /// Return log records strictly after a monotonic cursor, for gap-free incremental following.
    FollowLogs {
        /// Target service.
        service: ServiceID,
        /// Specific disk-retained run generation to follow. Omit to follow the bounded visible log
        /// stream.
        run_generation: Option<u64>,
        /// Return only records with `seq` greater than this cursor (all retained records if
        /// `None`).
        after: Option<u64>,
    },
    /// Return summaries of retained log runs for a service.
    ///
    /// This response is not paged. A run index that exceeds the protocol frame budget returns
    /// [`ErrorCode::LimitExceeded`].
    ListLogRuns {
        /// Target service.
        service: ServiceID,
    },
    /// Return the latest healthcheck attempt for a service's current live run.
    GetHealth {
        /// Target service.
        service: ServiceID,
    },
    /// Return retained healthcheck attempts for a service's current or latest run.
    GetHealthHistory {
        /// Target service.
        service: ServiceID,
    },
    /// Return retained scheduler lifecycle events for a service.
    ///
    /// Sessions answer it from protocol [`EVENTS_PROTOCOL_VERSION`] on.
    GetEvents {
        /// Target service.
        service: ServiceID,
        /// Return events with a sequence strictly greater than this cursor.
        after: Option<u64>,
        /// Bound the result; when `after` is absent this selects the newest events.
        tail: Option<usize>,
    },
    /// Restart a single service.
    Restart {
        /// Target service.
        service: ServiceID,
    },
    /// Restart all enabled services.
    RestartAll,
    /// Enable (and start) a single service.
    Enable {
        /// Target service.
        service: ServiceID,
    },
    /// Disable a single service.
    Disable {
        /// Target service.
        service: ServiceID,
    },
    /// Create and start a dynamic service.
    StartDynamicService {
        /// Definition, clone source, and lease request.
        params: DynamicServiceParams,
    },
    /// Replace or revive a dynamic service.
    ReplaceDynamicService {
        /// Existing dynamic service id.
        service: ServiceID,
        /// Required current revision.
        expected_revision: u64,
        /// Replacement definition, clone source, and lease request.
        params: DynamicServiceParams,
    },
    /// Renew a live dynamic service's lease without restarting it.
    RenewDynamicService {
        /// Existing dynamic service id.
        service: ServiceID,
        /// Required current revision.
        expected_revision: u64,
        /// Requested replacement lease; omission uses the session policy default.
        expires_after: Option<Lease>,
    },
    /// Retire a dynamic service.
    StopDynamicService {
        /// Dynamic service id.
        service: ServiceID,
    },
    /// Return the session's variables, or one service's resolved environment, with their values.
    ///
    /// Sessions answer it from protocol [`ENVIRONMENT_PROTOCOL_VERSION`] on; older ones reject it
    /// as a bad request.
    /// See [`micromux::ServiceControl::environment`] for what the variables are.
    GetEnvironment {
        /// Service id, matched exactly, or `None` for the session's own variables.
        service: Option<ServiceID>,
    },
    /// Reconcile configured services against the session's on-disk config.
    ///
    /// The config file is the authority, so this operation has no dynamic-service capability gate.
    ReconcileConfig {
        /// Compute the semantic diff without mutating the session. Deliberately a required
        /// field: omission must never silently mean "apply".
        dry_run: bool,
    },
    /// Write bytes to a service's PTY, as typed into an attached TUI.
    ///
    /// Sessions answer it from protocol [`TERMINAL_PROTOCOL_VERSION`] on; older ones reject it as a
    /// bad request.
    /// Input from every client, the session's own TUI included, is written in the order the
    /// session receives it, and one request's bytes are written contiguously.
    /// The MCP server never sends it: agents get no tool that types into a service.
    SendInput {
        /// Target service id, matched exactly.
        service: ServiceID,
        /// The bytes to write, at most [`micromux::MAX_PTY_INPUT_BATCH_BYTES`] unless `paste` is
        /// set.
        data: InputBytes,
        /// Whether the bytes are one paste, which may be up to [`MAX_REMOTE_PASTE_BYTES`].
        #[serde(default)]
        paste: bool,
    },
    /// Resize every service PTY in the session.
    ///
    /// Sessions answer it from protocol [`TERMINAL_PROTOCOL_VERSION`] on.
    /// The last resize the session receives wins, whichever client sent it, the session's own TUI
    /// included, and runs started later take that size too.
    ResizeTerminal {
        /// Columns, at least one.
        cols: u16,
        /// Rows, at least one.
        rows: u16,
    },
    /// Stop the whole session: stop every service and exit the session process (graceful, like the
    /// operator pressing Ctrl-C), freeing its ports. Acknowledged with [`Response::ShuttingDown`]
    /// just before the endpoint goes away.
    Shutdown,
    /// Stream [`SessionChange`] notifications until the client disconnects.
    Subscribe,
    /// Stream change notifications and negotiate additive subscription behavior.
    SubscribeWithVersion {
        /// Protocol version spoken by the subscribing client.
        protocol_version: ProtocolVersion,
    },
}

impl Request {
    /// Whether a client may repeat the request after losing the connection before its response.
    ///
    /// Mutations are deliberately excluded even when they are usually idempotent: a lost
    /// acknowledgement does not prove whether the scheduler accepted the first request.
    #[must_use]
    pub const fn is_retry_safe(&self) -> bool {
        matches!(
            self,
            Self::Describe
                | Self::ListServices
                | Self::GetService { .. }
                | Self::GetLogs { .. }
                | Self::FollowLogs { .. }
                | Self::ListLogRuns { .. }
                | Self::GetHealth { .. }
                | Self::GetHealthHistory { .. }
                | Self::GetEvents { .. }
                | Self::GetEnvironment { .. }
                | Self::ReconcileConfig { dry_run: true }
        )
    }
}

/// Raw PTY input carried by [`Request::SendInput`].
///
/// It travels as standard padded base64, so arbitrary bytes, control characters included, take a
/// predictable share of a frame.
/// Its `Debug` output names only the length, because the bytes may be a typed password.
#[derive(Clone, PartialEq, Eq)]
pub struct InputBytes(Vec<u8>);

impl InputBytes {
    /// The raw bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// Consumes the wrapper, returning the raw bytes.
    #[must_use]
    pub fn into_inner(self) -> Vec<u8> {
        self.0
    }
}

impl From<Vec<u8>> for InputBytes {
    fn from(bytes: Vec<u8>) -> Self {
        Self(bytes)
    }
}

impl std::fmt::Debug for InputBytes {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "InputBytes({} bytes)", self.0.len())
    }
}

impl Serialize for InputBytes {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&base64::engine::general_purpose::STANDARD.encode(&self.0))
    }
}

impl<'de> Deserialize<'de> for InputBytes {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let encoded = String::deserialize(deserializer)?;
        base64::engine::general_purpose::STANDARD
            .decode(encoded)
            .map(Self)
            .map_err(serde::de::Error::custom)
    }
}

impl JsonSchema for InputBytes {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "InputBytes".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "string",
            "contentEncoding": "base64",
        })
    }
}

/// A brief, identity-only view of a service for [`SessionInfo`].
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ServiceBrief {
    /// Stable service identifier.
    pub id: ServiceID,
    /// Human-readable service name.
    #[serde(default)]
    pub name: String,
}

/// Live session identity returned by [`Request::Describe`]. Never stored on disk.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SessionInfo {
    /// The protocol version this session speaks.
    pub protocol_version: ProtocolVersion,
    /// Deterministic session id: the endpoint hash of the canonical config path.
    pub id: String,
    /// Process id of the session.
    pub pid: u32,
    /// Monotonic session start token as Unix nanoseconds. With `pid`, forms a start token.
    pub start_time: u64,
    /// Session name (config `name:` if set, else `basename(working_dir)`).
    #[serde(default)]
    pub name: String,
    /// The directory the session was launched in.
    #[serde(default)]
    pub working_dir: String,
    /// The canonical config path that keys this session's endpoint.
    #[serde(default)]
    pub config_path: String,
    /// The services this session supervises.
    #[serde(default)]
    pub services: Vec<ServiceBrief>,
    /// Whether the service index was shortened to fit the control frame.
    ///
    /// Use [`Request::GetService`] for targeted lookup when this is true.
    #[serde(default)]
    pub services_truncated: bool,
    /// The micromux version of the session binary.
    #[serde(default)]
    pub micromux_version: String,
    /// The session's name, browser URLs, allocated ports, and routing status (protocol 3.11+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session: Option<Box<micromux::SessionSummary>>,
    /// Optional capabilities advertised by newer sessions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<SessionCapabilities>,
}

/// Optional session features and their current limits.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct SessionCapabilities {
    /// Dynamic-service limits, or `None` when runtime creation is not permitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dynamic_services: Option<DynamicServicesCaps>,
    /// Capacity and health of the bounded disk-log read pool.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disk_log_reads: Option<DiskLogReadHealth>,
}

/// Current capacity, occupancy, and timeout history of the disk-log read pool.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
pub struct DiskLogReadHealth {
    /// Whether the pool has started its workers.
    #[serde(default = "default_initialized_disk_log_pool")]
    pub initialized: bool,
    /// Whether the pool can initialize or has an unoccupied worker.
    pub available: bool,
    /// Worker slots configured for the pool.
    pub workers: usize,
    /// Worker threads currently executing a filesystem read.
    pub active: usize,
    /// Maximum reads that may wait for a worker.
    pub queue_capacity: usize,
    /// Reads currently waiting for a worker.
    pub queued: usize,
    /// Reads whose callers timed out or disconnected while the filesystem call remained blocked.
    #[serde(default)]
    pub abandoned: usize,
    /// Requests that have exceeded the read deadline since this session started.
    #[serde(default)]
    pub timed_out_requests: usize,
}

impl Default for DiskLogReadHealth {
    fn default() -> Self {
        Self {
            initialized: default_initialized_disk_log_pool(),
            available: false,
            workers: 0,
            active: 0,
            queue_capacity: 0,
            queued: 0,
            abandoned: 0,
            timed_out_requests: 0,
        }
    }
}

const fn default_initialized_disk_log_pool() -> bool {
    // Protocol 3.8 created the pool while building `Describe`, before this field existed.
    true
}

/// Dynamic-service limits and current usage advertised by a session.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DynamicServicesCaps {
    /// Maximum non-retired dynamic services.
    pub max_services: usize,
    /// Current non-retired dynamic-service count.
    pub live_services: usize,
    /// Maximum and default lease duration in seconds, or `None` for session-lifetime leases.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_lifetime_secs: Option<u64>,
    /// Canonical working-directory roots accepted by the session.
    pub allowed_working_roots: Vec<String>,
}

impl SessionInfo {
    /// Return whether another `Describe` response names the same running session instance.
    #[must_use]
    pub fn is_same_instance(&self, other: &Self) -> bool {
        self.id == other.id && self.pid == other.pid && self.start_time == other.start_time
    }
}

/// A typed error code shared by the protocol and the proxy diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum ErrorCode {
    /// No service with the given id exists.
    UnknownService,
    /// The requested service run is no longer retained or never existed.
    UnknownRun,
    /// No session answered the request.
    NoSession,
    /// More than one live session matched the selector.
    Ambiguous,
    /// A live session is busy (connect/reply timeout); never a reason to delete it.
    Busy,
    /// A request timed out.
    Timeout,
    /// The command is invalid in the service's current state.
    InvalidState,
    /// The latest config could not be reloaded before a restart/enable command.
    ConfigReload,
    /// The target session's policy denied the operation.
    PolicyDenied,
    /// A target-session resource limit was reached.
    LimitExceeded,
    /// An optimistic-concurrency revision was stale.
    RevisionMismatch,
    /// A dynamic service definition was invalid.
    InvalidSpec,
    /// The scheduler stopped before acknowledging a command.
    SchedulerStopped,
    /// The control plane is not supported on this platform.
    UnsupportedPlatform,
    /// The peer speaks an incompatible protocol version.
    ProtocolVersionMismatch,
    /// The request could not be parsed.
    BadRequest,
    /// An unexpected internal error.
    Internal,
    /// A newer peer returned an error code this binary does not know yet.
    #[serde(other)]
    Unknown,
}

/// A response from a session's control server.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub enum Response {
    /// Reply to [`Request::Describe`].
    Description(SessionInfo),
    /// Reply to [`Request::ListServices`].
    Services(Vec<ServiceSnapshot>),
    /// Reply to [`Request::GetService`].
    Service(Box<ServiceSnapshot>),
    /// Reply to [`Request::GetLogs`].
    Logs {
        /// The recent log records.
        lines: Vec<LogLine>,
        /// Whether the session had to drop older records to respect server response limits.
        #[serde(default)]
        truncated: bool,
        /// First sequence still retained by the visible in-memory stream.
        ///
        /// Present only for visible-stream responses. A cursor whose next expected sequence is
        /// below this value has crossed a retention gap and should resume here.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        first_retained_seq: Option<u64>,
    },
    /// Reply to [`Request::ListLogRuns`].
    LogRuns {
        /// Retained runs, oldest first.
        runs: Vec<LogRunSummary>,
    },
    /// Reply to [`Request::GetHealth`].
    Health(Option<HealthAttempt>),
    /// Reply to [`Request::GetHealthHistory`].
    HealthHistory {
        /// Retained attempts in oldest-first order.
        attempts: Vec<HealthAttempt>,
    },
    /// Reply to [`Request::GetEvents`].
    Events {
        /// Retained lifecycle events in ascending sequence order.
        events: Vec<ServiceEvent>,
        /// Whether matching events were omitted by the response bound.
        truncated: bool,
    },
    /// A mutation was *accepted* (validated + queued), not necessarily completed. Carries each
    /// affected service's latched generation.
    Accepted {
        /// Per-service acknowledgements.
        services: Vec<ServiceCommandAck>,
    },
    /// Reply to a dynamic-service mutation.
    DynamicService(DynamicServiceAck),
    /// Reply to a config reconciliation.
    Reconcile(ReconcileReceipt),
    /// Reply to [`Request::GetEnvironment`].
    Environment(ResolvedEnvironment),
    /// A streamed change notification (only after [`Request::Subscribe`]).
    Change(SessionChange),
    /// Reply to [`Request::SendInput`] and [`Request::ResizeTerminal`]: the session queued the input
    /// or resize for its PTYs.
    ///
    /// A service that is not running refuses input with [`ErrorCode::InvalidState`] instead.
    /// Input that races with the process exiting is still dropped later, and recorded as an
    /// `InputDropped` service event.
    TerminalQueued,
    /// Acknowledgement of [`Request::Shutdown`], written just before the session begins exiting.
    ShuttingDown,
    /// A typed error.
    Error {
        /// The error code.
        code: ErrorCode,
        /// A human-readable message.
        message: String,
    },
}

impl Response {
    /// Build an [`Response::Error`] from a code and message.
    #[must_use]
    pub fn error(code: ErrorCode, message: impl Into<String>) -> Self {
        Self::Error {
            code,
            message: message.into(),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::assert_matches;

    use super::*;
    use serde_json::json;
    use similar_asserts::assert_eq;

    fn session(id: &str, pid: u32, start_time: u64, name: &str) -> SessionInfo {
        SessionInfo {
            session: None,
            protocol_version: PROTOCOL_VERSION,
            id: id.to_string(),
            pid,
            start_time,
            name: name.to_string(),
            working_dir: ".".to_string(),
            config_path: "/project/micromux.yaml".to_string(),
            services: Vec::new(),
            services_truncated: false,
            micromux_version: env!("CARGO_PKG_VERSION").to_string(),
            capabilities: None,
        }
    }

    #[test]
    fn session_instance_identity_uses_stable_start_token() {
        let first = session("aaa", 42, 100, "app");
        let alias = session("aaa", 42, 100, "renamed");
        let replacement = session("aaa", 42, 101, "app");

        assert!(first.is_same_instance(&alias));
        assert!(!first.is_same_instance(&replacement));
    }

    #[test]
    fn protocol_version_uses_major_minor_shape_and_accepts_same_major() {
        assert_eq!(
            serde_json::to_value(PROTOCOL_VERSION).unwrap(),
            json!({ "major": 3, "minor": 18 })
        );
        assert_eq!(
            serde_json::from_value::<ProtocolVersion>(json!({ "major": 1, "minor": 0 })).unwrap(),
            ProtocolVersion::new(1, 0)
        );

        assert!(PROTOCOL_VERSION.is_compatible_with(ProtocolVersion::new(3, 18)));
        assert!(!PROTOCOL_VERSION.is_compatible_with(ProtocolVersion::new(2, 9)));
        assert!(!supports_versioned_subscriptions(ProtocolVersion::new(
            3, 6
        )));
        assert!(supports_versioned_subscriptions(ProtocolVersion::new(3, 7)));
    }

    /// A session answers `GetEvents` only from 3.3 on, and never across a major line.
    #[test]
    fn events_require_protocol_3_3_on_the_same_major_line() {
        assert!(ProtocolVersion::new(3, 3).supports(EVENTS_PROTOCOL_VERSION));
        assert!(!ProtocolVersion::new(3, 2).supports(EVENTS_PROTOCOL_VERSION));
        assert!(!ProtocolVersion::new(4, 3).supports(EVENTS_PROTOCOL_VERSION));
        assert!(PROTOCOL_VERSION.supports(EVENTS_PROTOCOL_VERSION));
    }

    /// A session answers `GetEnvironment` only from 3.15 on, and never across a major line.
    #[test]
    fn environment_requires_protocol_3_15_on_the_same_major_line() {
        assert!(ProtocolVersion::new(3, 15).supports(ENVIRONMENT_PROTOCOL_VERSION));
        assert!(ProtocolVersion::new(3, 16).supports(ENVIRONMENT_PROTOCOL_VERSION));
        assert!(!ProtocolVersion::new(3, 14).supports(ENVIRONMENT_PROTOCOL_VERSION));
        assert!(!ProtocolVersion::new(4, 15).supports(ENVIRONMENT_PROTOCOL_VERSION));
        assert!(PROTOCOL_VERSION.supports(ENVIRONMENT_PROTOCOL_VERSION));
    }

    /// A session answers terminal requests only from 3.18 on, and never across a major line.
    #[test]
    fn terminal_requests_require_protocol_3_18_on_the_same_major_line() {
        assert!(ProtocolVersion::new(3, 18).supports(TERMINAL_PROTOCOL_VERSION));
        assert!(!ProtocolVersion::new(3, 17).supports(TERMINAL_PROTOCOL_VERSION));
        assert!(!ProtocolVersion::new(4, 18).supports(TERMINAL_PROTOCOL_VERSION));
        assert!(PROTOCOL_VERSION.supports(TERMINAL_PROTOCOL_VERSION));
    }

    /// Input travels as base64, so control and non-UTF-8 bytes survive the JSON frame unchanged.
    #[test]
    fn send_input_round_trips_arbitrary_bytes_as_base64() -> serde_json::Result<()> {
        let bytes = vec![0x1b, b'[', b'A', 0x00, 0xff, b'\r'];
        let request = Request::SendInput {
            service: "shell".to_string(),
            data: InputBytes::from(bytes.clone()),
            paste: true,
        };

        let encoded = serde_json::to_value(&request)?;
        assert_eq!(
            encoded,
            json!({ "SendInput": { "service": "shell", "data": "G1tBAP8N", "paste": true } })
        );
        assert_matches!(
            serde_json::from_value::<Request>(encoded)?,
            Request::SendInput { service, data, paste: true }
                if service == "shell" && data.as_bytes() == bytes.as_slice()
        );

        // `paste` is additive and defaults to key input.
        assert_matches!(
            serde_json::from_value::<Request>(
                json!({ "SendInput": { "service": "shell", "data": "" } })
            )?,
            Request::SendInput { data, paste: false, .. } if data.as_bytes().is_empty()
        );
        assert!(
            serde_json::from_value::<Request>(
                json!({ "SendInput": { "service": "shell", "data": "not base64!" } })
            )
            .is_err()
        );
        Ok(())
    }

    /// Debug output reaches logs and "unexpected response" messages, so it must never carry
    /// typed bytes, which may be a password.
    #[test]
    fn send_input_debug_output_names_only_the_length() {
        let request = Request::SendInput {
            service: "shell".to_string(),
            data: InputBytes::from(b"hunter2".to_vec()),
            paste: false,
        };

        let debug = format!("{request:?}");

        assert!(debug.contains("7 bytes"), "{debug}");
        assert!(!debug.contains("hunter2"), "{debug}");
        assert!(!debug.contains("104"), "{debug}");
    }

    #[test]
    fn resize_and_terminal_acknowledgement_round_trip() -> serde_json::Result<()> {
        let encoded = serde_json::to_value(Request::ResizeTerminal {
            cols: 120,
            rows: 40,
        })?;
        assert_eq!(
            encoded,
            json!({ "ResizeTerminal": { "cols": 120, "rows": 40 } })
        );
        assert_matches!(
            serde_json::from_value::<Request>(encoded)?,
            Request::ResizeTerminal {
                cols: 120,
                rows: 40
            }
        );

        let encoded = serde_json::to_value(Response::TerminalQueued)?;
        assert_eq!(encoded, json!("TerminalQueued"));
        assert_matches!(
            serde_json::from_value::<Response>(encoded)?,
            Response::TerminalQueued
        );
        Ok(())
    }

    #[test]
    fn environment_request_and_response_round_trip() -> serde_json::Result<()> {
        for service in [None, Some("api".to_string())] {
            let encoded = serde_json::to_value(Request::GetEnvironment {
                service: service.clone(),
            })?;
            assert_matches!(
                serde_json::from_value::<Request>(encoded)?,
                Request::GetEnvironment { service: decoded } if decoded == service
            );
        }
        assert!(Request::GetEnvironment { service: None }.is_retry_safe());

        let environment = ResolvedEnvironment {
            variables: [
                ("API_PORT".to_string(), "20001".to_string()),
                ("DATABASE_URL".to_string(), "postgres://secret".to_string()),
            ]
            .into_iter()
            .collect(),
            stale: true,
        };
        let encoded = serde_json::to_value(Response::Environment(environment.clone()))?;
        assert_eq!(
            encoded,
            json!({
                "Environment": {
                    "variables": {"API_PORT": "20001", "DATABASE_URL": "postgres://secret"},
                    "stale": true
                }
            })
        );
        let Response::Environment(decoded) = serde_json::from_value::<Response>(encoded)? else {
            return Err(serde_json::Error::io(std::io::Error::other(
                "unexpected environment response variant",
            )));
        };
        assert_eq!(decoded, environment);
        Ok(())
    }

    /// Debug output reaches logs and "unexpected response" messages, so it must never carry a
    /// value.
    #[test]
    fn environment_debug_output_names_variables_without_values() {
        let response = Response::Environment(ResolvedEnvironment {
            variables: [("DATABASE_URL".to_string(), "postgres://secret".to_string())]
                .into_iter()
                .collect(),
            stale: false,
        });

        let debug = format!("{response:?}");

        assert!(debug.contains("DATABASE_URL"), "{debug}");
        assert!(!debug.contains("postgres://secret"), "{debug}");
    }

    #[test]
    fn protocol_version_rejects_plain_integer_shape() {
        let err = serde_json::from_value::<ProtocolVersion>(json!(5)).unwrap_err();

        assert!(
            err.to_string().contains("invalid type"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn protocol_version_rejects_missing_minor() {
        let err = serde_json::from_value::<ProtocolVersion>(json!({ "major": 5 })).unwrap_err();

        assert!(
            err.to_string().contains("missing field `minor`"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn unknown_error_codes_degrade_without_deserialize_failure() {
        let code = serde_json::from_str::<ErrorCode>("\"FutureError\"").unwrap();

        assert_eq!(code, ErrorCode::Unknown);
    }

    #[test]
    fn session_info_accepts_missing_additive_fields() {
        let info = serde_json::from_value::<SessionInfo>(json!({
            "protocol_version": { "major": 3, "minor": 2 },
            "id": "abc",
            "pid": 42,
            "start_time": 99
        }))
        .unwrap();

        assert_eq!(info.protocol_version, ProtocolVersion::new(3, 2));
        assert_eq!(info.name, "");
        assert!(info.services.is_empty());
        assert!(!info.services_truncated);
        assert_eq!(info.micromux_version, "");
        assert!(info.capabilities.is_none());
    }

    #[test]
    fn disk_log_read_health_accepts_missing_timeout_history() {
        let health = serde_json::from_value::<DiskLogReadHealth>(json!({
            "available": true,
            "workers": 4,
            "active": 1,
            "queue_capacity": 4,
            "queued": 2
        }))
        .unwrap();

        assert!(health.initialized);
        assert_eq!(health.abandoned, 0);
        assert_eq!(health.timed_out_requests, 0);
        assert_eq!(health.initialized, DiskLogReadHealth::default().initialized);
    }

    #[test]
    fn dynamic_service_ack_round_trips_and_accepts_missing_additive_fields() {
        let ack = DynamicServiceAck {
            service: "debug".to_string(),
            revision: 2,
            observed_generation: 1,
            expires_at_unix_ms: Some(1234),
            command: vec!["true".to_string()],
            working_dir: None,
            ports: vec![3201],
            env_keys: vec!["RUST_LOG".to_string()],
            restart: micromux::RestartPolicy::Never,
            healthcheck_configured: false,
            already_retired: false,
            idempotent_replay: true,
        };
        let encoded = serde_json::to_value(Response::DynamicService(ack.clone())).unwrap();
        let decoded = serde_json::from_value::<Response>(encoded).unwrap();
        let Response::DynamicService(decoded) = decoded else {
            panic!("expected a dynamic-service response");
        };
        assert_eq!(decoded.service, ack.service);
        assert_eq!(decoded.revision, ack.revision);
        assert!(decoded.idempotent_replay);

        // The defaulted fields are additive: a minimal older payload still deserializes.
        let minimal = serde_json::from_value::<DynamicServiceAck>(json!({
            "service": "debug",
            "revision": 1,
            "observed_generation": 0,
            "command": ["true"],
            "restart": "Never",
            "healthcheck_configured": false
        }))
        .unwrap();
        assert_eq!(minimal.expires_at_unix_ms, None);
        assert_eq!(minimal.ports, [] as [u16; 0]);
        assert!(!minimal.already_retired);
    }

    #[test]
    fn reconcile_request_and_receipt_round_trip() {
        let request = Request::ReconcileConfig { dry_run: true };
        let encoded = serde_json::to_value(&request).unwrap();
        assert_matches!(
            serde_json::from_value::<Request>(encoded).unwrap(),
            Request::ReconcileConfig { dry_run: true }
        );

        let receipt = micromux::ReconcileReceipt {
            config_path: "/project/micromux.yaml".to_string(),
            dry_run: true,
            actions: vec![micromux::ReconcileAction {
                service: "worker".to_string(),
                action: micromux::ReconcileActionKind::Changed,
                detail: "changed service spec".to_string(),
            }],
        };
        let encoded = serde_json::to_value(Response::Reconcile(receipt.clone())).unwrap();
        let Response::Reconcile(decoded) = serde_json::from_value::<Response>(encoded).unwrap()
        else {
            panic!("expected a reconcile response");
        };
        assert_eq!(decoded, receipt);
    }

    #[test]
    fn versioned_subscription_carries_the_client_protocol() {
        let request = Request::SubscribeWithVersion {
            protocol_version: PROTOCOL_VERSION,
        };

        let encoded = serde_json::to_value(&request).unwrap();

        assert_matches!(
            serde_json::from_value::<Request>(encoded).unwrap(),
            Request::SubscribeWithVersion { protocol_version }
                if protocol_version == PROTOCOL_VERSION
        );
    }

    #[test]
    fn health_history_request_and_response_round_trip() -> serde_json::Result<()> {
        let request = Request::GetHealthHistory {
            service: "api".to_string(),
        };
        let encoded = serde_json::to_value(&request)?;
        assert_matches!(
            serde_json::from_value::<Request>(encoded)?,
            Request::GetHealthHistory { service } if service == "api"
        );

        let response = Response::HealthHistory {
            attempts: vec![HealthAttempt {
                run_generation: 2,
                attempt: 3,
                command: "probe".to_string(),
                output: Vec::new(),
                result: None,
            }],
        };
        let encoded = serde_json::to_value(response)?;
        let Response::HealthHistory { attempts } = serde_json::from_value::<Response>(encoded)?
        else {
            return Err(serde_json::Error::io(std::io::Error::other(
                "unexpected health-history response variant",
            )));
        };
        assert_eq!(attempts.len(), 1);
        assert_eq!(attempts.first().map(|attempt| attempt.attempt), Some(3));
        Ok(())
    }

    #[test]
    fn logs_response_accepts_missing_truncated_flag() {
        let response = serde_json::from_value::<Response>(json!({
            "Logs": {
                "lines": []
            }
        }))
        .unwrap();

        match response {
            Response::Logs {
                lines,
                truncated,
                first_retained_seq,
            } => {
                assert!(lines.is_empty());
                assert!(!truncated);
                assert_eq!(first_retained_seq, None);
            }
            other => panic!("unexpected response: {other:?}"),
        }
    }

    #[test]
    fn protocol_version_ignores_additive_fields() {
        let version = serde_json::from_value::<ProtocolVersion>(json!({
            "major": 3,
            "minor": 18,
            "future_capability": true
        }))
        .unwrap();

        assert_eq!(version, PROTOCOL_VERSION);
    }

    #[test]
    fn only_observations_are_safe_to_retry_after_a_lost_response() {
        assert!(Request::ListServices.is_retry_safe());
        assert!(
            Request::GetService {
                service: "api".to_string(),
            }
            .is_retry_safe()
        );
        assert!(Request::ReconcileConfig { dry_run: true }.is_retry_safe());
        assert!(!Request::RestartAll.is_retry_safe());
        assert!(!Request::ReconcileConfig { dry_run: false }.is_retry_safe());
        assert!(!Request::Shutdown.is_retry_safe());
        // A replayed keystroke would type twice.
        assert!(
            !Request::SendInput {
                service: "api".to_string(),
                data: InputBytes::from(b"y".to_vec()),
                paste: false,
            }
            .is_retry_safe()
        );
        assert!(!Request::ResizeTerminal { cols: 80, rows: 24 }.is_retry_safe());
    }

    #[test]
    fn dynamic_request_round_trips_flat_spec_and_humantime_lease() -> serde_json::Result<()> {
        let value = json!({
            "StartDynamicService": {
                "params": {
                    "service": "debug",
                    "command": ["CMD-SHELL", "echo ready"],
                    "environment": {"MODE": "debug"},
                    "healthcheck": null,
                    "expires_after": "90s",
                    "idempotency_key": "request-1"
                }
            }
        });
        let request = serde_json::from_value::<Request>(value.clone())?;
        let Request::StartDynamicService { params } = &request else {
            return Err(serde_json::Error::io(std::io::Error::other(
                "unexpected request variant",
            )));
        };
        assert_eq!(
            params.expires_after,
            Some(micromux::Lease::After(std::time::Duration::from_secs(90)))
        );
        assert_eq!(params.spec.healthcheck, micromux::SpecField::Clear);
        let encoded = serde_json::to_value(&request)?;
        assert_eq!(
            encoded.pointer("/StartDynamicService/params/expires_after"),
            Some(&json!("1m 30s"))
        );
        assert_eq!(
            encoded.pointer("/StartDynamicService/params/extra_args"),
            Some(&json!([]))
        );
        let Request::StartDynamicService { params } = serde_json::from_value(encoded)? else {
            return Err(serde_json::Error::io(std::io::Error::other(
                "unexpected round-trip request variant",
            )));
        };
        assert_eq!(
            params.expires_after,
            Some(micromux::Lease::After(std::time::Duration::from_secs(90)))
        );
        Ok(())
    }

    #[test]
    fn dynamic_request_round_trips_an_unbounded_or_omitted_lease() -> serde_json::Result<()> {
        let unbounded = json!({
            "StartDynamicService": {
                "params": {
                    "service": "debug",
                    "command": ["true"],
                    "expires_after": "none"
                }
            }
        });
        let request = serde_json::from_value::<Request>(unbounded)?;
        let Request::StartDynamicService { params } = request else {
            return Err(serde_json::Error::io(std::io::Error::other(
                "unexpected request variant",
            )));
        };
        assert_eq!(params.expires_after, Some(micromux::Lease::Unbounded));

        let omitted = json!({
            "StartDynamicService": {
                "params": {
                    "service": "debug",
                    "command": ["true"]
                }
            }
        });
        let Request::StartDynamicService { params } = serde_json::from_value(omitted)? else {
            return Err(serde_json::Error::io(std::io::Error::other(
                "unexpected request variant",
            )));
        };
        assert_eq!(params.expires_after, None);
        Ok(())
    }
}