Skip to main content

agent_engine/session/
types.rs

1//! Identity, configuration, commands, events and the envelope — the entire
2//! client↔session contract (PLAN-phase2 §2.1–§2.4). Everything a client can
3//! send is serde-able from day one; `SessionEventWire::Stream` deliberately
4//! is not (it carries the un-serialised `StreamEvent` in-process).
5
6use std::path::PathBuf;
7
8use serde::{Deserialize, Serialize};
9
10use super::view::RuntimeView;
11
12// ── identity + configuration ──────────────────────────────────────────────────
13
14/// Conversation session id — the `Session.id` string (`{name}-{ts}-{pid}`; see
15/// events/registry.rs sanitize rules). NOT the tools::activation::SessionId
16/// (that is the per-runtime gate identity minted at Runtime::from_parts).
17#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
18#[serde(transparent)]
19pub struct SessionId(pub String);
20
21impl SessionId {
22    pub fn as_str(&self) -> &str {
23        &self.0
24    }
25}
26
27impl std::fmt::Display for SessionId {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        f.write_str(&self.0)
30    }
31}
32
33impl From<String> for SessionId {
34    fn from(s: String) -> Self {
35        Self(s)
36    }
37}
38
39impl From<&str> for SessionId {
40    fn from(s: &str) -> Self {
41        Self(s.to_string())
42    }
43}
44
45/// Ordered key-value snapshot of a client's environment.
46pub type SessionEnv = Vec<(String, String)>;
47
48/// Prefixes stripped from the client env before it enters the session.
49/// These are client-only or daemon-only knobs — never session identity.
50const ENV_STRIP_PREFIXES: &[&str] = &[
51    "SYNAPS_CLIENT_",
52    "SYNAPS_TUI_",
53    "SYNAPS_DAEMON_",
54    "SYNAPS_MEM_TRACE",
55];
56
57/// Secret patterns (case-insensitive suffix/infix) stripped at the client.
58/// Secrets never reach the daemon — the broker owns credentials.
59/// Build a [`SessionEnv`] from the current process environment, stripping
60/// client-only prefixes and secrets. Returns `(kept_env, stripped_secret_names)`.
61/// The stripped names are ONLY the secrets (not `SYNAPS_*` prefixes, those are noise).
62/// Used by thin clients before `Hello`.
63pub fn capture_client_env() -> (SessionEnv, Vec<String>) {
64    strip_client_env(std::env::vars())
65}
66
67/// The pure part of [`capture_client_env`]: filter `vars` (unit-testable
68/// without touching the process environment).
69pub fn strip_client_env(
70    vars: impl IntoIterator<Item = (String, String)>,
71) -> (SessionEnv, Vec<String>) {
72    let mut env: SessionEnv = Vec::new();
73    let mut stripped: Vec<String> = Vec::new();
74    for (k, v) in vars {
75        // A credential VALUE is stripped whatever its key is called
76        // (`DATABASE_URL=postgres://u:p@h`): the name denylist alone let it
77        // through to the daemon and the session files.
78        let secret_value = agent_core::core::config::is_secret_env_value(&v);
79        if should_strip_env(&k) || secret_value {
80            // Only record secret names, not SYNAPS_* prefix noise.
81            if is_secret_key(&k) || secret_value {
82                stripped.push(k);
83            }
84        } else {
85            env.push((k, v));
86        }
87    }
88    env.sort_by(|(a, _), (b, _)| a.cmp(b));
89    stripped.sort();
90    (env, stripped)
91}
92
93/// Whether a key should be stripped from the client env snapshot.
94pub fn should_strip_env(key: &str) -> bool {
95    let upper = key.to_ascii_uppercase();
96    for prefix in ENV_STRIP_PREFIXES {
97        if upper.starts_with(prefix) {
98            return true;
99        }
100    }
101    is_secret_key(&upper)
102}
103
104/// Whether a key matches the secret denylist (case-insensitive).
105/// Delegates to the canonical implementation in `agent_core::core::config`.
106pub fn is_secret_key(key: &str) -> bool {
107    agent_core::core::config::is_secret_key(key)
108}
109
110/// Everything `EngineHost::create_session` needs. Serializable: it is the
111/// payload of the wire `Attach::Create`. Mirrors `EngineOpts` minus the
112/// host-level fields (profile, no_extensions), plus the per-session facts a
113/// daemon cannot inherit from its own process (cwd, env overlay).
114#[derive(Clone, Debug, Serialize, Deserialize)]
115pub struct SessionConfig {
116    /// `EngineOpts.continue_session`. `Some(None)` = bare `--continue` (most
117    /// recent journal). Plain serde encodes `Some(None)` as `null` and decodes
118    /// that as `None`, so the daemon could never receive a bare `--continue`
119    /// (soak F21) — `double_option` keeps the two levels apart on the wire.
120    #[serde(default, with = "double_option", skip_serializing_if = "Option::is_none")]
121    pub continue_session: Option<Option<String>>,
122    /// `EngineOpts.system`.
123    #[serde(default)]
124    pub system: Option<String>,
125    /// `EngineOpts.prompt_manifest`.
126    #[serde(default)]
127    pub prompt_manifest: Option<PathBuf>,
128    /// Per-session working directory. `None` = process cwd (in-process hosts
129    /// pass `None` today → byte-identical). The daemon ALWAYS fills it from
130    /// `Hello.cwd`.
131    #[serde(default)]
132    pub cwd: Option<PathBuf>,
133    /// Per-session environment snapshot. `None` = inherit process env
134    /// (in-process hosts). The daemon fills it from `Hello.env` on
135    /// `Attach::Create` only; attaching to an existing session does not
136    /// change the creator's env.
137    #[serde(default)]
138    pub env: Option<SessionEnv>,
139    /// Names of environment variables stripped as secrets at the client
140    /// (e.g. `GH_TOKEN`, `AWS_SECRET_ACCESS_KEY`). NOT the `SYNAPS_*`
141    /// prefixes (those are noise). Used for loud notices when a tool fails
142    /// referencing a stripped secret. Persisted in the journal (names only,
143    /// never values).
144    #[serde(default, skip_serializing_if = "Vec::is_empty")]
145    pub env_stripped: Vec<String>,
146    /// `Confirm` hook results auto-approved (server `--auto-approve-confirms`).
147    /// Interactive hosts: false.
148    #[serde(default)]
149    pub auto_approve_confirms: bool,
150    /// CLI `--model` override applied after session resolution.
151    #[serde(default)]
152    pub model_override: Option<String>,
153    /// Save policy: only "save at all" — the TUI/chat/rpc always save; tests
154    /// may disable. Default `true`.
155    #[serde(default = "default_true")]
156    pub persist: bool,
157    /// Headless-chat policy: after every turn, save + `assess_context` and
158    /// auto-compact when the engine budget says so (chat.rs post-turn block).
159    /// The TUI does its own compaction; default `false`.
160    #[serde(default)]
161    pub auto_compact: bool,
162    /// Compaction transition policy: `InPlace` (default; chat, today's
163    /// actor) or `LinkedSuccessor` (the TUI's successor-session chain).
164    #[serde(default)]
165    pub compaction_policy: CompactionPolicyWire,
166    /// Block `create` on process-level extension discovery before emitting
167    /// `on_session_start` (chat/daemon). The TUI passes `false`: the actor
168    /// emits it from a spawned waiter so boot never blocks on discovery.
169    #[serde(default = "default_true")]
170    pub await_extensions: bool,
171    /// Never `Park` this session (`--keep-warm`). Default `false`.
172    #[serde(default)]
173    pub keep_warm: bool,
174    /// Who may drive this session ([`ClientInput`]); `None` = config
175    /// `client_input`. An older daemon ignores it (and enforces the owner).
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub client_input: Option<ClientInput>,
178    /// `--name`: name the session at create (same rules as `/cmd saveas`;
179    /// must be unique among saved sessions). Applied before the registry
180    /// entry is written so `synaps send --session <name>` resolves at once.
181    #[serde(default)]
182    pub name: Option<String>,
183    /// (E-P7, §S3) Hard per-session spend ceiling in USD. `None` = unbounded.
184    /// Checked after every `Usage` stream event; a breach cancels the turn,
185    /// revokes any armed driver, and emits `CostCapReached`. This is the
186    /// host-owned circuit breaker for an actor-resident autonomous driver.
187    #[serde(default, skip_serializing_if = "Option::is_none")]
188    pub max_session_cost: Option<f64>,
189    /// The session's explicit `/memory` choice, recorded by the actor so a
190    /// rebuilt runtime (unpark, daemon reload) restores it instead of
191    /// re-applying the operator's `memory.default_mode`. `None` = no choice
192    /// yet: the default applies. Host-recorded: the daemon drops a value a
193    /// client sends at create.
194    #[serde(
195        default,
196        skip_serializing_if = "Option::is_none",
197        deserialize_with = "SessionMemoryMode::deserialize_lenient"
198    )]
199    pub memory_mode: Option<SessionMemoryMode>,
200    /// Set by a daemon reload for a session it restores Parked (never on
201    /// the wire): with `await_extensions=false`, `on_session_start` waits
202    /// until the session is unparked instead of running right after create.
203    #[serde(skip)]
204    pub restore_parked: bool,
205}
206
207/// A durable `/memory` mode the user chose for a session
208/// (`SessionConfig::memory_mode`). `/memory once` is a one-shot lease, not
209/// a mode, and is not recorded.
210#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
211#[serde(rename_all = "snake_case")]
212pub enum SessionMemoryMode {
213    Off,
214    RecallEachPrompt,
215    CaptureOnly,
216    CaptureAndRecall,
217}
218
219impl SessionMemoryMode {
220    /// `SessionConfig::memory_mode` reader: a value this build does not know
221    /// (a newer image's mode) reads as `Off` — the consent-safe direction —
222    /// rather than an error that would fail the whole reload state and
223    /// rehydrate no session at all. Null (or a missing field) is no choice.
224    fn deserialize_lenient<'de, D>(d: D) -> Result<Option<Self>, D::Error>
225    where
226        D: serde::Deserializer<'de>,
227    {
228        let v = serde_json::Value::deserialize(d)?;
229        if v.is_null() {
230            return Ok(None);
231        }
232        Ok(Some(serde_json::from_value(v.clone()).unwrap_or_else(|_| {
233            tracing::warn!(mode = %v, "unknown session memory mode; treating as off");
234            Self::Off
235        })))
236    }
237
238    /// The mode `/memory <arg>` sets, if it sets one.
239    pub fn from_command_arg(arg: &str) -> Option<Self> {
240        match arg.trim() {
241            "off" => Some(Self::Off),
242            "recall" => Some(Self::RecallEachPrompt),
243            "capture" => Some(Self::CaptureOnly),
244            "on" => Some(Self::CaptureAndRecall),
245            _ => None,
246        }
247    }
248
249    /// The lease mode to grant; `None` for `Off`.
250    pub fn lease_mode(self) -> Option<crate::runtime::memory_context::MemoryContextMode> {
251        use crate::runtime::memory_context::MemoryContextMode as M;
252        match self {
253            Self::Off => None,
254            Self::RecallEachPrompt => Some(M::RecallEachPrompt),
255            Self::CaptureOnly => Some(M::CaptureOnly),
256            Self::CaptureAndRecall => Some(M::CaptureAndRecall),
257        }
258    }
259}
260
261fn default_true() -> bool {
262    true
263}
264
265/// Serializable mirror of `runtime::compaction::CompactionPolicy`.
266#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "snake_case")]
268pub enum CompactionPolicyWire {
269    #[default]
270    InPlace,
271    LinkedSuccessor,
272}
273
274impl From<CompactionPolicyWire> for crate::runtime::compaction::CompactionPolicy {
275    fn from(p: CompactionPolicyWire) -> Self {
276        match p {
277            CompactionPolicyWire::InPlace => Self::InPlace,
278            CompactionPolicyWire::LinkedSuccessor => Self::LinkedSuccessor,
279        }
280    }
281}
282
283impl Default for SessionConfig {
284    fn default() -> Self {
285        Self {
286            continue_session: None,
287            system: None,
288            prompt_manifest: None,
289            cwd: None,
290            env: None,
291            env_stripped: Vec::new(),
292            auto_approve_confirms: false,
293            model_override: None,
294            persist: true,
295            auto_compact: false,
296            compaction_policy: CompactionPolicyWire::InPlace,
297            await_extensions: true,
298            keep_warm: false,
299            client_input: None,
300            name: None,
301            max_session_cost: None,
302            memory_mode: None,
303            restore_parked: false,
304        }
305    }
306}
307
308/// Serializable copy of `engine::setup::ContinueInfo`.
309#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
310pub struct ContinueInfoWire {
311    pub session_id: String,
312    /// "chain", "name", "compacted", or None.
313    pub resolved_via: Option<String>,
314    pub query: String,
315    /// F24: notice when the session was followed through a compaction chain.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub compaction_notice: Option<String>,
318}
319
320impl From<&crate::engine::setup::ContinueInfo> for ContinueInfoWire {
321    fn from(c: &crate::engine::setup::ContinueInfo) -> Self {
322        Self {
323            session_id: c.session_id.clone(),
324            resolved_via: c.resolved_via.clone(),
325            query: c.query.clone(),
326            compaction_notice: c.compaction_notice.clone(),
327        }
328    }
329}
330
331#[derive(Clone, Debug, Serialize, Deserialize)]
332pub struct SessionMeta {
333    pub id: SessionId,
334    pub name: Option<String>,
335    pub model: String,
336    pub cwd: Option<PathBuf>,
337    pub created_at: chrono::DateTime<chrono::Utc>,
338    pub continued: bool,
339    pub continue_info: Option<ContinueInfoWire>,
340    /// Daemon pid (in-process: this process).
341    pub host_pid: u32,
342    // ── filled at list time from the handle's cells (meta itself is frozen) ──
343    #[serde(default)]
344    pub lifecycle: SessionLifecycle,
345    #[serde(default)]
346    pub clients: usize,
347    #[serde(default)]
348    pub input_owner: Option<ClientId>,
349    #[serde(default)]
350    pub awaiting_input: usize,
351    /// Every attached client, named. Empty from an older daemon.
352    #[serde(default, skip_serializing_if = "Vec::is_empty")]
353    pub roster: Vec<ClientInfo>,
354    /// Who may drive ([`ClientInput`]); `None` from an older daemon (which
355    /// enforces the owner: `Exclusive`). With `Shared`, `input_owner` is the
356    /// active client, not the only one that may type.
357    #[serde(default, skip_serializing_if = "Option::is_none")]
358    pub client_input: Option<ClientInput>,
359    /// `conv.session.id` — differs from `id` after a LinkedSuccessor compaction.
360    #[serde(default)]
361    pub journal_id: String,
362    /// Set when the session's journal is locked by another process (F23):
363    /// `"pid N (kind)"`. Shown in `daemon sessions`; cleared on unpark.
364    #[serde(default, skip_serializing_if = "Option::is_none")]
365    pub locked_by: Option<String>,
366    /// Pinned (`KeepWarm{on}`, `/pin`): never parked, never idle-ended, and
367    /// the daemon does not idle-exit while it is set. An older daemon omits
368    /// it (→ false); an older client ignores it.
369    #[serde(default)]
370    pub pinned: bool,
371    // ── state for the `/sessions` modal, published by the actor. An older
372    //    daemon omits them (→ defaults); an older client ignores them. ──
373    /// A turn or a compaction is running.
374    #[serde(default)]
375    pub busy: bool,
376    /// When the session entered its current state (turn/compaction start,
377    /// idle start, park time).
378    #[serde(default)]
379    pub state_since: Option<chrono::DateTime<chrono::Utc>>,
380    /// When the idle park fires (Live, zero clients, grace armed). `None`
381    /// when not armed — a worker re-check is not a park due.
382    #[serde(default)]
383    pub park_due: Option<chrono::DateTime<chrono::Utc>>,
384    /// When a Parked session is evicted; `None` if not parked or never.
385    #[serde(default)]
386    pub evict_due: Option<chrono::DateTime<chrono::Utc>>,
387    /// The live conversation's title, as of the last publish.
388    #[serde(default)]
389    pub title: Option<String>,
390    /// Session cost in USD, as of the last publish.
391    #[serde(default)]
392    pub cost_usd: f64,
393    /// API message count, as of the last publish.
394    #[serde(default)]
395    pub messages: usize,
396}
397
398/// Where a session is in its park/unpark life (`SessionHandle::lifecycle`).
399#[repr(u8)]
400#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
401#[serde(rename_all = "snake_case")]
402pub enum SessionLifecycle {
403    #[default]
404    Live = 0,
405    Parking = 1,
406    Parked = 2,
407    Ending = 3,
408}
409
410impl SessionLifecycle {
411    pub fn from_u8(v: u8) -> Self {
412        match v {
413            1 => Self::Parking,
414            2 => Self::Parked,
415            3 => Self::Ending,
416            _ => Self::Live,
417        }
418    }
419}
420
421pub use crate::core::config::ClientInput;
422
423/// Minted by the actor per Attach.
424#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
425#[serde(transparent)]
426pub struct ClientId(pub u64);
427
428#[derive(Clone, Debug, Serialize, Deserialize)]
429pub struct ClientMeta {
430    pub kind: ClientKind,
431    /// `$TERM`, informational.
432    pub terminal: Option<String>,
433    /// Client-generated uuid; reattach dedup (day 3).
434    pub instance: String,
435    /// How much history this client wants mirrored (phase 4).
436    #[serde(default)]
437    pub history: HistoryMode,
438    /// Display items in `Attached.display_tail` / `DisplayTail` queries (phase 4).
439    #[serde(default = "default_tail_items")]
440    pub tail_items: usize,
441    /// Additive stream events this client can decode. Absent from older
442    /// clients (all `false`), so a newer daemon never sends them one; an
443    /// older daemon ignores the unknown field.
444    #[serde(default, skip_serializing_if = "ClientCapabilities::is_none")]
445    pub capabilities: ClientCapabilities,
446    /// What this client asks to be called (`--as`, `SYNAPS_CLIENT_NAME`):
447    /// a label, not a login — every client is the daemon's own user. The
448    /// session resolves it ([`resolve_client_name`]) and reports the result
449    /// in `ClientJoined`/`roster`. Absent = the kind's name. An older
450    /// daemon ignores it.
451    #[serde(default, skip_serializing_if = "Option::is_none")]
452    pub name: Option<String>,
453}
454
455/// Longest client name ([`validate_client_name`]).
456pub const CLIENT_NAME_MAX: usize = 32;
457
458/// A client name is 1–32 ASCII letters, digits, `-` or `_`, starting with
459/// a letter or digit. The client checks before connecting; the daemon
460/// checks again and refuses the handshake.
461pub fn validate_client_name(name: &str) -> Result<(), String> {
462    let ok_first = name.chars().next().is_some_and(|c| c.is_ascii_alphanumeric());
463    let ok_rest = name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
464    if name.is_empty() || name.len() > CLIENT_NAME_MAX || !ok_first || !ok_rest {
465        return Err(format!(
466            "invalid client name {name:?}: use 1-{CLIENT_NAME_MAX} letters, digits, '-' or '_', starting with a letter or digit"
467        ));
468    }
469    Ok(())
470}
471
472/// `SYNAPS_CLIENT_NAME`, trimmed; `None` when unset or empty. Not
473/// validated here: the caller reports a bad one.
474pub fn client_name_from_env() -> Option<String> {
475    std::env::var("SYNAPS_CLIENT_NAME")
476        .ok()
477        .map(|v| v.trim().to_string())
478        .filter(|v| !v.is_empty())
479}
480
481/// The name a joining client gets in a session: its requested name, or its
482/// kind's name if it asked for none (or an invalid one), with the lowest
483/// free `-N` suffix (N ≥ 2) if another client already has it. Names
484/// compare case-insensitively.
485pub fn resolve_client_name<'a>(
486    requested: Option<&str>,
487    kind: ClientKind,
488    taken: impl IntoIterator<Item = &'a str>,
489) -> String {
490    let base = requested
491        .filter(|n| validate_client_name(n).is_ok())
492        .unwrap_or(kind.default_name());
493    let taken: std::collections::HashSet<String> = taken.into_iter().map(str::to_ascii_lowercase).collect();
494    if !taken.contains(&base.to_ascii_lowercase()) {
495        return base.to_string();
496    }
497    (2..)
498        .map(|n| format!("{base}-{n}"))
499        .find(|c| !taken.contains(&c.to_ascii_lowercase()))
500        .expect("an unbounded range always has a free suffix")
501}
502
503/// One attached client as every client sees it (`AttachSnapshot.roster`,
504/// `ClientJoined`, `/clients`, `synaps daemon sessions`).
505#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
506pub struct ClientInfo {
507    pub id: ClientId,
508    /// Resolved by the session ([`resolve_client_name`]); unique in it.
509    pub name: String,
510    pub kind: ClientKind,
511    pub mode: AttachMode,
512    /// Unix ms.
513    pub attached_at_ms: u64,
514}
515
516impl ClientInfo {
517    /// `discord (#3)`: the name for people, the id for scripts that grep.
518    pub fn label(&self) -> String {
519        format!("{} (#{})", self.name, self.id.0)
520    }
521}
522
523/// A client-side copy of the session's roster, kept current from the
524/// attach snapshot, `ClientJoined` and `ClientLeft` (each transport owns
525/// one).
526#[derive(Clone, Debug, Default, PartialEq, Eq)]
527pub struct Roster(Vec<ClientInfo>);
528
529impl Roster {
530    pub fn from_snapshot(snapshot: &AttachSnapshot) -> Self {
531        let mut r = Self(snapshot.roster.clone());
532        // An older daemon sends no roster: fall back to ids and kinds.
533        if r.0.is_empty() {
534            r.0 = snapshot
535                .clients
536                .iter()
537                .map(|(id, kind)| ClientInfo {
538                    id: *id,
539                    name: kind.default_name().to_string(),
540                    kind: *kind,
541                    mode: AttachMode::Mirror,
542                    attached_at_ms: 0,
543                })
544                .collect();
545        }
546        r
547    }
548
549    pub fn apply(&mut self, event: &SessionEventWire) {
550        match event {
551            SessionEventWire::ClientJoined { client, kind, name, mode } => {
552                self.0.retain(|c| c.id != *client);
553                self.0.push(ClientInfo {
554                    id: *client,
555                    name: if name.is_empty() { kind.default_name().to_string() } else { name.clone() },
556                    kind: *kind,
557                    mode: *mode,
558                    // The event carries no time: it just happened.
559                    attached_at_ms: chrono::Utc::now().timestamp_millis().max(0) as u64,
560                });
561                self.0.sort_by_key(|c| c.id.0);
562            }
563            SessionEventWire::ClientLeft { client } => self.0.retain(|c| c.id != *client),
564            _ => {}
565        }
566    }
567
568    pub fn clients(&self) -> &[ClientInfo] {
569        &self.0
570    }
571
572    pub fn get(&self, id: ClientId) -> Option<&ClientInfo> {
573        self.0.iter().find(|c| c.id == id)
574    }
575
576    /// `discord (#3)`, or `client #3` for an id not in the roster.
577    pub fn label(&self, id: ClientId) -> String {
578        self.get(id).map(ClientInfo::label).unwrap_or_else(|| format!("client #{}", id.0))
579    }
580}
581
582/// Opt-in stream signals (see [`ClientMeta::capabilities`]). The daemon's
583/// event enums nested under `Stream` (`WireLlmEvent`, ...) have no
584/// `#[serde(other)]`: an older client fails the whole frame on an unknown
585/// variant — and a failed frame reads as a dead socket (the TUI drops into
586/// reconnect, whose `Attached` replay would carry the same variant). So
587/// every new nested variant is sent only to a client that declares it here.
588#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
589pub struct ClientCapabilities {
590    /// `LlmEvent::ToolQueued` / `ToolStarted` (scheduler lane waits).
591    #[serde(default)]
592    pub tool_queue: bool,
593    /// Knows `client_input = shared`: `OwnerChangeReason::Input` and
594    /// `Attached.client_input`. Without it, a shared session is presented
595    /// in owner terms (`wire::legacy_shared`).
596    #[serde(default)]
597    pub owner_reason_input: bool,
598}
599
600impl ClientCapabilities {
601    /// What this build decodes.
602    pub fn current() -> Self {
603        Self { tool_queue: true, owner_reason_input: true }
604    }
605
606    fn is_none(&self) -> bool {
607        *self == Self::default()
608    }
609}
610
611/// Default for `ClientMeta.tail_items`: matches the TUI's resumed-display cap.
612pub const DEFAULT_TAIL_ITEMS: usize = 120;
613
614fn default_tail_items() -> usize {
615    DEFAULT_TAIL_ITEMS
616}
617
618/// `SYNAPS_ATTACH_TAIL_ITEMS` (client side): display items requested in
619/// `Attached.display_tail`; `DEFAULT_TAIL_ITEMS` when unset/invalid.
620pub fn tail_items_from_env() -> usize {
621    std::env::var("SYNAPS_ATTACH_TAIL_ITEMS")
622        .ok()
623        .and_then(|v| v.trim().parse::<usize>().ok())
624        .unwrap_or(DEFAULT_TAIL_ITEMS)
625}
626
627impl ClientMeta {
628    /// Fresh meta with a random instance id and no terminal.
629    pub fn new(kind: ClientKind) -> Self {
630        Self {
631            kind,
632            terminal: None,
633            instance: uuid::Uuid::new_v4().to_string(),
634            history: HistoryMode::default(),
635            tail_items: tail_items_from_env(),
636            capabilities: ClientCapabilities::current(),
637            name: None,
638        }
639    }
640
641    /// With a requested name (see [`ClientMeta::name`]).
642    pub fn named(mut self, name: Option<String>) -> Self {
643        self.name = name;
644        self
645    }
646}
647
648/// What a client wants in `Attached` / `Conversation`: the full
649/// `api_messages` mirror (`Full`, the 741b6b60 behaviour) or only the
650/// digest + a daemon-side display tail (`Digest`, phase 4).
651#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
652#[serde(rename_all = "snake_case")]
653pub enum HistoryMode {
654    #[default]
655    Full,
656    Digest,
657}
658
659impl HistoryMode {
660    /// `SYNAPS_CLIENT_HISTORY=full|digest`; `default` wins when unset or
661    /// unrecognised.
662    pub fn from_env_or(default: Self) -> Self {
663        match std::env::var("SYNAPS_CLIENT_HISTORY").ok().as_deref().map(str::trim) {
664            Some(v) if v.eq_ignore_ascii_case("full") => Self::Full,
665            Some(v) if v.eq_ignore_ascii_case("digest") => Self::Digest,
666            _ => default,
667        }
668    }
669
670    /// What `synaps --attach` asks for (phase 4 B7: `Digest`).
671    /// `SYNAPS_CLIENT_HISTORY=full` restores the 741b6b60 mirror wholesale.
672    pub fn attach_client_default() -> Self {
673        Self::Digest
674    }
675}
676
677#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
678#[serde(rename_all = "snake_case")]
679pub enum ClientKind {
680    Tui,
681    Chat,
682    Attach,
683    Rpc,
684    Server,
685    Test,
686}
687
688impl ClientKind {
689    /// The name a client of this kind gets when it asks for none.
690    pub fn default_name(self) -> &'static str {
691        match self {
692            Self::Tui => "tui",
693            Self::Chat => "chat",
694            Self::Attach => "attach",
695            Self::Rpc => "rpc",
696            Self::Server => "server",
697            Self::Test => "test",
698        }
699    }
700}
701
702/// Attach mode. Ownership (B1): `Mirror` owns input iff nobody does,
703/// `Takeover` steals it, `Observe` never owns it.
704#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
705#[serde(rename_all = "snake_case")]
706pub enum AttachMode {
707    Mirror,
708    Takeover,
709    Observe,
710}
711
712/// Actor-side client accounting (§8): `Detached` never cancels a stream.
713#[derive(Clone, Copy, Debug, PartialEq, Eq)]
714pub enum AttachState {
715    Attached(usize),
716    Detached { running: bool },
717    /// Save + PTY teardown in progress (B3).
718    Parking,
719    /// `runtime`/`conv` dropped; `background` alive; unpark on Attach/wake (B3).
720    Parked,
721}
722
723// ── prompts ───────────────────────────────────────────────────────────────────
724
725#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
726#[serde(rename_all = "snake_case")]
727pub enum PromptKind {
728    Secret,
729    Confirm,
730}
731
732/// Fixed title `resolve_before_tool_call_result` uses for Confirm prompts
733/// (runtime/mod.rs).
734pub const CONFIRM_PROMPT_TITLE: &str = "Confirm tool call";
735/// Fixed title `confirm_activation_with_host` uses for the `activate_tools`
736/// y/yes gate (tools/discovery.rs). Everything not in the confirm set is
737/// `Secret` (masked input).
738pub const CONFIRM_ACTIVATION_PROMPT_TITLE: &str = "Confirm tool activation";
739
740impl PromptKind {
741    /// Derive the kind from the prompt title (the actor classifies at receipt;
742    /// `SecretPromptHandle::prompt` classifies for the in-process TUI).
743    pub fn from_title(title: &str) -> Self {
744        if title == CONFIRM_PROMPT_TITLE || title == CONFIRM_ACTIVATION_PROMPT_TITLE {
745            Self::Confirm
746        } else {
747            Self::Secret
748        }
749    }
750}
751
752/// Who raised an extension tool-call Confirm and what "Allow all" would
753/// cover. Built host-side from the hook chain (`HookBus::emit` stamps the
754/// extension ids; an extension cannot name itself or another extension), so
755/// the dialog can show the exact scope BEFORE the user answers.
756#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
757pub struct ConfirmScope {
758    /// Extension ids whose `Confirm` this prompt resolves; "Allow all"
759    /// latches exactly these.
760    pub extensions: Vec<String>,
761    /// Tool the call targets (display only; the latch is per extension).
762    #[serde(default, skip_serializing_if = "Option::is_none")]
763    pub tool: Option<String>,
764    /// Extensions whose `Modify` rewrote the input this prompt approves
765    /// (empty = the model's own input). Lets the session record, for every
766    /// client's transcript, that an approved call ran rewritten input.
767    #[serde(default, skip_serializing_if = "Vec::is_empty")]
768    pub rewritten_by: Vec<String>,
769}
770
771impl ConfirmScope {
772    /// `a` or `a, b`.
773    pub fn extensions_label(&self) -> String {
774        self.extensions.join(", ")
775    }
776
777    /// Text of the "Allow all" button (without the key hint).
778    pub fn allow_all_label(&self) -> String {
779        format!("Allow all from {} this session", self.extensions_label())
780    }
781
782    /// The exact reach of "Allow all", shown before the user answers.
783    pub fn allow_all_scope(&self) -> String {
784        format!(
785            "Allow all: later confirms from {} (any tool) are approved without asking until \
786             /new or /confirms reset. Other extensions still ask.",
787            self.extensions_label()
788        )
789    }
790}
791
792/// Make prompt text safe to print in any client (prA I-R4-3, I-R5): drop
793/// C0/C1 control characters except `\n` (a `\t` becomes a space); the
794/// zero-width space and the LRM/RLM marks (U+200B, U+200E, U+200F); bidi
795/// embeddings/overrides/isolates (U+202A–U+202E, U+2066–U+2069) and the
796/// Arabic letter mark (U+061C); and the line/paragraph separators (U+2028,
797/// U+2029), which some terminals treat as line breaks. ZWNJ / ZWJ
798/// (U+200C, U+200D) are KEPT: emoji sequences and several scripts need
799/// them. Prevents an extension's text from moving the cursor (`\x1b[3A`,
800/// `\r`) over the host-built header, or disguising text with direction
801/// overrides.
802pub fn sanitize_prompt_text(text: &str) -> String {
803    text.chars()
804        .filter_map(|c| match c {
805            '\n' => Some('\n'),
806            '\t' => Some(' '),
807            c if c.is_control() => None,
808            '\u{200B}' | '\u{200E}' | '\u{200F}' | '\u{061C}' | '\u{2028}' | '\u{2029}' => None,
809            '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' => None,
810            c => Some(c),
811        })
812        .collect()
813}
814
815#[derive(Clone, Debug, Serialize, Deserialize)]
816pub struct PromptRequest {
817    /// Per-session monotonic; actor dedups answers on it.
818    pub id: u64,
819    pub kind: PromptKind,
820    pub title: String,
821    pub prompt: String,
822    pub raised_at: chrono::DateTime<chrono::Utc>,
823    /// Extension tool-call confirms only: the source extension(s) and tool.
824    /// Absent → "Allow all" is not offered (it could not be scoped).
825    #[serde(default, skip_serializing_if = "Option::is_none")]
826    pub confirm_scope: Option<ConfirmScope>,
827}
828
829// ── commands, settings, queries ───────────────────────────────────────────────
830
831/// A command with its origin. `from: None` = host-originated (router,
832/// lifecycle, idle probe) and bypasses input ownership (B1).
833#[derive(Debug)]
834pub struct Addressed {
835    pub from: Option<ClientId>,
836    pub cmd: SessionCommand,
837}
838
839/// Why a `Checkpoint` was requested.
840#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
841#[serde(rename_all = "snake_case")]
842pub enum CheckpointReason {
843    Reload,
844    HostRequest,
845}
846
847/// The entire client→session control surface (SEAMS §5.2/§5.3).
848///
849/// `Debug` is manual: `Submit`/`Steer`/`SubmitPrepared`/`Answer`/`Resume`
850/// print `<redacted>` (no lengths) so a command can be traced by *type*.
851#[derive(Serialize, Deserialize)]
852#[serde(tag = "cmd", rename_all = "snake_case")]
853pub enum SessionCommand {
854    /// User-authored prompt. Actor: reset auto-turn counter, push user msg
855    /// verbatim, start turn.
856    Submit {
857        text: String,
858        /// Pre-built canonical user content blocks (images, documents)
859        /// produced by `PendingAttachments::build_content` on the client.
860        /// Empty ⇔ text-only (backward compatible).
861        #[serde(default)]
862        attachments: Vec<serde_json::Value>,
863    },
864    /// Text typed while streaming. Actor: steer if a steer_tx is live else
865    /// queue; ALWAYS also sets queued_message.
866    Steer { text: String },
867    /// Steer one of this session's running subagents (`sa_N`) from its watch
868    /// view. Owner-only like `Steer`. The note also enters the MAIN
869    /// conversation as an event (no auto-turn), so the main agent knows the
870    /// user redirected its worker. Failure → `Refused`.
871    SubagentSteer { handle_id: String, text: String },
872    /// Esc. Cancel, adopt the turn's partial history + append the
873    /// interruption marker (`engine::interrupt`), dequeue, flush pending
874    /// events, cancel subagents, save.
875    Cancel,
876    /// Answer to a PromptRequest. `None` = cancelled.
877    /// NEVER journaled, NEVER replayed, NEVER traced.
878    Answer { prompt_id: u64, value: Option<String> },
879    /// `id` is client-chosen and echoed in `SettingChanged.id`.
880    Set { id: u64, setting: SessionSetting },
881    Compact { instructions: Option<String> },
882    /// `/new`: ConversationState::clear.
883    NewSession,
884    Save,
885    /// Reply = `SessionEventWire::QueryResult { id, value }`.
886    Query { id: u64, query: SessionQuery },
887    /// Reply = `Attached { client_id, … }` on THIS client's channel only.
888    Attach { client: ClientMeta, mode: AttachMode },
889    Detach { client: ClientId },
890    /// Host shutdown of this session: save → on_session_end → leases → Ended.
891    End { reason: EndReason },
892    /// Resync after Lagged (B, day 3): actor re-sends history + turn_replay.
893    Resync { client: ClientId, since_seq: u64 },
894    /// Runtime-backed slash command (`engine::commands::handle_engine_command`:
895    /// /model /thinking /context /trace /memory /compact …). Reply =
896    /// `QueryResult { id, value: {"kind": .., "text": ..} }`.
897    EngineCommand { id: u64, name: String, arg: String },
898    /// (A3) dispatch.rs LoadSkill — pre-built tool_use/tool_result pair
899    /// (+ optional user text) then a turn. Does NOT reset
900    /// consecutive_auto_turns.
901    SubmitPrepared {
902        messages: Vec<crate::SharedMessage>,
903        #[serde(default)]
904        user_text: Option<String>,
905    },
906    /// (A3) tools-backed (non-interactive) plugin command on THE runtime's
907    /// tool set. Reply = `QueryResult{id, {kind:"plugin_output", ..}}`.
908    PluginCommand { id: u64, plugin: String, name: String, arg: String },
909    /// (A3) `/resume`: save current, load `query`, restore model/reasoning/
910    /// system prompt, swap conversation. Reply = `Resumed{id, ..}`.
911    Resume { id: u64, query: String },
912    /// (B1, used by C3 reload) cancel any turn (partial history + marker),
913    /// abort compaction, save, close PTYs, emit Notice. Never ends the
914    /// session. Reply = `QueryResult{id: CHECKPOINT_QUERY_ID, {ok:true}}`.
915    Checkpoint { reason: CheckpointReason },
916    /// (B3) pin/unpin (`/pin on|off`, `--keep-warm`, `/keep-warm on|off`,
917    /// `synaps daemon pin`). Published on `SessionHandle::pinned()`.
918    KeepWarm { on: bool },
919    /// (B1) `/takeover`: the sending client takes input ownership in place,
920    /// like an `--takeover` attach without re-attaching. Not an input
921    /// command (a read-only client sends it); refused from an `Observe`
922    /// client, a no-op from the owner. Emits `InputOwnerChanged{Takeover}`
923    /// (`Attach` when nobody owned input).
924    TakeInput,
925    /// Host-only (never wire): park now if `can_park()` (reload rehydrates
926    /// a Parked session Parked). A no-op otherwise.
927    #[serde(skip)]
928    Park,
929    /// Host-only (never wire): reload's rehydrate hands the new image the
930    /// workers the old image stopped or still owed a wake
931    /// (`SessionReloadRecord::workers`). The actor re-registers their ids
932    /// against their archives and wakes the parent once per worker.
933    #[serde(skip)]
934    AdoptWorkers { workers: Vec<crate::runtime::subagent::CarriedWorker> },
935    /// Host-only (never wire): reload's rehydrate hands the new image the
936    /// exact tool activations the session held in the previous image
937    /// (`SessionReloadRecord::tool_activations`). The runtime re-validates
938    /// and restores them at its first turn start; a parked session keeps
939    /// them for its unpark. Sent before anything can start a turn.
940    #[serde(skip)]
941    RestoreToolActivations {
942        activations: Vec<crate::tools::activation::CarriedActivation>,
943    },
944    /// Host-only (never wire): reload's rehydrate, last, for a session that
945    /// comes back Live. The old image's park timer did not survive the exec
946    /// and only an attach or detach arms a new one, so a session no client
947    /// reconnects to stayed Live with zero clients forever. Arms the park
948    /// grace as a detach does; a client reconnecting within it clears it.
949    /// A no-op on a parked session.
950    #[serde(skip)]
951    ArmPark,
952    /// Host-only (never wire): the reload this session checkpointed for
953    /// did not exec (the exec failed, or the reload stopped after the
954    /// checkpoints). The checkpoint's reload fence lifts, and the workers
955    /// the reload stopped are announced to this same image.
956    #[serde(skip)]
957    ReloadAborted,
958    /// Host→session (never wire): the actor re-emits as `SessionEventWire`.
959    #[serde(skip)]
960    HostEvent(HostEvent),
961    /// (E-P0) Start or re-arm the session driver for `plugin`.
962    /// `command` is the interactive command name (e.g. "auto");
963    /// `arg` is everything after the command ("start -- do X").
964    /// No `DriverStop` — `Cancel` handles that (§2).
965    DriverStart {
966        plugin: String,
967        command: String,
968        arg: String,
969    },
970}
971
972/// What `Checkpoint{Reload}` reports so `daemon reload` can rebuild the
973/// session as it IS (not as it was created): the actor's config, keep-warm
974/// pin, lifecycle, the non-persisted knobs (`settings_replay`, incl.
975/// `/system`), the CURRENT model/thinking, and its tool activations.
976#[derive(Clone, Debug, Serialize, Deserialize)]
977pub struct SessionReloadRecord {
978    pub config: SessionConfig,
979    pub keep_warm: bool,
980    pub lifecycle: SessionLifecycle,
981    #[serde(default)]
982    pub settings_replay: Vec<SessionSetting>,
983    /// Per-session `/keepwarm` override (`off`/`auto`/`<N>h`), if any.
984    #[serde(default)]
985    pub cache_keepwarm: Option<String>,
986    pub model: String,
987    pub thinking_level: String,
988    /// Workers a reload stopped (or that still owed a completion wake), so
989    /// the next image can re-register their ids and wake the parent.
990    #[serde(default)]
991    pub workers: Vec<crate::runtime::subagent::CarriedWorker>,
992    /// The session's exact tool activations (`activate_tools` grants), so
993    /// the next image's runtime keeps the tools array the cached prompt
994    /// prefix starts with. Pins only, re-validated on restore.
995    #[serde(default)]
996    pub tool_activations: Vec<crate::tools::activation::CarriedActivation>,
997}
998
999/// What a session tells a client whose command a daemon reload refused.
1000pub const RELOADING_REFUSAL: &str = "daemon reloading; retry in a moment";
1001
1002impl SessionCommand {
1003    /// Refused while a daemon reload has checkpointed the session (its
1004    /// reload fence is up) until the exec, or until the daemon reports the
1005    /// exec failed: anything that starts a turn (a `Steer` with no turn
1006    /// running is a `Submit`), changes the conversation or journal the
1007    /// record points at, launches or steers work, or changes a setting the
1008    /// record already carries. Cancel, answers, queries, saves and
1009    /// attach/detach stay open.
1010    pub fn refused_while_reloading(&self) -> bool {
1011        matches!(
1012            self,
1013            Self::Submit { .. }
1014                | Self::SubmitPrepared { .. }
1015                | Self::Steer { .. }
1016                | Self::SubagentSteer { .. }
1017                | Self::Compact { .. }
1018                | Self::NewSession
1019                | Self::Resume { .. }
1020                | Self::EngineCommand { .. }
1021                | Self::PluginCommand { .. }
1022                | Self::DriverStart { .. }
1023                | Self::Set { .. }
1024                | Self::KeepWarm { .. }
1025        )
1026    }
1027}
1028
1029impl std::fmt::Debug for SessionCommand {
1030    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1031        match self {
1032            Self::Submit { attachments, .. } => {
1033                let kinds: Vec<&str> = attachments
1034                    .iter()
1035                    .filter_map(|b| b.get("type").and_then(|v| v.as_str()))
1036                    .collect();
1037                f.debug_struct("Submit")
1038                    .field("text", &format_args!("<redacted>"))
1039                    .field("attachments", &format_args!("{}:{:?}", attachments.len(), kinds))
1040                    .finish()
1041            }
1042            Self::Steer { .. } => f
1043                .debug_struct("Steer")
1044                .field("text", &format_args!("<redacted>"))
1045                .finish(),
1046            Self::SubagentSteer { handle_id, .. } => f
1047                .debug_struct("SubagentSteer")
1048                .field("handle_id", handle_id)
1049                .field("text", &format_args!("<redacted>"))
1050                .finish(),
1051            Self::SubmitPrepared { .. } => f
1052                .debug_struct("SubmitPrepared")
1053                .field("messages", &format_args!("<redacted>"))
1054                .field("user_text", &format_args!("<redacted>"))
1055                .finish(),
1056            Self::Answer { prompt_id, .. } => f
1057                .debug_struct("Answer")
1058                .field("prompt_id", prompt_id)
1059                .field("value", &format_args!("<redacted>"))
1060                .finish(),
1061            Self::Resume { id, .. } => f
1062                .debug_struct("Resume")
1063                .field("id", id)
1064                .field("query", &format_args!("<redacted>"))
1065                .finish(),
1066            Self::Cancel => f.write_str("Cancel"),
1067            Self::Set { id, setting } => {
1068                f.debug_struct("Set").field("id", id).field("setting", setting).finish()
1069            }
1070            Self::Compact { instructions } => {
1071                f.debug_struct("Compact").field("instructions", instructions).finish()
1072            }
1073            Self::NewSession => f.write_str("NewSession"),
1074            Self::Save => f.write_str("Save"),
1075            Self::TakeInput => f.write_str("TakeInput"),
1076            Self::Park => f.write_str("Park"),
1077            Self::AdoptWorkers { workers } => f
1078                .debug_struct("AdoptWorkers")
1079                .field("workers", &workers.iter().map(|w| w.id.as_str()).collect::<Vec<_>>())
1080                .finish(),
1081            Self::RestoreToolActivations { activations } => f
1082                .debug_struct("RestoreToolActivations")
1083                .field(
1084                    "tools",
1085                    &activations.iter().map(|a| a.tool_id.as_str()).collect::<Vec<_>>(),
1086                )
1087                .finish(),
1088            Self::ReloadAborted => f.write_str("ReloadAborted"),
1089            Self::ArmPark => f.write_str("ArmPark"),
1090            Self::Query { id, query } => {
1091                f.debug_struct("Query").field("id", id).field("query", query).finish()
1092            }
1093            Self::Attach { client, mode } => {
1094                f.debug_struct("Attach").field("client", client).field("mode", mode).finish()
1095            }
1096            Self::Detach { client } => f.debug_struct("Detach").field("client", client).finish(),
1097            Self::End { reason } => f.debug_struct("End").field("reason", reason).finish(),
1098            Self::Resync { client, since_seq } => f
1099                .debug_struct("Resync")
1100                .field("client", client)
1101                .field("since_seq", since_seq)
1102                .finish(),
1103            Self::EngineCommand { id, name, arg } => f
1104                .debug_struct("EngineCommand")
1105                .field("id", id)
1106                .field("name", name)
1107                .field("arg", arg)
1108                .finish(),
1109            Self::PluginCommand { id, plugin, name, arg } => f
1110                .debug_struct("PluginCommand")
1111                .field("id", id)
1112                .field("plugin", plugin)
1113                .field("name", name)
1114                .field("arg", arg)
1115                .finish(),
1116            Self::Checkpoint { reason } => {
1117                f.debug_struct("Checkpoint").field("reason", reason).finish()
1118            }
1119            Self::KeepWarm { on } => f.debug_struct("KeepWarm").field("on", on).finish(),
1120            Self::HostEvent(ev) => f.debug_tuple("HostEvent").field(ev).finish(),
1121            Self::DriverStart { plugin, command, .. } => f
1122                .debug_struct("DriverStart")
1123                .field("plugin", plugin)
1124                .field("command", command)
1125                .field("arg", &format_args!("<redacted>"))
1126                .finish(),
1127        }
1128    }
1129}
1130
1131/// Host-originated events pushed into a session (C3 router, loader).
1132#[derive(Debug, Clone)]
1133pub enum HostEvent {
1134    ExtensionNotification {
1135        extension_id: String,
1136        method: String,
1137        params: serde_json::Value,
1138    },
1139    LoaderProgress(crate::extensions::loader::ExtensionLoaderEvent),
1140}
1141
1142/// The `&mut Runtime` setters the TUI/rpc/server call (SEAMS §5.3).
1143#[derive(Debug, Clone, Serialize, Deserialize)]
1144#[serde(tag = "setting", rename_all = "snake_case")]
1145pub enum SessionSetting {
1146    /// try_set_model → SettingApplied::Model{applied, thinking_level}
1147    Model { model: String },
1148    /// set_reasoning_level_checked
1149    ReasoningLevel {
1150        #[serde(with = "reasoning_level_serde")]
1151        level: agent_core::reasoning::ReasoningLevel,
1152    },
1153    /// set_context_window
1154    ContextWindow { tokens: Option<u64> },
1155    CompactionModel { model: Option<String> },
1156    ApiRetries { n: u32 },
1157    SubagentTimeout { secs: u64 },
1158    MaxToolOutput { bytes: usize },
1159    BashTimeout { secs: u64 },
1160    BashMaxTimeout { secs: u64 },
1161    /// set_system_prompt
1162    SystemPrompt { text: String },
1163    /// reload_prompt() → SettingApplied::PromptReloaded{generation, source}
1164    ReloadPrompt,
1165    /// grant_worker_model
1166    GrantWorkerModel { model: String },
1167}
1168
1169#[derive(Debug, Clone, Serialize, Deserialize)]
1170pub struct SettingApplied {
1171    /// Correlates with `Set{id}`.
1172    #[serde(default)]
1173    pub id: u64,
1174    pub setting: String,
1175    pub ok: bool,
1176    pub message: Option<String>,
1177    pub view: RuntimeView,
1178    /// `{from, to}` when a model change clamped the reasoning level, so the
1179    /// TUI renders `reasoning_clamp_notice` byte-for-byte.
1180    #[serde(default)]
1181    pub clamp: Option<ReasoningClampWire>,
1182}
1183
1184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1185pub struct ReasoningClampWire {
1186    pub from: String,
1187    pub to: String,
1188}
1189
1190#[derive(Debug, Clone, Serialize, Deserialize)]
1191#[serde(tag = "query", rename_all = "snake_case")]
1192pub enum SessionQuery {
1193    /// {session, model, tokens, cost, streaming, auto_turns, attached, pending_prompts}
1194    Status,
1195    /// Vec<SharedMessage> (api_messages)
1196    Messages,
1197    /// Vec<SubagentDisplayRow>
1198    SubagentRows,
1199    /// runtime.prompt_inspection_json()
1200    PromptInspection,
1201    /// rpc_dispatch::build_tools_list_body input
1202    ToolsSchema,
1203    /// RuntimeView (cheap; LocalTransport answers without a hop)
1204    View,
1205    /// assess_context
1206    ContextAssessment,
1207    /// `engine::commands::context_command(runtime, Some(api_messages))` text.
1208    ContextReport,
1209    /// `display::DisplayTail` of the last `items` display items (phase 4).
1210    DisplayTail { items: usize },
1211    /// `runtime::subagent_watch::WatchPage`: one of this session's workers,
1212    /// its journal from `since` (the previous page's `next_seq`; 0 = all).
1213    /// Unknown handle → `{"error": ..}`. `tool_queue`: include
1214    /// `WatchEvent::ToolQueued`/`ToolStarted` entries (an older client
1215    /// omits it and would fail to decode a page that had them; an older
1216    /// daemon ignores it and never records them).
1217    SubagentWatch {
1218        handle_id: String,
1219        since: u64,
1220        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1221        tool_queue: bool,
1222    },
1223}
1224
1225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1226#[serde(rename_all = "snake_case")]
1227pub enum EndReason {
1228    ClientQuit,
1229    HostShutdown,
1230    Evicted,
1231    Error,
1232    /// F18: zero turns, zero clients, park grace elapsed. There is nothing
1233    /// to journal, so the session cannot park; it ends instead of holding a
1234    /// Runtime resident forever.
1235    Idle,
1236}
1237
1238// ── events + envelope ─────────────────────────────────────────────────────────
1239
1240/// What a session tells its clients. `Stream` carries the un-serialised
1241/// StreamEvent in-process (LocalTransport) — that IS the byte-identical
1242/// contract. The socket boundary converts to `wire::WireSessionEvent`.
1243#[derive(Debug, Clone)]
1244#[allow(clippy::large_enum_variant)] // Attached carries the full snapshot by design (§2.4)
1245pub enum SessionEventWire {
1246    Stream(crate::StreamEvent),
1247    /// Actor bookkeeping the client needs to mirror `App` fields exactly.
1248    /// `user_text` = the prompt that started the turn: the queued text on
1249    /// `QueuedAuto` (every client pushes the User card + scroll), the
1250    /// submitted text on `User` (clients OTHER than the submitter push the
1251    /// card; the submitter drew it at submit); `None` otherwise. The attach
1252    /// replay ring stores it as `None` (the snapshot's history has it).
1253    TurnStarted {
1254        turn_baseline: usize,
1255        trigger: TurnTrigger,
1256        user_text: Option<String>,
1257    },
1258    /// Emitted after every MessageHistory / Done / Error / Cancel / Compact so
1259    /// mirrors never diverge: the actor's api_messages IS the truth.
1260    Conversation(ConversationSnapshot),
1261    Prompt(PromptRequest),
1262    /// So mirrors dismiss the modal.
1263    PromptResolved { prompt_id: u64 },
1264    /// Drained event card — presentation only.
1265    External(crate::events::types::Event),
1266    AutoTurnCapReached { cap: u32 },
1267    /// The turn machine is idle: a stream ended (Done/Error/Cancel) and NO
1268    /// auto-turn followed. Headless hosts gate stdin on this so a queued
1269    /// auto-turn is never raced by the next line.
1270    Idle,
1271    /// "→ steering:" vs "queued:".
1272    Steered { text: String, delivered: bool },
1273    Dequeued { text: String },
1274    /// Any ChatMessage::System the actor would have pushed.
1275    SystemNotice(String),
1276    LoaderProgress(crate::extensions::loader::ExtensionLoaderEvent),
1277    ExtensionNotification {
1278        extension_id: String,
1279        method: String,
1280        params: serde_json::Value,
1281    },
1282    SettingChanged(SettingApplied),
1283    QueryResult { id: u64, value: serde_json::Value },
1284    /// Only to the attaching client.
1285    Attached {
1286        client: ClientId,
1287        snapshot: AttachSnapshot,
1288    },
1289    /// `name`: resolved by the session (unique in it).
1290    ClientJoined { client: ClientId, kind: ClientKind, name: String, mode: AttachMode },
1291    ClientLeft { client: ClientId },
1292    Ended { reason: EndReason },
1293    /// Cancel landed. TUI: drop_empty_thinking, push Error(abort_msg),
1294    /// subagents.clear(), streaming=false. `context_saved` (name kept for
1295    /// protocol v3): the interrupted turn's partial work is kept in history.
1296    Aborted { context_saved: bool },
1297    /// `/clear`. TUI: transcript.clear, counters=0, "new session started".
1298    Cleared { session_id: String },
1299    /// (B2) `disclosure` = preview_compaction_disclosure().render_line().
1300    CompactionStarted { source: String, disclosure: String },
1301    CompactionApplied {
1302        previous_session_id: String,
1303        session_id: String,
1304        chains_advanced: Vec<String>,
1305        queued_restored: Option<String>,
1306        msg_count: usize,
1307    },
1308    /// "compaction failed: {e}" vs "compaction task panicked: {e}".
1309    CompactionFailed { message: String, panicked: bool },
1310    CompactionCancelled,
1311    /// `runtime.subagent_registry().display_rows()` — at Done/Error and at
1312    /// 1 Hz while any row is non-terminal.
1313    SubagentRows(Vec<crate::runtime::subagent::SubagentDisplayRow>),
1314    /// `/resume` reply (`Resume{id}`).
1315    Resumed {
1316        id: u64,
1317        old_id: String,
1318        new_id: String,
1319        via: Option<String>,
1320        clamp_notice: Option<String>,
1321    },
1322    /// (B1) sent to the previous owner on takeover, and to everyone on any
1323    /// owner change.
1324    InputOwnerChanged {
1325        from: Option<ClientId>,
1326        to: Option<ClientId>,
1327        reason: OwnerChangeReason,
1328    },
1329    /// (B1) a non-owner sent an input command. Only the sender renders it.
1330    Refused { client: ClientId, command: String, reason: String },
1331    /// (B3) targeted like `Attached`: the attach could not be honoured.
1332    AttachRefused { message: String },
1333    /// (B3) lifecycle transitions for mirrors and `sessions` listings.
1334    Lifecycle(SessionLifecycle),
1335    /// (C3) daemon is about to exec itself; clients reconnect.
1336    Reloading { generation: u64, retry_after_ms: u64 },
1337    /// (E-P0) Driver armed on this session.
1338    DriverArmed {
1339        plugin_id: String,
1340        run_id: String,
1341        models: Vec<crate::extensions::session_driver::Selection>,
1342        selection: crate::extensions::session_driver::Selection,
1343        /// Remaining ms, not absolute Instant.
1344        deadline_ms: Option<u64>,
1345        notice: String,
1346    },
1347    /// (E-P0) Driver revoked.
1348    DriverRevoked {
1349        reason: String,
1350        undelivered_steering: Vec<String>,
1351    },
1352    /// (E-P0) One driver turn completed.
1353    DriverTurnOutcome {
1354        outcome: crate::extensions::session_driver::Outcome,
1355        selection: crate::extensions::session_driver::Selection,
1356        feedback: Option<String>,
1357    },
1358    /// (E-P7, §S3) A spend ceiling was breached: the turn was cancelled and any
1359    /// armed driver revoked. `scope` is "session" (config cap) or "run" (the
1360    /// driver grant's per-run cap). Additive v3 driver event — old clients skip
1361    /// it via `#[serde(other)]`.
1362    CostCapReached {
1363        scope: String,
1364        cost: f64,
1365        cap: f64,
1366    },
1367}
1368
1369#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1370#[serde(rename_all = "snake_case")]
1371pub enum OwnerChangeReason {
1372    Attach,
1373    Takeover,
1374    OwnerDetached,
1375    Reload,
1376    /// `client_input = shared`: this client sent input, so it is now the
1377    /// active one. Sent only to clients declaring
1378    /// `ClientCapabilities::owner_reason_input`: an older one never sees an
1379    /// owner change on a shared session (`wire::legacy_shared`).
1380    Input,
1381}
1382
1383#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1384#[serde(rename_all = "snake_case")]
1385pub enum TurnTrigger {
1386    User,
1387    QueuedAuto,
1388    EventAuto,
1389    PluginCommand,
1390    Compaction,
1391    /// (E-P0) Turn initiated by the session driver.
1392    DriverAuto,
1393}
1394
1395/// Per-session, gapless `seq` assigned at the single emit site
1396/// (`SessionActor::emit`); `ts` from the host clock.
1397#[derive(Debug, Clone)]
1398pub struct Envelope {
1399    pub session_id: SessionId,
1400    pub seq: u64,
1401    pub ts: chrono::DateTime<chrono::Utc>,
1402    pub event: SessionEventWire,
1403}
1404
1405#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1406pub struct ConversationTokens {
1407    pub input: u64,
1408    pub output: u64,
1409    pub cache_read: u64,
1410    pub cache_creation: u64,
1411}
1412
1413/// Memo of `wire::messages_hash(api_messages)` shared by every clone of one
1414/// snapshot: the daemon converts a `Conversation` to its wire digest once
1415/// per socket client, and hashing serialises the whole history — now once
1416/// per event, not once per client. Keyed on the history's length and last
1417/// message identity (histories only grow), so a snapshot whose messages are
1418/// replaced afterwards recomputes instead of reusing a stale hash.
1419#[derive(Clone, Default)]
1420pub struct MessagesHashMemo(pub(crate) std::sync::Arc<std::sync::Mutex<Option<HashedHistory>>>);
1421
1422/// `(len, last message, hash)` of the history a memo was computed for.
1423type HashedHistory = (usize, Option<crate::SharedMessage>, u64);
1424
1425impl MessagesHashMemo {
1426    pub fn hash(&self, messages: &[crate::SharedMessage]) -> u64 {
1427        let mut memo = self
1428            .0
1429            .lock()
1430            .unwrap_or_else(std::sync::PoisonError::into_inner);
1431        if let Some((len, last, hash)) = memo.as_ref() {
1432            let same_last = match (last, messages.last()) {
1433                (Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b),
1434                (None, None) => true,
1435                _ => false,
1436            };
1437            if *len == messages.len() && same_last {
1438                return *hash;
1439            }
1440        }
1441        let hash = super::wire::messages_hash(messages);
1442        *memo = Some((messages.len(), messages.last().cloned(), hash));
1443        hash
1444    }
1445}
1446
1447impl std::fmt::Debug for MessagesHashMemo {
1448    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1449        f.write_str("MessagesHashMemo")
1450    }
1451}
1452
1453/// Serializable mirror of `ConversationState` (+ the actor's auto-turn
1454/// counter). Clients MUST replace, never merge, on `Conversation(_)`.
1455#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1456pub struct ConversationSnapshot {
1457    /// The TUI's `App.session` mirror (never `api_messages`).
1458    #[serde(default)]
1459    pub header: SessionHeader,
1460    pub api_messages: Vec<crate::SharedMessage>,
1461    /// `api_messages.len()` on the daemon — always filled by the actor;
1462    /// `api_messages` itself may be empty for `HistoryMode::Digest` clients.
1463    #[serde(default)]
1464    pub messages_len: usize,
1465    pub tokens: ConversationTokens,
1466    pub cost: f64,
1467    /// Prompt-cache keep-warm spend, already included in `cost` (task #444).
1468    #[serde(default)]
1469    pub keepwarm_cost: f64,
1470    /// Keep-warm ping tokens, already included in `tokens` (task #444).
1471    #[serde(default)]
1472    pub keepwarm_tokens: ConversationTokens,
1473    /// Legacy (protocol v3 shape kept): always `None` — an interrupted turn
1474    /// is recorded in `api_messages` (`engine::interrupt`), never as a recap.
1475    pub abort_context: Option<String>,
1476    pub queued_message: Option<String>,
1477    pub pending_events_len: usize,
1478    pub consecutive_auto_turns: u32,
1479    /// Never serialised; see `MessagesHashMemo`.
1480    #[serde(skip)]
1481    pub messages_hash_memo: MessagesHashMemo,
1482}
1483
1484/// `Session` minus `api_messages` and accounting: what a client mirrors.
1485#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1486pub struct SessionHeader {
1487    pub id: String,
1488    pub title: String,
1489    pub name: Option<String>,
1490    pub model: String,
1491    pub thinking_level: String,
1492    pub system_prompt: Option<String>,
1493    pub created_at: chrono::DateTime<chrono::Utc>,
1494    pub updated_at: chrono::DateTime<chrono::Utc>,
1495    pub parent_session: Option<String>,
1496}
1497
1498impl From<&crate::Session> for SessionHeader {
1499    fn from(s: &crate::Session) -> Self {
1500        Self {
1501            id: s.id.clone(),
1502            title: s.title.clone(),
1503            name: s.name.clone(),
1504            model: s.model.clone(),
1505            thinking_level: s.thinking_level.clone(),
1506            system_prompt: s.system_prompt.clone(),
1507            created_at: s.created_at,
1508            updated_at: s.updated_at,
1509            parent_session: s.parent_session.clone(),
1510        }
1511    }
1512}
1513
1514#[derive(Debug, Clone)]
1515pub struct AttachSnapshot {
1516    pub meta: SessionMeta,
1517    pub view: RuntimeView,
1518    pub conversation: ConversationSnapshot,
1519    pub streaming: bool,
1520    /// Current-turn events since TurnStarted (bounded ring) so a mid-turn
1521    /// attach can rebuild partial text/tool cards.
1522    pub replay: Vec<Envelope>,
1523    pub pending_prompts: Vec<PromptRequest>,
1524    pub clients: Vec<(ClientId, ClientKind)>,
1525    /// Every attached client with its resolved name (`clients` stays for
1526    /// older clients). Empty from an older daemon.
1527    pub roster: Vec<ClientInfo>,
1528    /// Who may drive ([`ClientInput`]); `Exclusive` from an older daemon.
1529    pub client_input: ClientInput,
1530    /// Who owns input right now (B1) — so a joiner knows immediately
1531    /// whether its keystrokes will be honoured.
1532    pub input_owner: Option<ClientId>,
1533    /// Daemon-projected display tail — `Some` iff the client attached with
1534    /// `HistoryMode::Digest` (`conversation.api_messages` is then empty).
1535    pub display_tail: Option<crate::session::display::DisplayTail>,
1536}
1537
1538impl AttachSnapshot {
1539    /// For the client this snapshot was made for (`me`): who owns input, if
1540    /// someone else does — "input is owned by tui (#1); attach with
1541    /// --takeover to steal it". Rendered by each client from its OWN
1542    /// snapshot; the actor used to broadcast it as a `SystemNotice`, which
1543    /// every attached client (the owner included) and later attach replays
1544    /// showed.
1545    /// `None` with `client_input = shared`: every drive client may type.
1546    pub fn input_owned_elsewhere(&self, me: ClientId) -> Option<String> {
1547        if self.client_input == ClientInput::Shared {
1548            return None;
1549        }
1550        let owner = self.input_owner.filter(|o| *o != me)?;
1551        let who = Roster::from_snapshot(self).label(owner);
1552        Some(format!("input is owned by {who}; attach with --takeover to steal it"))
1553    }
1554}
1555
1556/// `ReasoningLevel` has no serde impls in agent-core; go through its
1557/// canonical string form.
1558pub mod reasoning_level_serde {
1559    use agent_core::reasoning::ReasoningLevel;
1560    use serde::{Deserialize, Deserializer, Serialize, Serializer};
1561
1562    pub fn serialize<S: Serializer>(level: &ReasoningLevel, s: S) -> Result<S::Ok, S::Error> {
1563        level.as_str().serialize(s)
1564    }
1565
1566    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<ReasoningLevel, D::Error> {
1567        let s = String::deserialize(d)?;
1568        ReasoningLevel::parse(&s)
1569            .ok_or_else(|| serde::de::Error::custom(format!("unknown reasoning level `{s}`")))
1570    }
1571}
1572
1573#[cfg(test)]
1574mod tests {
1575    use super::*;
1576
1577    #[test]
1578    fn client_names_are_short_plain_labels() {
1579        for ok in ["tui", "discord", "Dash_2", "a", "9lives", &"x".repeat(CLIENT_NAME_MAX)] {
1580            assert_eq!(validate_client_name(ok), Ok(()), "{ok}");
1581        }
1582        for bad in ["", "-lead", "_lead", "has space", "dots.no", "émoji", &"x".repeat(CLIENT_NAME_MAX + 1)] {
1583            let err = validate_client_name(bad).unwrap_err();
1584            assert!(err.starts_with("invalid client name"), "{bad}: {err}");
1585        }
1586    }
1587
1588    #[test]
1589    fn a_session_resolves_names_to_unique_ones() {
1590        // Requested, else the kind's name; an invalid request falls back.
1591        assert_eq!(resolve_client_name(Some("discord"), ClientKind::Rpc, []), "discord");
1592        assert_eq!(resolve_client_name(None, ClientKind::Tui, []), "tui");
1593        assert_eq!(resolve_client_name(Some("no spaces"), ClientKind::Attach, []), "attach");
1594        // Taken (case-insensitively): lowest free suffix from 2.
1595        assert_eq!(resolve_client_name(None, ClientKind::Tui, ["tui"]), "tui-2");
1596        assert_eq!(resolve_client_name(Some("TUI"), ClientKind::Tui, ["tui", "tui-2"]), "TUI-3");
1597        assert_eq!(resolve_client_name(None, ClientKind::Tui, ["tui", "tui-3"]), "tui-2");
1598        // A freed name is reused.
1599        assert_eq!(resolve_client_name(None, ClientKind::Tui, ["tui-2"]), "tui");
1600    }
1601
1602    #[test]
1603    fn a_roster_follows_joins_and_leaves_and_labels_by_name() {
1604        let joined = |id: u64, name: &str, mode: AttachMode| SessionEventWire::ClientJoined {
1605            client: ClientId(id),
1606            kind: ClientKind::Attach,
1607            name: name.to_string(),
1608            mode,
1609        };
1610        let mut r = Roster::default();
1611        r.apply(&joined(2, "dash", AttachMode::Observe));
1612        r.apply(&joined(1, "terminal", AttachMode::Mirror));
1613        // An older daemon's join has no name: the kind's is used.
1614        r.apply(&joined(3, "", AttachMode::Mirror));
1615        let ids: Vec<u64> = r.clients().iter().map(|c| c.id.0).collect();
1616        assert_eq!(ids, [1, 2, 3], "kept in id order");
1617        assert_eq!(r.get(ClientId(2)).unwrap().mode, AttachMode::Observe);
1618        assert_eq!(r.label(ClientId(1)), "terminal (#1)");
1619        assert_eq!(r.label(ClientId(3)), "attach (#3)");
1620        r.apply(&SessionEventWire::ClientLeft { client: ClientId(1) });
1621        assert_eq!(r.label(ClientId(1)), "client #1", "gone: id only");
1622        assert_eq!(r.clients().len(), 2);
1623    }
1624
1625    /// prA I-R5 minor: line/paragraph separators and the Arabic letter mark
1626    /// are stripped with the other format characters; ZWNJ/ZWJ are kept so
1627    /// emoji sequences and scripts that need them render intact.
1628    #[test]
1629    fn sanitize_prompt_text_strips_separators_keeps_zwj_zwnj() {
1630        let input = "a\u{2028}b\u{2029}c\u{061C}d\u{200B}e\u{200E}f\u{200F}g\u{202E}h\u{2067}i\x1bj\tk\nl";
1631        assert_eq!(sanitize_prompt_text(input), "abcdefghij k\nl");
1632        let family = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}";
1633        assert_eq!(sanitize_prompt_text(family), family, "ZWJ emoji intact");
1634        let persian = "\u{0645}\u{06CC}\u{200C}\u{062E}\u{0648}\u{0627}\u{0647}\u{0645}";
1635        assert_eq!(sanitize_prompt_text(persian), persian, "ZWNJ intact");
1636    }
1637
1638    #[test]
1639    fn prompt_kind_from_title() {
1640        assert_eq!(PromptKind::from_title("Confirm tool call"), PromptKind::Confirm);
1641        assert_eq!(
1642            PromptKind::from_title("Confirm tool activation"),
1643            PromptKind::Confirm
1644        );
1645        assert_eq!(PromptKind::from_title("API key"), PromptKind::Secret);
1646    }
1647
1648    #[test]
1649    fn session_config_default_persists() {
1650        let cfg: SessionConfig = serde_json::from_str("{}").unwrap();
1651        assert!(cfg.persist);
1652        assert!(cfg.cwd.is_none());
1653        assert_eq!(
1654            serde_json::to_value(SessionConfig::default()).unwrap()["persist"],
1655            serde_json::Value::Bool(true)
1656        );
1657    }
1658
1659    #[test]
1660    fn session_config_env_defaults_to_none() {
1661        let cfg: SessionConfig = serde_json::from_str("{}").unwrap();
1662        assert!(cfg.env.is_none());
1663    }
1664
1665    #[test]
1666    fn session_config_env_round_trips() {
1667        let env = vec![("FOO".into(), "bar".into()), ("PATH".into(), "/usr/bin".into())];
1668        let cfg = SessionConfig { env: Some(env.clone()), ..Default::default() };
1669        let json = serde_json::to_string(&cfg).unwrap();
1670        let cfg2: SessionConfig = serde_json::from_str(&json).unwrap();
1671        assert_eq!(cfg2.env, Some(env));
1672    }
1673
1674    #[test]
1675    fn should_strip_env_client_prefixes() {
1676        assert!(should_strip_env("SYNAPS_CLIENT_REEXEC"));
1677        assert!(should_strip_env("SYNAPS_TUI_SCROLLBACK"));
1678        assert!(should_strip_env("SYNAPS_DAEMON_ADOPT"));
1679        assert!(should_strip_env("SYNAPS_MEM_TRACE"));
1680        assert!(should_strip_env("SYNAPS_MEM_TRACE_FOO"));
1681        // Session env — not stripped
1682        assert!(!should_strip_env("SYNAPS_ANTHROPIC_BASE_URL"));
1683        assert!(!should_strip_env("HOME"));
1684        assert!(!should_strip_env("PATH"));
1685        assert!(!should_strip_env("VIRTUAL_ENV"));
1686    }
1687
1688    #[test]
1689    fn should_strip_env_secrets() {
1690        assert!(should_strip_env("ANTHROPIC_API_KEY"));
1691        assert!(should_strip_env("OPENAI_API_KEY"));
1692        assert!(should_strip_env("my_secret_token"));
1693        assert!(should_strip_env("AWS_SECRET_ACCESS_KEY"));
1694        assert!(should_strip_env("DB_PASSWORD"));
1695        assert!(should_strip_env("GCP_CREDENTIALS"));
1696        // Case insensitive
1697        assert!(should_strip_env("My_Api_Key"));
1698        // Not a secret
1699        assert!(!should_strip_env("MY_VALUE"));
1700        assert!(!should_strip_env("TOKENBUCKET_SIZE"));
1701        // suffix-anchored: the secret name must END the key
1702        assert!(!should_strip_env("API_TOKEN_TTL_SECS"));
1703        assert!(!should_strip_env("KEYBOARD_LAYOUT"));
1704        assert!(!should_strip_env("SSH_KEY_PATH"));
1705        assert!(should_strip_env("GH_TOKEN"));
1706        assert!(should_strip_env("SSH_KEY"));
1707        assert!(should_strip_env("SECRET_KEY_BASE"));
1708        assert!(should_strip_env("MY_PASSWD"));
1709    }
1710
1711    #[test]
1712    fn strip_client_env_drops_credential_values_whatever_the_key() {
1713        let vars = vec![
1714            ("HOME".to_string(), "/home/u".to_string()),
1715            (
1716                "DATABASE_URL".to_string(),
1717                "postgres://app:hunter2@db/prod".to_string(),
1718            ),
1719            (
1720                "HTTPS_PROXY".to_string(),
1721                "http://user:pass@proxy:3128".to_string(),
1722            ),
1723            (
1724                "SENTRY_DSN".to_string(),
1725                "https://abc123@o1.ingest.sentry.io/42".to_string(),
1726            ),
1727            ("GITHUB_PAT".to_string(), "ghp_x".to_string()),
1728            (
1729                "API_BASE_URL".to_string(),
1730                "https://api.example.com/v1".to_string(),
1731            ),
1732        ];
1733        let (env, stripped) = strip_client_env(vars);
1734        let kept: Vec<&str> = env.iter().map(|(k, _)| k.as_str()).collect();
1735        assert_eq!(
1736            kept,
1737            vec!["API_BASE_URL", "HOME"],
1738            "only non-secrets survive"
1739        );
1740        assert!(env.iter().all(|(_, v)| !v.contains("hunter2")
1741            && !v.contains("user:pass")
1742            && !v.contains("abc123")));
1743        assert_eq!(
1744            stripped,
1745            vec!["DATABASE_URL", "GITHUB_PAT", "HTTPS_PROXY", "SENTRY_DSN"],
1746            "stripped names are recorded"
1747        );
1748    }
1749
1750    #[test]
1751    fn capture_client_env_is_sorted_and_stripped() {
1752        // We can't fully control the process env in a unit test, but we can
1753        // verify the output is sorted and that known strip-list vars are absent.
1754        let (env, stripped) = capture_client_env();
1755        // Every stripped name is a secret by our own rule, and none of them
1756        // survived into the kept env.
1757        for name in &stripped {
1758            let by_value = std::env::var(name)
1759                .map(|v| agent_core::core::config::is_secret_env_value(&v))
1760                .unwrap_or(false);
1761            assert!(
1762                is_secret_key(name) || by_value,
1763                "stripped non-secret: {name}"
1764            );
1765            assert!(
1766                env.iter().all(|(k, _)| k != name),
1767                "stripped name leaked: {name}"
1768            );
1769        }
1770        // Sorted
1771        for w in env.windows(2) {
1772            assert!(w[0].0 <= w[1].0, "not sorted: {:?} > {:?}", w[0].0, w[1].0);
1773        }
1774        // No secrets or client-only vars
1775        for (k, v) in &env {
1776            assert!(!should_strip_env(k), "should have been stripped: {k}");
1777            assert!(
1778                !agent_core::core::config::is_secret_env_value(v),
1779                "credential value kept: {k}"
1780            );
1781        }
1782    }
1783
1784    #[test]
1785    fn command_json_round_trip() {
1786        let cmd = SessionCommand::Set {
1787            id: 7,
1788            setting: SessionSetting::ReasoningLevel {
1789                level: agent_core::reasoning::ReasoningLevel::Ultra,
1790            },
1791        };
1792        let json = serde_json::to_string(&cmd).unwrap();
1793        assert_eq!(
1794            json,
1795            r#"{"cmd":"set","id":7,"setting":{"setting":"reasoning_level","level":"ultra"}}"#
1796        );
1797        let back: SessionCommand = serde_json::from_str(&json).unwrap();
1798        assert!(matches!(
1799            back,
1800            SessionCommand::Set {
1801                id: 7,
1802                setting: SessionSetting::ReasoningLevel {
1803                    level: agent_core::reasoning::ReasoningLevel::Ultra
1804                }
1805            }
1806        ));
1807
1808        let submit: SessionCommand = serde_json::from_str(r#"{"cmd":"submit","text":"hi"}"#).unwrap();
1809        match submit {
1810            SessionCommand::Submit { text, attachments } => {
1811                assert_eq!(text, "hi");
1812                assert!(attachments.is_empty());
1813            }
1814            other => panic!("unexpected {other:?}"),
1815        }
1816
1817        // Submit with content blocks round-trips.
1818        let blocks = vec![
1819            serde_json::json!({"type":"image","source":{"type":"base64","media_type":"image/png","data":"iVBOR"}}),
1820            serde_json::json!({"type":"text","text":"hello"}),
1821        ];
1822        let submit_with = SessionCommand::Submit {
1823            text: "describe".into(),
1824            attachments: blocks.clone(),
1825        };
1826        let json = serde_json::to_string(&submit_with).unwrap();
1827        let back: SessionCommand = serde_json::from_str(&json).unwrap();
1828        match back {
1829            SessionCommand::Submit { text, attachments } => {
1830                assert_eq!(text, "describe");
1831                assert_eq!(attachments.len(), 2);
1832                assert_eq!(attachments[0]["type"], "image");
1833                assert_eq!(attachments[1]["type"], "text");
1834            }
1835            other => panic!("unexpected {other:?}"),
1836        }
1837    }
1838
1839    #[test]
1840    fn new_commands_round_trip() {
1841        let cmds = vec![
1842            SessionCommand::SubmitPrepared {
1843                messages: vec![std::sync::Arc::new(serde_json::json!({"role":"user","content":"x"}))],
1844                user_text: Some("t".into()),
1845            },
1846            SessionCommand::PluginCommand { id: 1, plugin: "p".into(), name: "n".into(), arg: "a".into() },
1847            SessionCommand::Resume { id: 2, query: "q".into() },
1848            SessionCommand::Checkpoint { reason: CheckpointReason::Reload },
1849            SessionCommand::KeepWarm { on: true },
1850            SessionCommand::Query { id: 3, query: SessionQuery::ContextReport },
1851            SessionCommand::Query {
1852                id: 4,
1853                query: SessionQuery::SubagentWatch { handle_id: "sa_2".into(), since: 7, tool_queue: true },
1854            },
1855            SessionCommand::SubagentSteer { handle_id: "sa_2".into(), text: "focus on X".into() },
1856            SessionCommand::DriverStart { plugin: "p".into(), command: "auto".into(), arg: "start -- hi".into() },
1857            SessionCommand::TakeInput,
1858        ];
1859        for cmd in cmds {
1860            let json = serde_json::to_string(&cmd).unwrap();
1861            let back: SessionCommand = serde_json::from_str(&json).unwrap();
1862            assert_eq!(serde_json::to_string(&back).unwrap(), json);
1863        }
1864        let take: SessionCommand = serde_json::from_str(r#"{"cmd":"take_input"}"#).unwrap();
1865        assert!(matches!(take, SessionCommand::TakeInput));
1866        let cp: SessionCommand = serde_json::from_str(r#"{"cmd":"checkpoint","reason":"host_request"}"#).unwrap();
1867        assert!(matches!(cp, SessionCommand::Checkpoint { reason: CheckpointReason::HostRequest }));
1868    }
1869
1870    #[test]
1871    fn command_debug_redacts_bodies_without_lengths() {
1872        let secret = "hunter2-very-secret";
1873        let cmds = vec![
1874            SessionCommand::Submit { text: secret.into(), attachments: vec![] },
1875            SessionCommand::Steer { text: secret.into() },
1876            SessionCommand::SubagentSteer { handle_id: "sa_1".into(), text: secret.into() },
1877            SessionCommand::SubmitPrepared {
1878                messages: vec![std::sync::Arc::new(serde_json::json!({"content": secret}))],
1879                user_text: Some(secret.into()),
1880            },
1881            SessionCommand::Answer { prompt_id: 1, value: Some(secret.into()) },
1882            SessionCommand::Resume { id: 1, query: secret.into() },
1883            SessionCommand::DriverStart { plugin: "p".into(), command: "auto".into(), arg: secret.into() },
1884        ];
1885        for cmd in cmds {
1886            let d = format!("{cmd:?}");
1887            assert!(!d.contains(secret), "{d}");
1888            assert!(d.contains("<redacted>"), "{d}");
1889            assert!(!d.contains("chars"), "{d}");
1890            assert!(!d.contains(&secret.len().to_string()), "{d}");
1891        }
1892        let d = format!("{:?}", SessionCommand::Set { id: 4, setting: SessionSetting::ReloadPrompt });
1893        assert_eq!(d, "Set { id: 4, setting: ReloadPrompt }");
1894
1895        // Submit debug shows count+kinds, never base64.
1896        let b64_secret = "aHVudGVyMi12ZXJ5LXNlY3JldA==";
1897        let cmd = SessionCommand::Submit {
1898            text: "x".into(),
1899            attachments: vec![
1900                serde_json::json!({"type":"image","source":{"type":"base64","media_type":"image/png","data":b64_secret}}),
1901                serde_json::json!({"type":"document","title":"x.pdf","source":{"type":"base64","media_type":"application/pdf","data":"JVBER"}}),
1902            ],
1903        };
1904        let d = format!("{cmd:?}");
1905        assert!(d.contains(r#"2:["image", "document"]"#), "{d}");
1906        assert!(!d.contains(b64_secret), "base64 leaked: {d}");
1907    }
1908
1909    #[test]
1910    fn session_config_new_fields_default() {
1911        let cfg: SessionConfig = serde_json::from_str("{}").unwrap();
1912        assert_eq!(cfg.compaction_policy, CompactionPolicyWire::InPlace);
1913        assert!(cfg.await_extensions);
1914        assert!(!cfg.keep_warm);
1915        let cfg: SessionConfig =
1916            serde_json::from_str(r#"{"compaction_policy":"linked_successor","await_extensions":false}"#).unwrap();
1917        assert_eq!(cfg.compaction_policy, CompactionPolicyWire::LinkedSuccessor);
1918        assert!(!cfg.await_extensions);
1919    }
1920
1921    #[test]
1922    fn session_lifecycle_u8_round_trip() {
1923        for l in [SessionLifecycle::Live, SessionLifecycle::Parking, SessionLifecycle::Parked, SessionLifecycle::Ending] {
1924            assert_eq!(SessionLifecycle::from_u8(l as u8), l);
1925        }
1926        assert_eq!(serde_json::to_string(&SessionLifecycle::Parked).unwrap(), r#""parked""#);
1927    }
1928
1929    #[test]
1930    fn host_event_is_never_serialised() {
1931        let cmd = SessionCommand::HostEvent(HostEvent::LoaderProgress(
1932            crate::extensions::loader::ExtensionLoaderEvent::Started,
1933        ));
1934        assert!(serde_json::to_string(&cmd).is_err());
1935    }
1936}
1937
1938/// `Option<Option<String>>` on the wire without collapsing `Some(None)`:
1939/// absent → `None`; `{"latest": true}` → `Some(None)`; `"id"` → `Some(Some(id))`.
1940/// Older daemons/clients that sent a bare string or `null` still decode.
1941mod double_option {
1942    use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
1943
1944    #[derive(Serialize, Deserialize)]
1945    #[serde(untagged)]
1946    enum Wire {
1947        Latest { latest: bool },
1948        Id(String),
1949    }
1950
1951    pub fn serialize<S: Serializer>(v: &Option<Option<String>>, s: S) -> Result<S::Ok, S::Error> {
1952        match v {
1953            None => s.serialize_none(),
1954            Some(None) => Wire::Latest { latest: true }.serialize(s),
1955            Some(Some(id)) => Wire::Id(id.clone()).serialize(s),
1956        }
1957    }
1958
1959    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Option<String>>, D::Error> {
1960        match Option::<Wire>::deserialize(d)? {
1961            None => Ok(None),
1962            Some(Wire::Latest { latest: true }) => Ok(Some(None)),
1963            Some(Wire::Latest { latest: false }) => Err(de::Error::custom("continue_session: latest must be true")),
1964            Some(Wire::Id(id)) => Ok(Some(Some(id))),
1965        }
1966    }
1967
1968    #[cfg(test)]
1969    mod tests {
1970        use super::super::SessionConfig;
1971
1972        fn rt(v: Option<Option<String>>) -> Option<Option<String>> {
1973            let cfg = SessionConfig { continue_session: v, ..Default::default() };
1974            let j = serde_json::to_string(&cfg).unwrap();
1975            serde_json::from_str::<SessionConfig>(&j).unwrap().continue_session
1976        }
1977
1978        #[test]
1979        fn continue_session_round_trips_all_three_states() {
1980            assert_eq!(rt(None), None);
1981            assert_eq!(rt(Some(None)), Some(None), "bare --continue must survive the wire");
1982            assert_eq!(rt(Some(Some("abc".into()))), Some(Some("abc".into())));
1983        }
1984
1985        #[test]
1986        fn continue_session_accepts_legacy_encodings() {
1987            let old_null: SessionConfig = serde_json::from_str(r#"{"continue_session":null}"#).unwrap();
1988            assert_eq!(old_null.continue_session, None);
1989            let old_id: SessionConfig = serde_json::from_str(r#"{"continue_session":"xyz"}"#).unwrap();
1990            assert_eq!(old_id.continue_session, Some(Some("xyz".into())));
1991            let absent: SessionConfig = serde_json::from_str(r#"{}"#).unwrap();
1992            assert_eq!(absent.continue_session, None);
1993        }
1994    }
1995}
1996
1997/// Where a daemon session writes its pin (`daemon::pins::PinBook`). The
1998/// actor calls it exactly when the pin changes, when a pinned session moves
1999/// to a new journal or is renamed, and when a pinned session is ended on
2000/// purpose. Implementations do their own I/O and never fail the caller.
2001pub trait PinSink: Send + Sync {
2002    /// The session is pinned: add or refresh its entry (`journal_id` is
2003    /// current; `id` is the actor id, which may name an older journal).
2004    /// `cache_keepwarm`: the session's `/keepwarm` override (`off`/`auto`/`<N>h`).
2005    fn pinned(&self, id: &str, journal_id: &str, name: Option<&str>, cwd: Option<&std::path::Path>, cache_keepwarm: Option<&str>);
2006    /// Unpinned, or ended on purpose while pinned: drop its entry.
2007    fn unpinned(&self, id: &str, journal_id: &str);
2008    /// A pinned session's journal changed (`/clear`, a successor compaction,
2009    /// resume): the entry follows it.
2010    fn moved(&self, from: &str, to: &str);
2011}