synaps-engine 0.10.1

Runtime engine — streaming, tools, MCP, skills, extensions, sidecar
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
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
//! Identity, configuration, commands, events and the envelope — the entire
//! client↔session contract (PLAN-phase2 §2.1–§2.4). Everything a client can
//! send is serde-able from day one; `SessionEventWire::Stream` deliberately
//! is not (it carries the un-serialised `StreamEvent` in-process).

use std::path::PathBuf;

use serde::{Deserialize, Serialize};

use super::view::RuntimeView;

// ── identity + configuration ──────────────────────────────────────────────────

/// Conversation session id — the `Session.id` string (`{name}-{ts}-{pid}`; see
/// events/registry.rs sanitize rules). NOT the tools::activation::SessionId
/// (that is the per-runtime gate identity minted at Runtime::from_parts).
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SessionId(pub String);

impl SessionId {
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for SessionId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<String> for SessionId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for SessionId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

/// Ordered key-value snapshot of a client's environment.
pub type SessionEnv = Vec<(String, String)>;

/// Prefixes stripped from the client env before it enters the session.
/// These are client-only or daemon-only knobs — never session identity.
const ENV_STRIP_PREFIXES: &[&str] = &[
    "SYNAPS_CLIENT_",
    "SYNAPS_TUI_",
    "SYNAPS_DAEMON_",
    "SYNAPS_MEM_TRACE",
];

/// Secret patterns (case-insensitive suffix/infix) stripped at the client.
/// Secrets never reach the daemon — the broker owns credentials.
/// Build a [`SessionEnv`] from the current process environment, stripping
/// client-only prefixes and secrets. Returns `(kept_env, stripped_secret_names)`.
/// The stripped names are ONLY the secrets (not `SYNAPS_*` prefixes, those are noise).
/// Used by thin clients before `Hello`.
pub fn capture_client_env() -> (SessionEnv, Vec<String>) {
    strip_client_env(std::env::vars())
}

/// The pure part of [`capture_client_env`]: filter `vars` (unit-testable
/// without touching the process environment).
pub fn strip_client_env(
    vars: impl IntoIterator<Item = (String, String)>,
) -> (SessionEnv, Vec<String>) {
    let mut env: SessionEnv = Vec::new();
    let mut stripped: Vec<String> = Vec::new();
    for (k, v) in vars {
        // A credential VALUE is stripped whatever its key is called
        // (`DATABASE_URL=postgres://u:p@h`): the name denylist alone let it
        // through to the daemon and the session files.
        let secret_value = agent_core::core::config::is_secret_env_value(&v);
        if should_strip_env(&k) || secret_value {
            // Only record secret names, not SYNAPS_* prefix noise.
            if is_secret_key(&k) || secret_value {
                stripped.push(k);
            }
        } else {
            env.push((k, v));
        }
    }
    env.sort_by(|(a, _), (b, _)| a.cmp(b));
    stripped.sort();
    (env, stripped)
}

/// Whether a key should be stripped from the client env snapshot.
pub fn should_strip_env(key: &str) -> bool {
    let upper = key.to_ascii_uppercase();
    for prefix in ENV_STRIP_PREFIXES {
        if upper.starts_with(prefix) {
            return true;
        }
    }
    is_secret_key(&upper)
}

/// Whether a key matches the secret denylist (case-insensitive).
/// Delegates to the canonical implementation in `agent_core::core::config`.
pub fn is_secret_key(key: &str) -> bool {
    agent_core::core::config::is_secret_key(key)
}

/// Everything `EngineHost::create_session` needs. Serializable: it is the
/// payload of the wire `Attach::Create`. Mirrors `EngineOpts` minus the
/// host-level fields (profile, no_extensions), plus the per-session facts a
/// daemon cannot inherit from its own process (cwd, env overlay).
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SessionConfig {
    /// `EngineOpts.continue_session`. `Some(None)` = bare `--continue` (most
    /// recent journal). Plain serde encodes `Some(None)` as `null` and decodes
    /// that as `None`, so the daemon could never receive a bare `--continue`
    /// (soak F21) — `double_option` keeps the two levels apart on the wire.
    #[serde(default, with = "double_option", skip_serializing_if = "Option::is_none")]
    pub continue_session: Option<Option<String>>,
    /// `EngineOpts.system`.
    #[serde(default)]
    pub system: Option<String>,
    /// `EngineOpts.prompt_manifest`.
    #[serde(default)]
    pub prompt_manifest: Option<PathBuf>,
    /// Per-session working directory. `None` = process cwd (in-process hosts
    /// pass `None` today → byte-identical). The daemon ALWAYS fills it from
    /// `Hello.cwd`.
    #[serde(default)]
    pub cwd: Option<PathBuf>,
    /// Per-session environment snapshot. `None` = inherit process env
    /// (in-process hosts). The daemon fills it from `Hello.env` on
    /// `Attach::Create` only; attaching to an existing session does not
    /// change the creator's env.
    #[serde(default)]
    pub env: Option<SessionEnv>,
    /// Names of environment variables stripped as secrets at the client
    /// (e.g. `GH_TOKEN`, `AWS_SECRET_ACCESS_KEY`). NOT the `SYNAPS_*`
    /// prefixes (those are noise). Used for loud notices when a tool fails
    /// referencing a stripped secret. Persisted in the journal (names only,
    /// never values).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub env_stripped: Vec<String>,
    /// `Confirm` hook results auto-approved (server `--auto-approve-confirms`).
    /// Interactive hosts: false.
    #[serde(default)]
    pub auto_approve_confirms: bool,
    /// CLI `--model` override applied after session resolution.
    #[serde(default)]
    pub model_override: Option<String>,
    /// Save policy: only "save at all" — the TUI/chat/rpc always save; tests
    /// may disable. Default `true`.
    #[serde(default = "default_true")]
    pub persist: bool,
    /// Headless-chat policy: after every turn, save + `assess_context` and
    /// auto-compact when the engine budget says so (chat.rs post-turn block).
    /// The TUI does its own compaction; default `false`.
    #[serde(default)]
    pub auto_compact: bool,
    /// Compaction transition policy: `InPlace` (default; chat, today's
    /// actor) or `LinkedSuccessor` (the TUI's successor-session chain).
    #[serde(default)]
    pub compaction_policy: CompactionPolicyWire,
    /// Block `create` on process-level extension discovery before emitting
    /// `on_session_start` (chat/daemon). The TUI passes `false`: the actor
    /// emits it from a spawned waiter so boot never blocks on discovery.
    #[serde(default = "default_true")]
    pub await_extensions: bool,
    /// Never `Park` this session (`--keep-warm`). Default `false`.
    #[serde(default)]
    pub keep_warm: bool,
    /// `--name`: name the session at create (same rules as `/cmd saveas`;
    /// must be unique among saved sessions). Applied before the registry
    /// entry is written so `synaps send --session <name>` resolves at once.
    #[serde(default)]
    pub name: Option<String>,
    /// (E-P7, §S3) Hard per-session spend ceiling in USD. `None` = unbounded.
    /// Checked after every `Usage` stream event; a breach cancels the turn,
    /// revokes any armed driver, and emits `CostCapReached`. This is the
    /// host-owned circuit breaker for an actor-resident autonomous driver.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_session_cost: Option<f64>,
}

fn default_true() -> bool {
    true
}

/// Serializable mirror of `runtime::compaction::CompactionPolicy`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CompactionPolicyWire {
    #[default]
    InPlace,
    LinkedSuccessor,
}

impl From<CompactionPolicyWire> for crate::runtime::compaction::CompactionPolicy {
    fn from(p: CompactionPolicyWire) -> Self {
        match p {
            CompactionPolicyWire::InPlace => Self::InPlace,
            CompactionPolicyWire::LinkedSuccessor => Self::LinkedSuccessor,
        }
    }
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            continue_session: None,
            system: None,
            prompt_manifest: None,
            cwd: None,
            env: None,
            env_stripped: Vec::new(),
            auto_approve_confirms: false,
            model_override: None,
            persist: true,
            auto_compact: false,
            compaction_policy: CompactionPolicyWire::InPlace,
            await_extensions: true,
            keep_warm: false,
            name: None,
            max_session_cost: None,
        }
    }
}

/// Serializable copy of `engine::setup::ContinueInfo`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContinueInfoWire {
    pub session_id: String,
    /// "chain", "name", "compacted", or None.
    pub resolved_via: Option<String>,
    pub query: String,
    /// F24: notice when the session was followed through a compaction chain.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compaction_notice: Option<String>,
}

impl From<&crate::engine::setup::ContinueInfo> for ContinueInfoWire {
    fn from(c: &crate::engine::setup::ContinueInfo) -> Self {
        Self {
            session_id: c.session_id.clone(),
            resolved_via: c.resolved_via.clone(),
            query: c.query.clone(),
            compaction_notice: c.compaction_notice.clone(),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SessionMeta {
    pub id: SessionId,
    pub name: Option<String>,
    pub model: String,
    pub cwd: Option<PathBuf>,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub continued: bool,
    pub continue_info: Option<ContinueInfoWire>,
    /// Daemon pid (in-process: this process).
    pub host_pid: u32,
    // ── filled at list time from the handle's cells (meta itself is frozen) ──
    #[serde(default)]
    pub lifecycle: SessionLifecycle,
    #[serde(default)]
    pub clients: usize,
    #[serde(default)]
    pub input_owner: Option<ClientId>,
    #[serde(default)]
    pub awaiting_input: usize,
    /// `conv.session.id` — differs from `id` after a LinkedSuccessor compaction.
    #[serde(default)]
    pub journal_id: String,
    /// Set when the session's journal is locked by another process (F23):
    /// `"pid N (kind)"`. Shown in `daemon sessions`; cleared on unpark.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub locked_by: Option<String>,
}

/// Where a session is in its park/unpark life (`SessionHandle::lifecycle`).
#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionLifecycle {
    #[default]
    Live = 0,
    Parking = 1,
    Parked = 2,
    Ending = 3,
}

impl SessionLifecycle {
    pub fn from_u8(v: u8) -> Self {
        match v {
            1 => Self::Parking,
            2 => Self::Parked,
            3 => Self::Ending,
            _ => Self::Live,
        }
    }
}

/// Minted by the actor per Attach.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ClientId(pub u64);

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClientMeta {
    pub kind: ClientKind,
    /// `$TERM`, informational.
    pub terminal: Option<String>,
    /// Client-generated uuid; reattach dedup (day 3).
    pub instance: String,
    /// How much history this client wants mirrored (phase 4).
    #[serde(default)]
    pub history: HistoryMode,
    /// Display items in `Attached.display_tail` / `DisplayTail` queries (phase 4).
    #[serde(default = "default_tail_items")]
    pub tail_items: usize,
}

/// Default for `ClientMeta.tail_items`: matches the TUI's resumed-display cap.
pub const DEFAULT_TAIL_ITEMS: usize = 120;

fn default_tail_items() -> usize {
    DEFAULT_TAIL_ITEMS
}

/// `SYNAPS_ATTACH_TAIL_ITEMS` (client side): display items requested in
/// `Attached.display_tail`; `DEFAULT_TAIL_ITEMS` when unset/invalid.
pub fn tail_items_from_env() -> usize {
    std::env::var("SYNAPS_ATTACH_TAIL_ITEMS")
        .ok()
        .and_then(|v| v.trim().parse::<usize>().ok())
        .unwrap_or(DEFAULT_TAIL_ITEMS)
}

impl ClientMeta {
    /// Fresh meta with a random instance id and no terminal.
    pub fn new(kind: ClientKind) -> Self {
        Self {
            kind,
            terminal: None,
            instance: uuid::Uuid::new_v4().to_string(),
            history: HistoryMode::default(),
            tail_items: tail_items_from_env(),
        }
    }
}

/// What a client wants in `Attached` / `Conversation`: the full
/// `api_messages` mirror (`Full`, the 741b6b60 behaviour) or only the
/// digest + a daemon-side display tail (`Digest`, phase 4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum HistoryMode {
    #[default]
    Full,
    Digest,
}

impl HistoryMode {
    /// `SYNAPS_CLIENT_HISTORY=full|digest`; `default` wins when unset or
    /// unrecognised.
    pub fn from_env_or(default: Self) -> Self {
        match std::env::var("SYNAPS_CLIENT_HISTORY").ok().as_deref().map(str::trim) {
            Some(v) if v.eq_ignore_ascii_case("full") => Self::Full,
            Some(v) if v.eq_ignore_ascii_case("digest") => Self::Digest,
            _ => default,
        }
    }

    /// What `synaps --attach` asks for (phase 4 B7: `Digest`).
    /// `SYNAPS_CLIENT_HISTORY=full` restores the 741b6b60 mirror wholesale.
    pub fn attach_client_default() -> Self {
        Self::Digest
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClientKind {
    Tui,
    Chat,
    Attach,
    Rpc,
    Server,
    Test,
}

/// Attach mode. Ownership (B1): `Mirror` owns input iff nobody does,
/// `Takeover` steals it, `Observe` never owns it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AttachMode {
    Mirror,
    Takeover,
    Observe,
}

/// Actor-side client accounting (§8): `Detached` never cancels a stream.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AttachState {
    Attached(usize),
    Detached { running: bool },
    /// Save + PTY teardown in progress (B3).
    Parking,
    /// `runtime`/`conv` dropped; `background` alive; unpark on Attach/wake (B3).
    Parked,
}

// ── prompts ───────────────────────────────────────────────────────────────────

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PromptKind {
    Secret,
    Confirm,
}

/// Fixed title `resolve_before_tool_call_result` uses for Confirm prompts
/// (runtime/mod.rs).
pub const CONFIRM_PROMPT_TITLE: &str = "Confirm tool call";
/// Fixed title `confirm_activation_with_host` uses for the `activate_tools`
/// y/yes gate (tools/discovery.rs). Everything not in the confirm set is
/// `Secret` (masked input).
pub const CONFIRM_ACTIVATION_PROMPT_TITLE: &str = "Confirm tool activation";

impl PromptKind {
    /// Derive the kind from the prompt title (the actor classifies at receipt;
    /// `SecretPromptHandle::prompt` classifies for the in-process TUI).
    pub fn from_title(title: &str) -> Self {
        if title == CONFIRM_PROMPT_TITLE || title == CONFIRM_ACTIVATION_PROMPT_TITLE {
            Self::Confirm
        } else {
            Self::Secret
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PromptRequest {
    /// Per-session monotonic; actor dedups answers on it.
    pub id: u64,
    pub kind: PromptKind,
    pub title: String,
    pub prompt: String,
    pub raised_at: chrono::DateTime<chrono::Utc>,
}

// ── commands, settings, queries ───────────────────────────────────────────────

/// A command with its origin. `from: None` = host-originated (router,
/// lifecycle, idle probe) and bypasses input ownership (B1).
#[derive(Debug)]
pub struct Addressed {
    pub from: Option<ClientId>,
    pub cmd: SessionCommand,
}

/// Why a `Checkpoint` was requested.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CheckpointReason {
    Reload,
    HostRequest,
}

/// The entire client→session control surface (SEAMS §5.2/§5.3).
///
/// `Debug` is manual: `Submit`/`Steer`/`SubmitPrepared`/`Answer`/`Resume`
/// print `<redacted>` (no lengths) so a command can be traced by *type*.
#[derive(Serialize, Deserialize)]
#[serde(tag = "cmd", rename_all = "snake_case")]
pub enum SessionCommand {
    /// User-authored prompt. Actor: reset auto-turn counter, push user msg
    /// verbatim, start turn.
    Submit {
        text: String,
        /// Pre-built canonical user content blocks (images, documents)
        /// produced by `PendingAttachments::build_content` on the client.
        /// Empty ⇔ text-only (backward compatible).
        #[serde(default)]
        attachments: Vec<serde_json::Value>,
    },
    /// Text typed while streaming. Actor: steer if a steer_tx is live else
    /// queue; ALWAYS also sets queued_message.
    Steer { text: String },
    /// Esc. Cancel, adopt the turn's partial history + append the
    /// interruption marker (`engine::interrupt`), dequeue, flush pending
    /// events, cancel subagents, save.
    Cancel,
    /// Answer to a PromptRequest. `None` = cancelled.
    /// NEVER journaled, NEVER replayed, NEVER traced.
    Answer { prompt_id: u64, value: Option<String> },
    /// `id` is client-chosen and echoed in `SettingChanged.id`.
    Set { id: u64, setting: SessionSetting },
    Compact { instructions: Option<String> },
    /// `/new`: ConversationState::clear.
    NewSession,
    Save,
    /// Reply = `SessionEventWire::QueryResult { id, value }`.
    Query { id: u64, query: SessionQuery },
    /// Reply = `Attached { client_id, … }` on THIS client's channel only.
    Attach { client: ClientMeta, mode: AttachMode },
    Detach { client: ClientId },
    /// Host shutdown of this session: save → on_session_end → leases → Ended.
    End { reason: EndReason },
    /// Resync after Lagged (B, day 3): actor re-sends history + turn_replay.
    Resync { client: ClientId, since_seq: u64 },
    /// Runtime-backed slash command (`engine::commands::handle_engine_command`:
    /// /model /thinking /context /trace /memory /compact …). Reply =
    /// `QueryResult { id, value: {"kind": .., "text": ..} }`.
    EngineCommand { id: u64, name: String, arg: String },
    /// (A3) dispatch.rs LoadSkill — pre-built tool_use/tool_result pair
    /// (+ optional user text) then a turn. Does NOT reset
    /// consecutive_auto_turns.
    SubmitPrepared {
        messages: Vec<crate::SharedMessage>,
        #[serde(default)]
        user_text: Option<String>,
    },
    /// (A3) tools-backed (non-interactive) plugin command on THE runtime's
    /// tool set. Reply = `QueryResult{id, {kind:"plugin_output", ..}}`.
    PluginCommand { id: u64, plugin: String, name: String, arg: String },
    /// (A3) `/resume`: save current, load `query`, restore model/reasoning/
    /// system prompt, swap conversation. Reply = `Resumed{id, ..}`.
    Resume { id: u64, query: String },
    /// (B1, used by C3 reload) cancel any turn (partial history + marker),
    /// abort compaction, save, close PTYs, emit Notice. Never ends the
    /// session. Reply = `QueryResult{id: CHECKPOINT_QUERY_ID, {ok:true}}`.
    Checkpoint { reason: CheckpointReason },
    /// (B3) pin/unpin (`--keep-warm`, `/keep-warm on|off`).
    KeepWarm { on: bool },
    /// Host-only (never wire): park now if `can_park()` (reload rehydrates
    /// a Parked session Parked). A no-op otherwise.
    #[serde(skip)]
    Park,
    /// Host→session (never wire): the actor re-emits as `SessionEventWire`.
    #[serde(skip)]
    HostEvent(HostEvent),
    /// (E-P0) Start or re-arm the session driver for `plugin`.
    /// `command` is the interactive command name (e.g. "auto");
    /// `arg` is everything after the command ("start -- do X").
    /// No `DriverStop` — `Cancel` handles that (§2).
    DriverStart {
        plugin: String,
        command: String,
        arg: String,
    },
}

/// What `Checkpoint{Reload}` reports so `daemon reload` can rebuild the
/// session as it IS (not as it was created): the actor's config, keep-warm
/// pin, lifecycle, the non-persisted knobs (`settings_replay`, incl.
/// `/system`), and the CURRENT model/thinking.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SessionReloadRecord {
    pub config: SessionConfig,
    pub keep_warm: bool,
    pub lifecycle: SessionLifecycle,
    #[serde(default)]
    pub settings_replay: Vec<SessionSetting>,
    pub model: String,
    pub thinking_level: String,
}

impl std::fmt::Debug for SessionCommand {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Submit { attachments, .. } => {
                let kinds: Vec<&str> = attachments
                    .iter()
                    .filter_map(|b| b.get("type").and_then(|v| v.as_str()))
                    .collect();
                f.debug_struct("Submit")
                    .field("text", &format_args!("<redacted>"))
                    .field("attachments", &format_args!("{}:{:?}", attachments.len(), kinds))
                    .finish()
            }
            Self::Steer { .. } => f
                .debug_struct("Steer")
                .field("text", &format_args!("<redacted>"))
                .finish(),
            Self::SubmitPrepared { .. } => f
                .debug_struct("SubmitPrepared")
                .field("messages", &format_args!("<redacted>"))
                .field("user_text", &format_args!("<redacted>"))
                .finish(),
            Self::Answer { prompt_id, .. } => f
                .debug_struct("Answer")
                .field("prompt_id", prompt_id)
                .field("value", &format_args!("<redacted>"))
                .finish(),
            Self::Resume { id, .. } => f
                .debug_struct("Resume")
                .field("id", id)
                .field("query", &format_args!("<redacted>"))
                .finish(),
            Self::Cancel => f.write_str("Cancel"),
            Self::Set { id, setting } => {
                f.debug_struct("Set").field("id", id).field("setting", setting).finish()
            }
            Self::Compact { instructions } => {
                f.debug_struct("Compact").field("instructions", instructions).finish()
            }
            Self::NewSession => f.write_str("NewSession"),
            Self::Save => f.write_str("Save"),
            Self::Park => f.write_str("Park"),
            Self::Query { id, query } => {
                f.debug_struct("Query").field("id", id).field("query", query).finish()
            }
            Self::Attach { client, mode } => {
                f.debug_struct("Attach").field("client", client).field("mode", mode).finish()
            }
            Self::Detach { client } => f.debug_struct("Detach").field("client", client).finish(),
            Self::End { reason } => f.debug_struct("End").field("reason", reason).finish(),
            Self::Resync { client, since_seq } => f
                .debug_struct("Resync")
                .field("client", client)
                .field("since_seq", since_seq)
                .finish(),
            Self::EngineCommand { id, name, arg } => f
                .debug_struct("EngineCommand")
                .field("id", id)
                .field("name", name)
                .field("arg", arg)
                .finish(),
            Self::PluginCommand { id, plugin, name, arg } => f
                .debug_struct("PluginCommand")
                .field("id", id)
                .field("plugin", plugin)
                .field("name", name)
                .field("arg", arg)
                .finish(),
            Self::Checkpoint { reason } => {
                f.debug_struct("Checkpoint").field("reason", reason).finish()
            }
            Self::KeepWarm { on } => f.debug_struct("KeepWarm").field("on", on).finish(),
            Self::HostEvent(ev) => f.debug_tuple("HostEvent").field(ev).finish(),
            Self::DriverStart { plugin, command, .. } => f
                .debug_struct("DriverStart")
                .field("plugin", plugin)
                .field("command", command)
                .field("arg", &format_args!("<redacted>"))
                .finish(),
        }
    }
}

/// Host-originated events pushed into a session (C3 router, loader).
#[derive(Debug, Clone)]
pub enum HostEvent {
    ExtensionNotification {
        extension_id: String,
        method: String,
        params: serde_json::Value,
    },
    LoaderProgress(crate::extensions::loader::ExtensionLoaderEvent),
}

/// The `&mut Runtime` setters the TUI/rpc/server call (SEAMS §5.3).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "setting", rename_all = "snake_case")]
pub enum SessionSetting {
    /// try_set_model → SettingApplied::Model{applied, thinking_level}
    Model { model: String },
    /// set_reasoning_level_checked
    ReasoningLevel {
        #[serde(with = "reasoning_level_serde")]
        level: agent_core::reasoning::ReasoningLevel,
    },
    /// set_context_window
    ContextWindow { tokens: Option<u64> },
    CompactionModel { model: Option<String> },
    ApiRetries { n: u32 },
    SubagentTimeout { secs: u64 },
    MaxToolOutput { bytes: usize },
    BashTimeout { secs: u64 },
    BashMaxTimeout { secs: u64 },
    /// set_system_prompt
    SystemPrompt { text: String },
    /// reload_prompt() → SettingApplied::PromptReloaded{generation, source}
    ReloadPrompt,
    /// grant_worker_model
    GrantWorkerModel { model: String },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SettingApplied {
    /// Correlates with `Set{id}`.
    #[serde(default)]
    pub id: u64,
    pub setting: String,
    pub ok: bool,
    pub message: Option<String>,
    pub view: RuntimeView,
    /// `{from, to}` when a model change clamped the reasoning level, so the
    /// TUI renders `reasoning_clamp_notice` byte-for-byte.
    #[serde(default)]
    pub clamp: Option<ReasoningClampWire>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReasoningClampWire {
    pub from: String,
    pub to: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "query", rename_all = "snake_case")]
pub enum SessionQuery {
    /// {session, model, tokens, cost, streaming, auto_turns, attached, pending_prompts}
    Status,
    /// Vec<SharedMessage> (api_messages)
    Messages,
    /// Vec<SubagentDisplayRow>
    SubagentRows,
    /// runtime.prompt_inspection_json()
    PromptInspection,
    /// rpc_dispatch::build_tools_list_body input
    ToolsSchema,
    /// RuntimeView (cheap; LocalTransport answers without a hop)
    View,
    /// assess_context
    ContextAssessment,
    /// `engine::commands::context_command(runtime, Some(api_messages))` text.
    ContextReport,
    /// `display::DisplayTail` of the last `items` display items (phase 4).
    DisplayTail { items: usize },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EndReason {
    ClientQuit,
    HostShutdown,
    Evicted,
    Error,
    /// F18: zero turns, zero clients, park grace elapsed. There is nothing
    /// to journal, so the session cannot park; it ends instead of holding a
    /// Runtime resident forever.
    Idle,
}

// ── events + envelope ─────────────────────────────────────────────────────────

/// What a session tells its clients. `Stream` carries the un-serialised
/// StreamEvent in-process (LocalTransport) — that IS the byte-identical
/// contract. The socket boundary converts to `wire::WireSessionEvent`.
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)] // Attached carries the full snapshot by design (§2.4)
pub enum SessionEventWire {
    Stream(crate::StreamEvent),
    /// Actor bookkeeping the client needs to mirror `App` fields exactly.
    /// `user_text` = the prompt that started the turn: the queued text on
    /// `QueuedAuto` (every client pushes the User card + scroll), the
    /// submitted text on `User` (clients OTHER than the submitter push the
    /// card; the submitter drew it at submit); `None` otherwise. The attach
    /// replay ring stores it as `None` (the snapshot's history has it).
    TurnStarted {
        turn_baseline: usize,
        trigger: TurnTrigger,
        user_text: Option<String>,
    },
    /// Emitted after every MessageHistory / Done / Error / Cancel / Compact so
    /// mirrors never diverge: the actor's api_messages IS the truth.
    Conversation(ConversationSnapshot),
    Prompt(PromptRequest),
    /// So mirrors dismiss the modal.
    PromptResolved { prompt_id: u64 },
    /// Drained event card — presentation only.
    External(crate::events::types::Event),
    AutoTurnCapReached { cap: u32 },
    /// The turn machine is idle: a stream ended (Done/Error/Cancel) and NO
    /// auto-turn followed. Headless hosts gate stdin on this so a queued
    /// auto-turn is never raced by the next line.
    Idle,
    /// "→ steering:" vs "queued:".
    Steered { text: String, delivered: bool },
    Dequeued { text: String },
    /// Any ChatMessage::System the actor would have pushed.
    SystemNotice(String),
    LoaderProgress(crate::extensions::loader::ExtensionLoaderEvent),
    ExtensionNotification {
        extension_id: String,
        method: String,
        params: serde_json::Value,
    },
    SettingChanged(SettingApplied),
    QueryResult { id: u64, value: serde_json::Value },
    /// Only to the attaching client.
    Attached {
        client: ClientId,
        snapshot: AttachSnapshot,
    },
    ClientJoined { client: ClientId, kind: ClientKind },
    ClientLeft { client: ClientId },
    Ended { reason: EndReason },
    /// Cancel landed. TUI: drop_empty_thinking, push Error(abort_msg),
    /// subagents.clear(), streaming=false. `context_saved` (name kept for
    /// protocol v3): the interrupted turn's partial work is kept in history.
    Aborted { context_saved: bool },
    /// `/clear`. TUI: transcript.clear, counters=0, "new session started".
    Cleared { session_id: String },
    /// (B2) `disclosure` = preview_compaction_disclosure().render_line().
    CompactionStarted { source: String, disclosure: String },
    CompactionApplied {
        previous_session_id: String,
        session_id: String,
        chains_advanced: Vec<String>,
        queued_restored: Option<String>,
        msg_count: usize,
    },
    /// "compaction failed: {e}" vs "compaction task panicked: {e}".
    CompactionFailed { message: String, panicked: bool },
    CompactionCancelled,
    /// `runtime.subagent_registry().display_rows()` — at Done/Error and at
    /// 1 Hz while any row is non-terminal.
    SubagentRows(Vec<crate::runtime::subagent::SubagentDisplayRow>),
    /// `/resume` reply (`Resume{id}`).
    Resumed {
        id: u64,
        old_id: String,
        new_id: String,
        via: Option<String>,
        clamp_notice: Option<String>,
    },
    /// (B1) sent to the previous owner on takeover, and to everyone on any
    /// owner change.
    InputOwnerChanged {
        from: Option<ClientId>,
        to: Option<ClientId>,
        reason: OwnerChangeReason,
    },
    /// (B1) a non-owner sent an input command. Only the sender renders it.
    Refused { client: ClientId, command: String, reason: String },
    /// (B3) targeted like `Attached`: the attach could not be honoured.
    AttachRefused { message: String },
    /// (B3) lifecycle transitions for mirrors and `sessions` listings.
    Lifecycle(SessionLifecycle),
    /// (C3) daemon is about to exec itself; clients reconnect.
    Reloading { generation: u64, retry_after_ms: u64 },
    /// (E-P0) Driver armed on this session.
    DriverArmed {
        plugin_id: String,
        run_id: String,
        models: Vec<crate::extensions::session_driver::Selection>,
        selection: crate::extensions::session_driver::Selection,
        /// Remaining ms, not absolute Instant.
        deadline_ms: Option<u64>,
        notice: String,
    },
    /// (E-P0) Driver revoked.
    DriverRevoked {
        reason: String,
        undelivered_steering: Vec<String>,
    },
    /// (E-P0) One driver turn completed.
    DriverTurnOutcome {
        outcome: crate::extensions::session_driver::Outcome,
        selection: crate::extensions::session_driver::Selection,
        feedback: Option<String>,
    },
    /// (E-P7, §S3) A spend ceiling was breached: the turn was cancelled and any
    /// armed driver revoked. `scope` is "session" (config cap) or "run" (the
    /// driver grant's per-run cap). Additive v3 driver event — old clients skip
    /// it via `#[serde(other)]`.
    CostCapReached {
        scope: String,
        cost: f64,
        cap: f64,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OwnerChangeReason {
    Attach,
    Takeover,
    OwnerDetached,
    Reload,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TurnTrigger {
    User,
    QueuedAuto,
    EventAuto,
    PluginCommand,
    Compaction,
    /// (E-P0) Turn initiated by the session driver.
    DriverAuto,
}

/// Per-session, gapless `seq` assigned at the single emit site
/// (`SessionActor::emit`); `ts` from the host clock.
#[derive(Debug, Clone)]
pub struct Envelope {
    pub session_id: SessionId,
    pub seq: u64,
    pub ts: chrono::DateTime<chrono::Utc>,
    pub event: SessionEventWire,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConversationTokens {
    pub input: u64,
    pub output: u64,
    pub cache_read: u64,
    pub cache_creation: u64,
}

/// Memo of `wire::messages_hash(api_messages)` shared by every clone of one
/// snapshot: the daemon converts a `Conversation` to its wire digest once
/// per socket client, and hashing serialises the whole history — now once
/// per event, not once per client. Keyed on the history's length and last
/// message identity (histories only grow), so a snapshot whose messages are
/// replaced afterwards recomputes instead of reusing a stale hash.
#[derive(Clone, Default)]
pub struct MessagesHashMemo(pub(crate) std::sync::Arc<std::sync::Mutex<Option<HashedHistory>>>);

/// `(len, last message, hash)` of the history a memo was computed for.
type HashedHistory = (usize, Option<crate::SharedMessage>, u64);

impl MessagesHashMemo {
    pub fn hash(&self, messages: &[crate::SharedMessage]) -> u64 {
        let mut memo = self
            .0
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some((len, last, hash)) = memo.as_ref() {
            let same_last = match (last, messages.last()) {
                (Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b),
                (None, None) => true,
                _ => false,
            };
            if *len == messages.len() && same_last {
                return *hash;
            }
        }
        let hash = super::wire::messages_hash(messages);
        *memo = Some((messages.len(), messages.last().cloned(), hash));
        hash
    }
}

impl std::fmt::Debug for MessagesHashMemo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("MessagesHashMemo")
    }
}

/// Serializable mirror of `ConversationState` (+ the actor's auto-turn
/// counter). Clients MUST replace, never merge, on `Conversation(_)`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ConversationSnapshot {
    /// The TUI's `App.session` mirror (never `api_messages`).
    #[serde(default)]
    pub header: SessionHeader,
    pub api_messages: Vec<crate::SharedMessage>,
    /// `api_messages.len()` on the daemon — always filled by the actor;
    /// `api_messages` itself may be empty for `HistoryMode::Digest` clients.
    #[serde(default)]
    pub messages_len: usize,
    pub tokens: ConversationTokens,
    pub cost: f64,
    /// Legacy (protocol v3 shape kept): always `None` — an interrupted turn
    /// is recorded in `api_messages` (`engine::interrupt`), never as a recap.
    pub abort_context: Option<String>,
    pub queued_message: Option<String>,
    pub pending_events_len: usize,
    pub consecutive_auto_turns: u32,
    /// Never serialised; see `MessagesHashMemo`.
    #[serde(skip)]
    pub messages_hash_memo: MessagesHashMemo,
}

/// `Session` minus `api_messages` and accounting: what a client mirrors.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionHeader {
    pub id: String,
    pub title: String,
    pub name: Option<String>,
    pub model: String,
    pub thinking_level: String,
    pub system_prompt: Option<String>,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
    pub parent_session: Option<String>,
}

impl From<&crate::Session> for SessionHeader {
    fn from(s: &crate::Session) -> Self {
        Self {
            id: s.id.clone(),
            title: s.title.clone(),
            name: s.name.clone(),
            model: s.model.clone(),
            thinking_level: s.thinking_level.clone(),
            system_prompt: s.system_prompt.clone(),
            created_at: s.created_at,
            updated_at: s.updated_at,
            parent_session: s.parent_session.clone(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct AttachSnapshot {
    pub meta: SessionMeta,
    pub view: RuntimeView,
    pub conversation: ConversationSnapshot,
    pub streaming: bool,
    /// Current-turn events since TurnStarted (bounded ring) so a mid-turn
    /// attach can rebuild partial text/tool cards.
    pub replay: Vec<Envelope>,
    pub pending_prompts: Vec<PromptRequest>,
    pub clients: Vec<(ClientId, ClientKind)>,
    /// Who owns input right now (B1) — so a joiner knows immediately
    /// whether its keystrokes will be honoured.
    pub input_owner: Option<ClientId>,
    /// Daemon-projected display tail — `Some` iff the client attached with
    /// `HistoryMode::Digest` (`conversation.api_messages` is then empty).
    pub display_tail: Option<crate::session::display::DisplayTail>,
}

impl AttachSnapshot {
    /// For the client this snapshot was made for (`me`): who owns input, if
    /// someone else does — "input is owned by client #1 (tui); attach with
    /// --takeover to steal it". Rendered by each client from its OWN
    /// snapshot; the actor used to broadcast it as a `SystemNotice`, which
    /// every attached client (the owner included) and later attach replays
    /// showed.
    pub fn input_owned_elsewhere(&self, me: ClientId) -> Option<String> {
        let owner = self.input_owner.filter(|o| *o != me)?;
        let kind = self
            .clients
            .iter()
            .find(|(c, _)| *c == owner)
            .map(|(_, k)| format!("{k:?}").to_lowercase())
            .unwrap_or_else(|| "?".into());
        Some(format!(
            "input is owned by client #{} ({kind}); attach with --takeover to steal it",
            owner.0
        ))
    }
}

/// `ReasoningLevel` has no serde impls in agent-core; go through its
/// canonical string form.
pub mod reasoning_level_serde {
    use agent_core::reasoning::ReasoningLevel;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    pub fn serialize<S: Serializer>(level: &ReasoningLevel, s: S) -> Result<S::Ok, S::Error> {
        level.as_str().serialize(s)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<ReasoningLevel, D::Error> {
        let s = String::deserialize(d)?;
        ReasoningLevel::parse(&s)
            .ok_or_else(|| serde::de::Error::custom(format!("unknown reasoning level `{s}`")))
    }
}

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

    #[test]
    fn prompt_kind_from_title() {
        assert_eq!(PromptKind::from_title("Confirm tool call"), PromptKind::Confirm);
        assert_eq!(
            PromptKind::from_title("Confirm tool activation"),
            PromptKind::Confirm
        );
        assert_eq!(PromptKind::from_title("API key"), PromptKind::Secret);
    }

    #[test]
    fn session_config_default_persists() {
        let cfg: SessionConfig = serde_json::from_str("{}").unwrap();
        assert!(cfg.persist);
        assert!(cfg.cwd.is_none());
        assert_eq!(
            serde_json::to_value(SessionConfig::default()).unwrap()["persist"],
            serde_json::Value::Bool(true)
        );
    }

    #[test]
    fn session_config_env_defaults_to_none() {
        let cfg: SessionConfig = serde_json::from_str("{}").unwrap();
        assert!(cfg.env.is_none());
    }

    #[test]
    fn session_config_env_round_trips() {
        let env = vec![("FOO".into(), "bar".into()), ("PATH".into(), "/usr/bin".into())];
        let cfg = SessionConfig { env: Some(env.clone()), ..Default::default() };
        let json = serde_json::to_string(&cfg).unwrap();
        let cfg2: SessionConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(cfg2.env, Some(env));
    }

    #[test]
    fn should_strip_env_client_prefixes() {
        assert!(should_strip_env("SYNAPS_CLIENT_REEXEC"));
        assert!(should_strip_env("SYNAPS_TUI_SCROLLBACK"));
        assert!(should_strip_env("SYNAPS_DAEMON_ADOPT"));
        assert!(should_strip_env("SYNAPS_MEM_TRACE"));
        assert!(should_strip_env("SYNAPS_MEM_TRACE_FOO"));
        // Session env — not stripped
        assert!(!should_strip_env("SYNAPS_ANTHROPIC_BASE_URL"));
        assert!(!should_strip_env("HOME"));
        assert!(!should_strip_env("PATH"));
        assert!(!should_strip_env("VIRTUAL_ENV"));
    }

    #[test]
    fn should_strip_env_secrets() {
        assert!(should_strip_env("ANTHROPIC_API_KEY"));
        assert!(should_strip_env("OPENAI_API_KEY"));
        assert!(should_strip_env("my_secret_token"));
        assert!(should_strip_env("AWS_SECRET_ACCESS_KEY"));
        assert!(should_strip_env("DB_PASSWORD"));
        assert!(should_strip_env("GCP_CREDENTIALS"));
        // Case insensitive
        assert!(should_strip_env("My_Api_Key"));
        // Not a secret
        assert!(!should_strip_env("MY_VALUE"));
        assert!(!should_strip_env("TOKENBUCKET_SIZE"));
        // suffix-anchored: the secret name must END the key
        assert!(!should_strip_env("API_TOKEN_TTL_SECS"));
        assert!(!should_strip_env("KEYBOARD_LAYOUT"));
        assert!(!should_strip_env("SSH_KEY_PATH"));
        assert!(should_strip_env("GH_TOKEN"));
        assert!(should_strip_env("SSH_KEY"));
        assert!(should_strip_env("SECRET_KEY_BASE"));
        assert!(should_strip_env("MY_PASSWD"));
    }

    #[test]
    fn strip_client_env_drops_credential_values_whatever_the_key() {
        let vars = vec![
            ("HOME".to_string(), "/home/u".to_string()),
            (
                "DATABASE_URL".to_string(),
                "postgres://app:hunter2@db/prod".to_string(),
            ),
            (
                "HTTPS_PROXY".to_string(),
                "http://user:pass@proxy:3128".to_string(),
            ),
            (
                "SENTRY_DSN".to_string(),
                "https://abc123@o1.ingest.sentry.io/42".to_string(),
            ),
            ("GITHUB_PAT".to_string(), "ghp_x".to_string()),
            (
                "API_BASE_URL".to_string(),
                "https://api.example.com/v1".to_string(),
            ),
        ];
        let (env, stripped) = strip_client_env(vars);
        let kept: Vec<&str> = env.iter().map(|(k, _)| k.as_str()).collect();
        assert_eq!(
            kept,
            vec!["API_BASE_URL", "HOME"],
            "only non-secrets survive"
        );
        assert!(env.iter().all(|(_, v)| !v.contains("hunter2")
            && !v.contains("user:pass")
            && !v.contains("abc123")));
        assert_eq!(
            stripped,
            vec!["DATABASE_URL", "GITHUB_PAT", "HTTPS_PROXY", "SENTRY_DSN"],
            "stripped names are recorded"
        );
    }

    #[test]
    fn capture_client_env_is_sorted_and_stripped() {
        // We can't fully control the process env in a unit test, but we can
        // verify the output is sorted and that known strip-list vars are absent.
        let (env, stripped) = capture_client_env();
        // Every stripped name is a secret by our own rule, and none of them
        // survived into the kept env.
        for name in &stripped {
            let by_value = std::env::var(name)
                .map(|v| agent_core::core::config::is_secret_env_value(&v))
                .unwrap_or(false);
            assert!(
                is_secret_key(name) || by_value,
                "stripped non-secret: {name}"
            );
            assert!(
                env.iter().all(|(k, _)| k != name),
                "stripped name leaked: {name}"
            );
        }
        // Sorted
        for w in env.windows(2) {
            assert!(w[0].0 <= w[1].0, "not sorted: {:?} > {:?}", w[0].0, w[1].0);
        }
        // No secrets or client-only vars
        for (k, v) in &env {
            assert!(!should_strip_env(k), "should have been stripped: {k}");
            assert!(
                !agent_core::core::config::is_secret_env_value(v),
                "credential value kept: {k}"
            );
        }
    }

    #[test]
    fn command_json_round_trip() {
        let cmd = SessionCommand::Set {
            id: 7,
            setting: SessionSetting::ReasoningLevel {
                level: agent_core::reasoning::ReasoningLevel::Ultra,
            },
        };
        let json = serde_json::to_string(&cmd).unwrap();
        assert_eq!(
            json,
            r#"{"cmd":"set","id":7,"setting":{"setting":"reasoning_level","level":"ultra"}}"#
        );
        let back: SessionCommand = serde_json::from_str(&json).unwrap();
        assert!(matches!(
            back,
            SessionCommand::Set {
                id: 7,
                setting: SessionSetting::ReasoningLevel {
                    level: agent_core::reasoning::ReasoningLevel::Ultra
                }
            }
        ));

        let submit: SessionCommand = serde_json::from_str(r#"{"cmd":"submit","text":"hi"}"#).unwrap();
        match submit {
            SessionCommand::Submit { text, attachments } => {
                assert_eq!(text, "hi");
                assert!(attachments.is_empty());
            }
            other => panic!("unexpected {other:?}"),
        }

        // Submit with content blocks round-trips.
        let blocks = vec![
            serde_json::json!({"type":"image","source":{"type":"base64","media_type":"image/png","data":"iVBOR"}}),
            serde_json::json!({"type":"text","text":"hello"}),
        ];
        let submit_with = SessionCommand::Submit {
            text: "describe".into(),
            attachments: blocks.clone(),
        };
        let json = serde_json::to_string(&submit_with).unwrap();
        let back: SessionCommand = serde_json::from_str(&json).unwrap();
        match back {
            SessionCommand::Submit { text, attachments } => {
                assert_eq!(text, "describe");
                assert_eq!(attachments.len(), 2);
                assert_eq!(attachments[0]["type"], "image");
                assert_eq!(attachments[1]["type"], "text");
            }
            other => panic!("unexpected {other:?}"),
        }
    }

    #[test]
    fn new_commands_round_trip() {
        let cmds = vec![
            SessionCommand::SubmitPrepared {
                messages: vec![std::sync::Arc::new(serde_json::json!({"role":"user","content":"x"}))],
                user_text: Some("t".into()),
            },
            SessionCommand::PluginCommand { id: 1, plugin: "p".into(), name: "n".into(), arg: "a".into() },
            SessionCommand::Resume { id: 2, query: "q".into() },
            SessionCommand::Checkpoint { reason: CheckpointReason::Reload },
            SessionCommand::KeepWarm { on: true },
            SessionCommand::Query { id: 3, query: SessionQuery::ContextReport },
            SessionCommand::DriverStart { plugin: "p".into(), command: "auto".into(), arg: "start -- hi".into() },
        ];
        for cmd in cmds {
            let json = serde_json::to_string(&cmd).unwrap();
            let back: SessionCommand = serde_json::from_str(&json).unwrap();
            assert_eq!(serde_json::to_string(&back).unwrap(), json);
        }
        let cp: SessionCommand = serde_json::from_str(r#"{"cmd":"checkpoint","reason":"host_request"}"#).unwrap();
        assert!(matches!(cp, SessionCommand::Checkpoint { reason: CheckpointReason::HostRequest }));
    }

    #[test]
    fn command_debug_redacts_bodies_without_lengths() {
        let secret = "hunter2-very-secret";
        let cmds = vec![
            SessionCommand::Submit { text: secret.into(), attachments: vec![] },
            SessionCommand::Steer { text: secret.into() },
            SessionCommand::SubmitPrepared {
                messages: vec![std::sync::Arc::new(serde_json::json!({"content": secret}))],
                user_text: Some(secret.into()),
            },
            SessionCommand::Answer { prompt_id: 1, value: Some(secret.into()) },
            SessionCommand::Resume { id: 1, query: secret.into() },
            SessionCommand::DriverStart { plugin: "p".into(), command: "auto".into(), arg: secret.into() },
        ];
        for cmd in cmds {
            let d = format!("{cmd:?}");
            assert!(!d.contains(secret), "{d}");
            assert!(d.contains("<redacted>"), "{d}");
            assert!(!d.contains("chars"), "{d}");
            assert!(!d.contains(&secret.len().to_string()), "{d}");
        }
        let d = format!("{:?}", SessionCommand::Set { id: 4, setting: SessionSetting::ReloadPrompt });
        assert_eq!(d, "Set { id: 4, setting: ReloadPrompt }");

        // Submit debug shows count+kinds, never base64.
        let b64_secret = "aHVudGVyMi12ZXJ5LXNlY3JldA==";
        let cmd = SessionCommand::Submit {
            text: "x".into(),
            attachments: vec![
                serde_json::json!({"type":"image","source":{"type":"base64","media_type":"image/png","data":b64_secret}}),
                serde_json::json!({"type":"document","title":"x.pdf","source":{"type":"base64","media_type":"application/pdf","data":"JVBER"}}),
            ],
        };
        let d = format!("{cmd:?}");
        assert!(d.contains(r#"2:["image", "document"]"#), "{d}");
        assert!(!d.contains(b64_secret), "base64 leaked: {d}");
    }

    #[test]
    fn session_config_new_fields_default() {
        let cfg: SessionConfig = serde_json::from_str("{}").unwrap();
        assert_eq!(cfg.compaction_policy, CompactionPolicyWire::InPlace);
        assert!(cfg.await_extensions);
        assert!(!cfg.keep_warm);
        let cfg: SessionConfig =
            serde_json::from_str(r#"{"compaction_policy":"linked_successor","await_extensions":false}"#).unwrap();
        assert_eq!(cfg.compaction_policy, CompactionPolicyWire::LinkedSuccessor);
        assert!(!cfg.await_extensions);
    }

    #[test]
    fn session_lifecycle_u8_round_trip() {
        for l in [SessionLifecycle::Live, SessionLifecycle::Parking, SessionLifecycle::Parked, SessionLifecycle::Ending] {
            assert_eq!(SessionLifecycle::from_u8(l as u8), l);
        }
        assert_eq!(serde_json::to_string(&SessionLifecycle::Parked).unwrap(), r#""parked""#);
    }

    #[test]
    fn host_event_is_never_serialised() {
        let cmd = SessionCommand::HostEvent(HostEvent::LoaderProgress(
            crate::extensions::loader::ExtensionLoaderEvent::Started,
        ));
        assert!(serde_json::to_string(&cmd).is_err());
    }
}

/// `Option<Option<String>>` on the wire without collapsing `Some(None)`:
/// absent → `None`; `{"latest": true}` → `Some(None)`; `"id"` → `Some(Some(id))`.
/// Older daemons/clients that sent a bare string or `null` still decode.
mod double_option {
    use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

    #[derive(Serialize, Deserialize)]
    #[serde(untagged)]
    enum Wire {
        Latest { latest: bool },
        Id(String),
    }

    pub fn serialize<S: Serializer>(v: &Option<Option<String>>, s: S) -> Result<S::Ok, S::Error> {
        match v {
            None => s.serialize_none(),
            Some(None) => Wire::Latest { latest: true }.serialize(s),
            Some(Some(id)) => Wire::Id(id.clone()).serialize(s),
        }
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Option<String>>, D::Error> {
        match Option::<Wire>::deserialize(d)? {
            None => Ok(None),
            Some(Wire::Latest { latest: true }) => Ok(Some(None)),
            Some(Wire::Latest { latest: false }) => Err(de::Error::custom("continue_session: latest must be true")),
            Some(Wire::Id(id)) => Ok(Some(Some(id))),
        }
    }

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

        fn rt(v: Option<Option<String>>) -> Option<Option<String>> {
            let cfg = SessionConfig { continue_session: v, ..Default::default() };
            let j = serde_json::to_string(&cfg).unwrap();
            serde_json::from_str::<SessionConfig>(&j).unwrap().continue_session
        }

        #[test]
        fn continue_session_round_trips_all_three_states() {
            assert_eq!(rt(None), None);
            assert_eq!(rt(Some(None)), Some(None), "bare --continue must survive the wire");
            assert_eq!(rt(Some(Some("abc".into()))), Some(Some("abc".into())));
        }

        #[test]
        fn continue_session_accepts_legacy_encodings() {
            let old_null: SessionConfig = serde_json::from_str(r#"{"continue_session":null}"#).unwrap();
            assert_eq!(old_null.continue_session, None);
            let old_id: SessionConfig = serde_json::from_str(r#"{"continue_session":"xyz"}"#).unwrap();
            assert_eq!(old_id.continue_session, Some(Some("xyz".into())));
            let absent: SessionConfig = serde_json::from_str(r#"{}"#).unwrap();
            assert_eq!(absent.continue_session, None);
        }
    }
}