Skip to main content

artifactize_core/acp/
wire.rs

1//! Owned ACP v1 JSON-RPC 2.0 stdio wire layer (`T-PARSE-AT-EDGE`, `C-ACP-EDGE-ISOLATION`).
2//!
3//! Enforces strict FIFO receive-order barriers via a single stdout reader task, bounds all
4//! incoming payloads, normalizes `configOptions` and legacy `models`/`modes` at the edge,
5//! rejects unknown server requests with `-32601`, and validates ACP v1 contract shapes.
6
7use std::{
8    path::Path,
9    sync::atomic::{AtomicU64, Ordering},
10    time::Duration,
11};
12
13use serde::{Deserialize, Serialize};
14use serde_json::{Value, json};
15use tokio::{
16    io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
17    process::{ChildStdin, ChildStdout},
18    sync::mpsc,
19    task::JoinHandle,
20};
21
22use crate::{
23    chat::ToolKind,
24    llm::{models::ListedModel, stdio_mcp::RpcId},
25    platform,
26};
27
28use super::redactor::StreamRedactor;
29
30use super::{
31    ConfigCategory, ConfigChoice, ConfigOption, ConfigSelection, PermissionOption,
32    PermissionOptionKind, PlanStep, PlanStepStatus, Problem, ToolDiff, ToolLocation, ToolStatus,
33};
34
35/// Pinned ACP protocol version.
36pub const PROTOCOL_VERSION: u32 = 1;
37/// ACP authentication-required JSON-RPC error code.
38const AUTH_REQUIRED: i64 = -32000;
39/// Timeout for the ACP `initialize` handshake.
40pub const INITIALIZE_TIMEOUT: Duration = Duration::from_secs(15);
41/// Timeout for `session/new` and `session/load`.
42pub const SESSION_OPEN_TIMEOUT: Duration = Duration::from_secs(30);
43/// Timeout for `session/set_config_option` and legacy model/mode setters.
44pub const CONFIG_TIMEOUT: Duration = Duration::from_secs(10);
45/// Grace window to drain stdout after sending `session/cancel` before terminating the child.
46pub const PROMPT_CANCEL_GRACE: Duration = Duration::from_secs(2);
47/// Best-effort write timeout for the `session/cancel` notification itself.
48const CANCEL_WRITE_GRACE: Duration = Duration::from_millis(250);
49/// Maximum size of one JSON-RPC line on ACP stdio.
50pub const LINE_BYTES: u64 = 32 * 1024 * 1024;
51/// Maximum persisted tool output per tool call.
52pub const TOOL_OUTPUT_BYTES: usize = 256 * 1024;
53/// Maximum persisted inline diff size per tool call.
54pub const DIFF_BYTES: usize = 512 * 1024;
55/// Maximum persisted final answer text per turn.
56pub const FINAL_ANSWER_BYTES: usize = 1024 * 1024;
57/// Maximum total persisted bytes of display events per turn.
58pub const TURN_PERSISTED_BYTES: usize = 8 * 1024 * 1024;
59/// Maximum number of display events persisted per turn.
60pub const TURN_DISPLAY_EVENTS: usize = 2_000;
61/// Maximum concurrent pending permission prompts per turn.
62pub const MAX_PENDING_PERMISSIONS: usize = 16;
63/// Maximum size of sanitized permission detail text persisted in SQLite.
64pub const PERMISSION_DETAIL_BYTES: usize = 16 * 1024;
65/// Bounded FIFO channel capacity between the stdout reader task and the turn/connection owner.
66pub const UPDATE_CHANNEL_CAPACITY: usize = 256;
67/// Some Antigravity CLI versions print this line before returning an auth error.
68pub const AUTH_LINK_MARKER: &str = "Open the following link to authenticate the ACP server:";
69
70static NEXT_CONNECTION_ID: AtomicU64 = AtomicU64::new(1);
71
72/// MCP server descriptor sent in `session/new` and `session/load`.
73#[derive(Debug, Clone, Serialize)]
74pub struct McpServer {
75    pub name: String,
76    #[serde(serialize_with = "crate::platform::path_serde::native::serialize_path")]
77    pub command: std::path::PathBuf,
78    pub args: Vec<String>,
79    pub env: Vec<McpEnv>,
80}
81
82#[derive(Debug, Clone, Serialize)]
83pub struct McpEnv {
84    pub name: String,
85    pub value: String,
86}
87
88/// Typed agent capabilities extracted from `initialize`.
89#[derive(Debug, Clone, Default)]
90pub struct AgentCapabilities {
91    pub load_session: bool,
92    pub logout_supported: bool,
93    pub system_prompt_append: bool,
94    pub mcp_http: bool,
95    pub mcp_sse: bool,
96}
97
98/// Typed result of `initialize`.
99#[derive(Debug, Clone)]
100pub struct Initialized {
101    pub protocol_version: u32,
102    pub capabilities: AgentCapabilities,
103}
104
105/// Typed result of `session/new` or `session/load`.
106#[derive(Debug, Clone)]
107pub struct OpenedSession {
108    pub session_id: String,
109    pub config_options: Vec<ConfigOption>,
110    pub uses_legacy_models: bool,
111    pub uses_legacy_modes: bool,
112}
113
114/// Typed ACP prompt completion reason.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
116#[serde(rename_all = "snake_case")]
117pub enum StopReason {
118    EndTurn,
119    Cancelled,
120    Refusal,
121    MaxTokens,
122    MaxTurnRequests,
123    #[serde(other)]
124    Other,
125}
126
127/// Typed ACP `session/request_permission` payload parsed at the edge.
128#[derive(Debug, Clone)]
129pub struct IncomingPermission {
130    pub rpc_id: RpcId,
131    pub session_id: String,
132    pub title: String,
133    pub tool_kind: ToolKind,
134    pub summary: String,
135    pub detail: Option<String>,
136    pub options: Vec<PermissionOption>,
137}
138
139/// Typed ACP `session/update` event normalized at the edge (no raw `serde_json::Value`).
140#[derive(Debug, Clone)]
141pub enum SessionEvent {
142    AgentMessageChunk {
143        text: String,
144    },
145    AgentThoughtChunk {
146        text: String,
147    },
148    ToolCall {
149        call_id: String,
150        title: String,
151        tool_kind: ToolKind,
152        status: ToolStatus,
153        summary: String,
154        locations: Vec<ToolLocation>,
155        output: Option<String>,
156        diff: Option<ToolDiff>,
157        output_truncated: bool,
158    },
159    ToolCallUpdate {
160        call_id: String,
161        title: Option<String>,
162        tool_kind: Option<ToolKind>,
163        status: Option<ToolStatus>,
164        summary: Option<String>,
165        locations: Option<Vec<ToolLocation>>,
166        output: Option<String>,
167        diff: Option<ToolDiff>,
168        output_truncated: bool,
169    },
170    Plan {
171        steps: Vec<PlanStep>,
172    },
173    ConfigOptionsUpdated {
174        options: Vec<ConfigOption>,
175    },
176    ModeChanged {
177        mode_id: String,
178    },
179    Notice {
180        text: String,
181    },
182}
183
184/// Replay suppression state bound to `(connection_id, load_request_id, remote_session_id)`.
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub struct LoadPhase {
187    pub connection_id: u64,
188    pub load_request_id: u64,
189    pub remote_session_id: String,
190}
191
192/// Outcome of applying saved `configOptions` in dependency order before `session/prompt`.
193#[derive(Debug, Clone)]
194pub struct AppliedConfig {
195    pub live_options: Vec<ConfigOption>,
196    pub effective_selections: Vec<ConfigSelection>,
197    pub notices: Vec<String>,
198}
199
200/// Frames delivered in strict FIFO receive order from the single stdout reader task.
201#[derive(Debug)]
202pub enum WireFrame {
203    Update {
204        session_id: String,
205        event: SessionEvent,
206    },
207    PermissionRequest(IncomingPermission),
208    UnknownServerRequest {
209        id: RpcId,
210        method: String,
211    },
212    Response {
213        id: u64,
214        result: Value,
215    },
216    Error {
217        id: u64,
218        code: i64,
219        message: String,
220        data: String,
221    },
222    SignedOut,
223    Eof,
224    ProtocolError(String),
225}
226
227/// Owned ACP JSON-RPC 2.0 stdio client with strict FIFO stdout reader barrier.
228pub struct Connection {
229    id: u64,
230    agent_name: String,
231    auth_hint: String,
232    redactor: StreamRedactor,
233    write: ChildStdin,
234    frames: mpsc::Receiver<WireFrame>,
235    reader_task: JoinHandle<()>,
236    next_request_id: u64,
237    replaying: Option<LoadPhase>,
238    capabilities: Option<AgentCapabilities>,
239}
240
241impl Connection {
242    pub fn new(
243        agent_name: impl Into<String>,
244        auth_hint: impl Into<String>,
245        stdout: ChildStdout,
246        stdin: ChildStdin,
247        hide_always_options: bool,
248        known_secrets: Vec<String>,
249    ) -> Self {
250        let id = NEXT_CONNECTION_ID.fetch_add(1, Ordering::Relaxed);
251        let (tx, rx) = mpsc::channel(UPDATE_CHANNEL_CAPACITY);
252        let reader_task = tokio::spawn(stdout_reader_loop(stdout, tx, hide_always_options));
253        Self {
254            id,
255            agent_name: agent_name.into(),
256            auth_hint: auth_hint.into(),
257            redactor: StreamRedactor::new(known_secrets),
258            write: stdin,
259            frames: rx,
260            reader_task,
261            next_request_id: 0,
262            replaying: None,
263            capabilities: None,
264        }
265    }
266
267    pub fn connection_id(&self) -> u64 {
268        self.id
269    }
270
271    pub fn capabilities(&self) -> Option<&AgentCapabilities> {
272        self.capabilities.as_ref()
273    }
274
275    pub async fn initialize(&mut self) -> Result<Initialized, Problem> {
276        let result: RawInitialized = self
277            .request_with_timeout("initialize", initialization_params(), INITIALIZE_TIMEOUT)
278            .await?;
279        if result.protocol_version != PROTOCOL_VERSION {
280            return Err(Problem::Failed(format!(
281                "{} offered unsupported ACP version {} (expected {PROTOCOL_VERSION}).",
282                self.agent_name, result.protocol_version
283            )));
284        }
285        let capabilities = AgentCapabilities {
286            load_session: result.agent_capabilities.load_session,
287            logout_supported: result.agent_capabilities.auth.logout.is_some(),
288            system_prompt_append: result
289                .agent_capabilities
290                .meta
291                .antigravity
292                .system_prompt
293                .append
294                || result.agent_capabilities.meta.system_prompt.append,
295            mcp_http: result.agent_capabilities.mcp_capabilities.http,
296            mcp_sse: result.agent_capabilities.mcp_capabilities.sse,
297        };
298        self.capabilities = Some(capabilities.clone());
299        Ok(Initialized {
300            protocol_version: result.protocol_version,
301            capabilities,
302        })
303    }
304
305    pub async fn session_new(
306        &mut self,
307        cwd: &Path,
308        mcp_servers: &[McpServer],
309        system_append: Option<&str>,
310    ) -> Result<OpenedSession, Problem> {
311        let mut params =
312            serde_json::to_value(NewSessionParams { cwd, mcp_servers }).map_err(|error| {
313                Problem::Failed(format!(
314                    "Cannot encode ACP session/new paths for {}: {error}",
315                    self.agent_name
316                ))
317            })?;
318        if let Some(system) = system_append {
319            params["_meta"] = json!({
320                "antigravity": { "systemPrompt": { "append": system } },
321                "systemPrompt": { "append": system }
322            });
323        }
324        let raw: RawSession = self
325            .request_with_timeout("session/new", params, SESSION_OPEN_TIMEOUT)
326            .await?;
327        Ok(normalize_session(raw))
328    }
329
330    /// Call `session/load` with replay suppression bound to `(connection_id, load_request_id, remote_session_id)`.
331    pub async fn session_load(
332        &mut self,
333        remote_session_id: &str,
334        cwd: &Path,
335        mcp_servers: &[McpServer],
336    ) -> Result<OpenedSession, Problem> {
337        let params = serde_json::to_value(LoadSessionParams {
338            session_id: remote_session_id,
339            cwd,
340            mcp_servers,
341        })
342        .map_err(|error| {
343            Problem::Failed(format!(
344                "Cannot encode ACP session/load params for {}: {error}",
345                self.agent_name
346            ))
347        })?;
348        let request_id = self.send_request("session/load", params).await?;
349        self.replaying = Some(LoadPhase {
350            connection_id: self.id,
351            load_request_id: request_id,
352            remote_session_id: remote_session_id.to_owned(),
353        });
354        let outcome = tokio::time::timeout(SESSION_OPEN_TIMEOUT, async {
355            loop {
356                let frame = self.next_raw_frame("session/load").await?;
357                match frame {
358                    WireFrame::Update { session_id, .. }
359                        if self.is_suppressed_replay(&session_id, request_id) =>
360                    {
361                        // Suppress historical replay updates until `session/load` completes.
362                        continue;
363                    }
364                    WireFrame::UnknownServerRequest { id, .. } => {
365                        self.send_method_not_found(id).await?;
366                    }
367                    WireFrame::PermissionRequest(req) => {
368                        // Never grant permission during session/load replay.
369                        self.send_permission_cancelled(req.rpc_id).await?;
370                    }
371                    WireFrame::Response { id, result } if id == request_id => {
372                        let raw: RawSessionLoadResult =
373                            serde_json::from_value(result).map_err(|_| {
374                                Problem::Failed(format!(
375                                    "{} returned an invalid ACP session/load response.",
376                                    self.agent_name
377                                ))
378                            })?;
379                        return Ok(normalize_session(RawSession {
380                            session_id: raw
381                                .session_id
382                                .unwrap_or_else(|| remote_session_id.to_owned()),
383                            config_options: raw.config_options,
384                            models: raw.models,
385                            modes: raw.modes,
386                        }));
387                    }
388                    WireFrame::Error {
389                        id,
390                        code,
391                        message,
392                        data,
393                    } if id == request_id => {
394                        return Err(self.rpc_error("session/load", code, &message, &data));
395                    }
396                    WireFrame::SignedOut => {
397                        return Err(Problem::SignedOut {
398                            agent: self.agent_name.clone(),
399                            hint: self.auth_hint.clone(),
400                        });
401                    }
402                    WireFrame::Eof => {
403                        return Err(Problem::Failed(format!(
404                            "{} exited while handling ACP session/load.",
405                            self.agent_name
406                        )));
407                    }
408                    WireFrame::ProtocolError(msg) => {
409                        return Err(Problem::Failed(self.redactor.redact_all(&msg)));
410                    }
411                    _ => {}
412                }
413            }
414        })
415        .await;
416        self.replaying = None;
417        outcome.unwrap_or_else(|_| {
418            Err(Problem::Failed(format!(
419                "{} timed out while handling ACP session/load.",
420                self.agent_name
421            )))
422        })
423    }
424
425    pub async fn set_config_option(
426        &mut self,
427        session_id: &str,
428        config_id: &str,
429        value: &str,
430    ) -> Result<Vec<ConfigOption>, Problem> {
431        let updated: RawConfigOptionsReply = self
432            .request_with_timeout(
433                "session/set_config_option",
434                json!({
435                    "sessionId": session_id,
436                    "configId": config_id,
437                    "value": value,
438                }),
439                CONFIG_TIMEOUT,
440            )
441            .await?;
442        Ok(normalize_config_options(updated.config_options))
443    }
444
445    pub async fn set_legacy_model(
446        &mut self,
447        session_id: &str,
448        model_id: &str,
449    ) -> Result<(), Problem> {
450        let _: Value = self
451            .request_with_timeout(
452                "session/set_model",
453                json!({ "sessionId": session_id, "modelId": model_id }),
454                CONFIG_TIMEOUT,
455            )
456            .await?;
457        Ok(())
458    }
459
460    pub async fn set_legacy_mode(
461        &mut self,
462        session_id: &str,
463        mode_id: &str,
464    ) -> Result<Option<String>, Problem> {
465        let request_id = self
466            .send_request(
467                "session/set_mode",
468                json!({ "sessionId": session_id, "modeId": mode_id }),
469            )
470            .await?;
471        let mut observed_mode: Option<String> = None;
472        let outcome = tokio::time::timeout(CONFIG_TIMEOUT, async {
473            loop {
474                match self.next_raw_frame("session/set_mode").await? {
475                    WireFrame::UnknownServerRequest { id, .. } => {
476                        self.send_method_not_found(id).await?;
477                    }
478                    WireFrame::PermissionRequest(req) => {
479                        self.send_permission_cancelled(req.rpc_id).await?;
480                    }
481                    WireFrame::Update {
482                        session_id: update_sid,
483                        event,
484                    } if update_sid == session_id => match event {
485                        SessionEvent::ModeChanged { mode_id } => {
486                            observed_mode = Some(mode_id);
487                        }
488                        SessionEvent::ConfigOptionsUpdated { options } => {
489                            if let Some(opt) = options
490                                .iter()
491                                .find(|opt| opt.category == ConfigCategory::Mode)
492                            {
493                                observed_mode = Some(opt.current_value.clone());
494                            }
495                        }
496                        _ => {}
497                    },
498                    WireFrame::Response { id, result } if id == request_id => {
499                        return Ok(extract_confirmed_legacy_mode(&result).or(observed_mode));
500                    }
501                    WireFrame::Error {
502                        id,
503                        code,
504                        message,
505                        data,
506                    } if id == request_id => {
507                        return Err(self.rpc_error("session/set_mode", code, &message, &data));
508                    }
509                    WireFrame::SignedOut => {
510                        return Err(Problem::SignedOut {
511                            agent: self.agent_name.clone(),
512                            hint: self.auth_hint.clone(),
513                        });
514                    }
515                    WireFrame::Eof => {
516                        return Err(Problem::Failed(format!(
517                            "{} exited while handling ACP session/set_mode.",
518                            self.agent_name
519                        )));
520                    }
521                    WireFrame::ProtocolError(msg) => {
522                        return Err(Problem::Failed(self.redactor.redact_all(&msg)));
523                    }
524                    WireFrame::Update { .. }
525                    | WireFrame::Response { .. }
526                    | WireFrame::Error { .. } => {}
527                }
528            }
529        })
530        .await;
531        outcome.unwrap_or_else(|_| {
532            Err(Problem::Failed(format!(
533                "{} timed out while handling ACP session/set_mode.",
534                self.agent_name
535            )))
536        })
537    }
538
539    /// Apply user-selected `configOptions` in dependency order:
540    /// `model` -> refresh live options -> `mode` -> `thought_level` -> rest.
541    ///
542    /// Falls back with a `Notice` only when a previously saved `model` or `thought_level`
543    /// disappeared from the live list; **aborts with `Problem::ModeMismatch`** if a user-selected
544    /// `mode` is missing or mismatched (never silently downgrades approval level).
545    pub async fn apply_config_options(
546        &mut self,
547        session: &OpenedSession,
548        requested: &[ConfigSelection],
549    ) -> Result<AppliedConfig, Problem> {
550        let mut live = session.config_options.clone();
551        let mut notices = Vec::new();
552        let mut ordered: Vec<(u8, &ConfigSelection)> = requested
553            .iter()
554            .map(|sel| {
555                let category = sel
556                    .category
557                    .or_else(|| {
558                        live.iter()
559                            .find(|opt| opt.id == sel.id)
560                            .map(|opt| opt.category)
561                    })
562                    .unwrap_or_else(|| infer_category(&sel.id, None));
563                (category.apply_rank(), sel)
564            })
565            .collect();
566        ordered.sort_by_key(|(rank, _)| *rank);
567
568        let mut effective = Vec::new();
569        for (_, selection) in ordered {
570            let inferred_cat = selection
571                .category
572                .or_else(|| {
573                    live.iter()
574                        .find(|opt| opt.id == selection.id)
575                        .map(|opt| opt.category)
576                })
577                .unwrap_or_else(|| infer_category(&selection.id, None));
578
579            let Some(current_opt) = live
580                .iter()
581                .find(|opt| {
582                    opt.id == selection.id
583                        || (selection.category.is_some()
584                            && Some(opt.category) == selection.category)
585                })
586                .cloned()
587            else {
588                if inferred_cat == ConfigCategory::Mode {
589                    return Err(Problem::ModeMismatch {
590                        requested: selection.value.clone(),
591                        actual: None,
592                    });
593                }
594                notices.push(format!(
595                    "Saved option {:?} is no longer advertised by {}; using the agent default.",
596                    selection.id, self.agent_name
597                ));
598                continue;
599            };
600
601            let is_mode = current_opt.category == ConfigCategory::Mode
602                || inferred_cat == ConfigCategory::Mode;
603            let choice_exists = current_opt
604                .choices
605                .iter()
606                .any(|choice| choice.value == selection.value);
607            if !choice_exists {
608                if is_mode {
609                    return Err(Problem::ModeMismatch {
610                        requested: selection.value.clone(),
611                        actual: Some(current_opt.current_value.clone()),
612                    });
613                }
614                notices.push(format!(
615                    "Saved {} {:?} is no longer available on {}; fell back to {:?}.",
616                    current_opt.name, selection.value, self.agent_name, current_opt.current_value
617                ));
618                effective.push(ConfigSelection {
619                    id: current_opt.id.clone(),
620                    value: current_opt.current_value.clone(),
621                    category: Some(current_opt.category),
622                });
623                continue;
624            }
625
626            if current_opt.current_value != selection.value {
627                if session.uses_legacy_models && current_opt.category == ConfigCategory::Model {
628                    self.set_legacy_model(&session.session_id, &selection.value)
629                        .await?;
630                    if let Some(opt) = live.iter_mut().find(|opt| opt.id == current_opt.id) {
631                        opt.current_value = selection.value.clone();
632                    }
633                } else if session.uses_legacy_modes && is_mode {
634                    let confirmed = self
635                        .set_legacy_mode(&session.session_id, &selection.value)
636                        .await?;
637                    if confirmed.as_deref() != Some(selection.value.as_str()) {
638                        return Err(Problem::ModeMismatch {
639                            requested: selection.value.clone(),
640                            actual: confirmed,
641                        });
642                    }
643                    if let Some(opt) = live.iter_mut().find(|opt| opt.id == current_opt.id) {
644                        opt.current_value = selection.value.clone();
645                    }
646                } else {
647                    live = self
648                        .set_config_option(&session.session_id, &current_opt.id, &selection.value)
649                        .await?;
650                    let confirmed = live
651                        .iter()
652                        .find(|opt| opt.id == current_opt.id)
653                        .map(|opt| opt.current_value.as_str());
654                    if confirmed != Some(selection.value.as_str()) {
655                        if is_mode {
656                            return Err(Problem::ModeMismatch {
657                                requested: selection.value.clone(),
658                                actual: confirmed.map(str::to_owned),
659                            });
660                        }
661                        return Err(Problem::Failed(format!(
662                            "{} did not confirm {} = {:?}.",
663                            self.agent_name, current_opt.id, selection.value
664                        )));
665                    }
666                }
667            }
668            effective.push(ConfigSelection {
669                id: current_opt.id,
670                value: selection.value.clone(),
671                category: Some(current_opt.category),
672            });
673        }
674
675        Ok(AppliedConfig {
676            live_options: live,
677            effective_selections: effective,
678            notices,
679        })
680    }
681
682    /// Inspect advertised models (and per-model thought levels when supported) for probes/CLI.
683    pub async fn inspect_models(
684        &mut self,
685        cwd: &Path,
686    ) -> Result<(Vec<ListedModel>, Vec<ConfigOption>), Problem> {
687        self.initialize().await?;
688        let session = self.session_new(cwd, &[], None).await?;
689        let mut config = session.config_options.clone();
690        let Some(model_opt) = config
691            .iter()
692            .find(|opt| opt.category == ConfigCategory::Model)
693            .cloned()
694        else {
695            return Ok((Vec::new(), config));
696        };
697        let mut models: Vec<ListedModel> = model_opt
698            .choices
699            .iter()
700            .filter_map(|choice| {
701                Some(ListedModel::new(
702                    choice.value.parse().ok()?,
703                    choice.name.clone(),
704                ))
705            })
706            .collect();
707        for model in models
708            .iter_mut()
709            .filter(|model| model.slug.as_str() == model_opt.current_value)
710        {
711            *model = listed_with_thought(model, &config);
712        }
713        if !session.uses_legacy_models {
714            for model in models
715                .iter_mut()
716                .filter(|model| model.slug.as_str() != model_opt.current_value)
717            {
718                if let Ok(updated) = self
719                    .set_config_option(&session.session_id, &model_opt.id, model.slug.as_str())
720                    .await
721                {
722                    config = updated;
723                    *model = listed_with_thought(model, &config);
724                }
725            }
726        }
727        Ok((models, session.config_options))
728    }
729
730    pub async fn logout(&mut self) -> Result<(), Problem> {
731        let init = self.initialize().await?;
732        if !init.capabilities.logout_supported {
733            return Err(Problem::Failed(format!(
734                "This {} CLI does not offer ACP sign-out. Sign out directly in the CLI (for example `/logout`).",
735                self.agent_name
736            )));
737        }
738        let _: Value = self
739            .request_with_timeout("logout", json!({}), INITIALIZE_TIMEOUT)
740            .await?;
741        Ok(())
742    }
743
744    pub async fn start_prompt(&mut self, session_id: &str, text: &str) -> Result<u64, Problem> {
745        self.send_request(
746            "session/prompt",
747            json!({
748                "sessionId": session_id,
749                "prompt": [{ "type": "text", "text": text }],
750            }),
751        )
752        .await
753    }
754
755    /// Receive the next FIFO frame while a prompt is active. Automatically answers unknown
756    /// server requests with `-32601` so the caller only sees updates, permissions, and prompt end.
757    pub async fn next_prompt_frame(
758        &mut self,
759        prompt_request_id: u64,
760        session_id: &str,
761    ) -> Result<PromptFrame, Problem> {
762        loop {
763            match self.next_raw_frame("session/prompt").await? {
764                WireFrame::Update {
765                    session_id: sid,
766                    event,
767                } if sid == session_id => return Ok(PromptFrame::Update(event)),
768                WireFrame::Update { .. } => {}
769                WireFrame::PermissionRequest(req) if req.session_id == session_id => {
770                    return Ok(PromptFrame::Permission(req));
771                }
772                WireFrame::PermissionRequest(req) => {
773                    self.send_permission_cancelled(req.rpc_id).await?;
774                }
775                WireFrame::UnknownServerRequest { id, .. } => {
776                    self.send_method_not_found(id).await?;
777                }
778                WireFrame::Response { id, result } if id == prompt_request_id => {
779                    let parsed: RawPromptResult = serde_json::from_value(result).map_err(|_| {
780                        Problem::Failed(format!(
781                            "{} returned an invalid ACP session/prompt response.",
782                            self.agent_name
783                        ))
784                    })?;
785                    return Ok(PromptFrame::Finished(parsed.stop_reason));
786                }
787                WireFrame::Error {
788                    id,
789                    code,
790                    message,
791                    data,
792                } if id == prompt_request_id => {
793                    return Err(self.rpc_error("session/prompt", code, &message, &data));
794                }
795                WireFrame::SignedOut => {
796                    return Err(Problem::SignedOut {
797                        agent: self.agent_name.clone(),
798                        hint: self.auth_hint.clone(),
799                    });
800                }
801                WireFrame::Eof => {
802                    return Err(Problem::Failed(format!(
803                        "{} exited while handling ACP session/prompt.",
804                        self.agent_name
805                    )));
806                }
807                WireFrame::ProtocolError(msg) => return Err(Problem::Failed(msg)),
808                WireFrame::Response { .. } | WireFrame::Error { .. } => {}
809            }
810        }
811    }
812
813    /// Send ACP `session/request_permission` `selected` outcome on the wire.
814    pub async fn send_permission_selected(
815        &mut self,
816        rpc_id: RpcId,
817        option_id: &str,
818    ) -> Result<(), Problem> {
819        self.send_json(&permission_selected_reply(rpc_id, option_id))
820            .await
821    }
822
823    /// Send ACP `session/request_permission` `cancelled` outcome per ACP v1 spec.
824    pub async fn send_permission_cancelled(&mut self, rpc_id: RpcId) -> Result<(), Problem> {
825        self.send_json(&permission_cancelled_reply(rpc_id)).await
826    }
827
828    /// Send `session/cancel` notification with bounded write timeout.
829    pub async fn send_cancel(&mut self, session_id: &str) {
830        let _ = tokio::time::timeout(
831            CANCEL_WRITE_GRACE,
832            self.send_json(&json!({
833                "jsonrpc": "2.0",
834                "method": "session/cancel",
835                "params": { "sessionId": session_id }
836            })),
837        )
838        .await;
839    }
840
841    /// Drain stdout up to `PROMPT_CANCEL_GRACE` after `session/cancel` so a warm child can
842    /// return to quiescence with `StopReason::Cancelled` instead of needing process termination.
843    pub async fn drain_after_cancel(&mut self, prompt_request_id: u64, session_id: &str) -> bool {
844        let result = tokio::time::timeout(PROMPT_CANCEL_GRACE, async {
845            loop {
846                match self.next_prompt_frame(prompt_request_id, session_id).await {
847                    Ok(PromptFrame::Finished(_)) => return true,
848                    Ok(PromptFrame::Permission(req)) => {
849                        if self.send_permission_cancelled(req.rpc_id).await.is_err() {
850                            return false;
851                        }
852                    }
853                    Ok(PromptFrame::Update(_)) => {}
854                    Err(_) => return false,
855                }
856            }
857        })
858        .await;
859        matches!(result, Ok(true))
860    }
861
862    async fn send_method_not_found(&mut self, id: RpcId) -> Result<(), Problem> {
863        self.send_json(&method_not_found_reply(id)).await
864    }
865
866    async fn request_with_timeout<T: serde::de::DeserializeOwned>(
867        &mut self,
868        method: &str,
869        params: Value,
870        timeout: Duration,
871    ) -> Result<T, Problem> {
872        let request_id = self.send_request(method, params).await?;
873        let outcome = tokio::time::timeout(timeout, async {
874            loop {
875                match self.next_raw_frame(method).await? {
876                    WireFrame::UnknownServerRequest { id, .. } => {
877                        self.send_method_not_found(id).await?;
878                    }
879                    WireFrame::PermissionRequest(req) => {
880                        self.send_permission_cancelled(req.rpc_id).await?;
881                    }
882                    WireFrame::Response { id, result } if id == request_id => {
883                        return serde_json::from_value(result).map_err(|_| {
884                            Problem::Failed(format!(
885                                "{} returned an invalid ACP {method} response.",
886                                self.agent_name
887                            ))
888                        });
889                    }
890                    WireFrame::Error {
891                        id,
892                        code,
893                        message,
894                        data,
895                    } if id == request_id => {
896                        return Err(self.rpc_error(method, code, &message, &data));
897                    }
898                    WireFrame::SignedOut => {
899                        return Err(Problem::SignedOut {
900                            agent: self.agent_name.clone(),
901                            hint: self.auth_hint.clone(),
902                        });
903                    }
904                    WireFrame::Eof => {
905                        return Err(Problem::Failed(format!(
906                            "{} exited while handling ACP {method}.",
907                            self.agent_name
908                        )));
909                    }
910                    WireFrame::ProtocolError(msg) => {
911                        return Err(Problem::Failed(self.redactor.redact_all(&msg)));
912                    }
913                    WireFrame::Update { .. }
914                    | WireFrame::Response { .. }
915                    | WireFrame::Error { .. } => {}
916                }
917            }
918        })
919        .await;
920        outcome.unwrap_or_else(|_| {
921            Err(Problem::Failed(format!(
922                "{} timed out while handling ACP {method}.",
923                self.agent_name
924            )))
925        })
926    }
927
928    async fn send_request(&mut self, method: &str, params: Value) -> Result<u64, Problem> {
929        self.next_request_id += 1;
930        let id = self.next_request_id;
931        self.send_json(&json!({
932            "jsonrpc": "2.0",
933            "id": id,
934            "method": method,
935            "params": params,
936        }))
937        .await?;
938        Ok(id)
939    }
940
941    async fn send_json(&mut self, value: &Value) -> Result<(), Problem> {
942        let mut bytes = value.to_string().into_bytes();
943        bytes.push(b'\n');
944        self.write.write_all(&bytes).await.map_err(|_| {
945            Problem::Failed(format!("{} stopped reading ACP input.", self.agent_name))
946        })?;
947        self.write
948            .flush()
949            .await
950            .map_err(|_| Problem::Failed(format!("{} stopped reading ACP input.", self.agent_name)))
951    }
952
953    async fn next_raw_frame(&mut self, method: &str) -> Result<WireFrame, Problem> {
954        self.frames.recv().await.ok_or_else(|| {
955            Problem::Failed(format!(
956                "{} exited while handling ACP {method}.",
957                self.agent_name
958            ))
959        })
960    }
961
962    fn is_suppressed_replay(&self, session_id: &str, request_id: u64) -> bool {
963        self.replaying.as_ref().is_some_and(|phase| {
964            phase.connection_id == self.id
965                && phase.load_request_id == request_id
966                && phase.remote_session_id == session_id
967        })
968    }
969
970    fn rpc_error(&self, method: &str, code: i64, message: &str, data: &str) -> Problem {
971        classify_rpc_error(
972            &self.agent_name,
973            &self.auth_hint,
974            &self.redactor,
975            method,
976            code,
977            message,
978            data,
979        )
980    }
981}
982
983fn classify_rpc_error(
984    agent_name: &str,
985    auth_hint: &str,
986    redactor: &StreamRedactor,
987    method: &str,
988    code: i64,
989    message: &str,
990    data: &str,
991) -> Problem {
992    if code == AUTH_REQUIRED {
993        return Problem::SignedOut {
994            agent: agent_name.to_owned(),
995            hint: auth_hint.to_owned(),
996        };
997    }
998    let redacted_message = redactor.redact_all(message.trim());
999    let redacted_data = redactor.redact_all(data);
1000    Problem::classify_text(
1001        agent_name,
1002        auth_hint,
1003        &format!("{code} {redacted_message} {redacted_data}"),
1004    )
1005    .unwrap_or_else(|| {
1006        let detail: String = redacted_message
1007            .chars()
1008            .filter(|c| !c.is_control())
1009            .collect();
1010        if detail.is_empty() {
1011            Problem::Failed(format!(
1012                "{agent_name} rejected ACP {method} (error {code})."
1013            ))
1014        } else {
1015            Problem::Failed(format!(
1016                "{agent_name} rejected ACP {method} (error {code}): {detail}"
1017            ))
1018        }
1019    })
1020}
1021
1022/// Extract a confirmed mode ID from a legacy `session/set_mode` JSON-RPC result when present.
1023fn extract_confirmed_legacy_mode(result: &Value) -> Option<String> {
1024    if let Some(mode) = result
1025        .get("currentModeId")
1026        .or_else(|| result.get("modeId"))
1027        .and_then(Value::as_str)
1028        .filter(|s| !s.is_empty())
1029    {
1030        return Some(mode.to_owned());
1031    }
1032    if let Some(mode) = result
1033        .get("modes")
1034        .and_then(|m| m.get("currentModeId"))
1035        .and_then(Value::as_str)
1036        .filter(|s| !s.is_empty())
1037    {
1038        return Some(mode.to_owned());
1039    }
1040    if let Some(raw_opts) = result.get("configOptions").and_then(Value::as_array) {
1041        let parsed: Vec<RawConfigOption> = raw_opts
1042            .iter()
1043            .filter_map(|v| serde_json::from_value(v.clone()).ok())
1044            .collect();
1045        let options = normalize_config_options(parsed);
1046        if let Some(opt) = options
1047            .into_iter()
1048            .find(|opt| opt.category == ConfigCategory::Mode && !opt.current_value.is_empty())
1049        {
1050            return Some(opt.current_value);
1051        }
1052    }
1053    None
1054}
1055
1056impl Drop for Connection {
1057    fn drop(&mut self) {
1058        self.reader_task.abort();
1059    }
1060}
1061
1062/// Frames surfaced to the turn runner during an active `session/prompt`.
1063#[derive(Debug)]
1064pub enum PromptFrame {
1065    Update(SessionEvent),
1066    Permission(IncomingPermission),
1067    Finished(StopReason),
1068}
1069
1070/// Single stdout reader task enforcing strict FIFO receive-order barriers.
1071async fn stdout_reader_loop(
1072    stdout: ChildStdout,
1073    tx: mpsc::Sender<WireFrame>,
1074    hide_always_options: bool,
1075) {
1076    let mut reader = BufReader::new(stdout);
1077    let mut line = Vec::new();
1078    let mut dropped_display_deltas: usize = 0;
1079
1080    loop {
1081        line.clear();
1082        let read = match (&mut reader)
1083            .take(LINE_BYTES + 1)
1084            .read_until(b'\n', &mut line)
1085            .await
1086        {
1087            Ok(count) => count,
1088            Err(error) => {
1089                let _ = tx
1090                    .send(WireFrame::ProtocolError(format!(
1091                        "Cannot read ACP output: {error}."
1092                    )))
1093                    .await;
1094                return;
1095            }
1096        };
1097        if read == 0 {
1098            let _ = tx.send(WireFrame::Eof).await;
1099            return;
1100        }
1101        if line.len() as u64 > LINE_BYTES {
1102            let _ = tx
1103                .send(WireFrame::ProtocolError(
1104                    "ACP agent wrote an oversized message (> 32 MiB).".into(),
1105                ))
1106                .await;
1107            return;
1108        }
1109        if line.iter().all(u8::is_ascii_whitespace) {
1110            continue;
1111        }
1112        if line.starts_with(AUTH_LINK_MARKER.as_bytes()) {
1113            let _ = tx.send(WireFrame::SignedOut).await;
1114            return;
1115        }
1116        let parsed = match parse_wire_frame(&line, hide_always_options) {
1117            Ok(Some(frame)) => frame,
1118            Ok(None) => continue,
1119            Err(error) => {
1120                let _ = tx.send(WireFrame::ProtocolError(error)).await;
1121                return;
1122            }
1123        };
1124
1125        let non_essential_delta = is_non_essential_display_delta(&parsed);
1126        if non_essential_delta {
1127            match tx.try_send(parsed) {
1128                Ok(()) => {}
1129                Err(mpsc::error::TrySendError::Full(_)) => {
1130                    dropped_display_deltas += 1;
1131                }
1132                Err(mpsc::error::TrySendError::Closed(_)) => return,
1133            }
1134        } else {
1135            if dropped_display_deltas > 0 {
1136                let count = std::mem::take(&mut dropped_display_deltas);
1137                let sid = match &parsed {
1138                    WireFrame::Update { session_id, .. } => session_id.clone(),
1139                    _ => String::new(),
1140                };
1141                if !sid.is_empty() {
1142                    let _ = tx
1143                        .send(WireFrame::Update {
1144                            session_id: sid,
1145                            event: SessionEvent::Notice {
1146                                text: format!(
1147                                    "Coalesced {count} rapid display update(s) to preserve ACP stream responsiveness."
1148                                ),
1149                            },
1150                        })
1151                        .await;
1152                }
1153            }
1154            if tx.send(parsed).await.is_err() {
1155                return;
1156            }
1157        }
1158    }
1159}
1160
1161fn is_non_essential_display_delta(frame: &WireFrame) -> bool {
1162    matches!(
1163        frame,
1164        WireFrame::Update {
1165            event: SessionEvent::AgentThoughtChunk { .. }
1166                | SessionEvent::ToolCallUpdate { status: None, .. },
1167            ..
1168        }
1169    )
1170}
1171
1172/// Pure edge parser turning one JSON-RPC line into a typed [`WireFrame`] (`T-PARSE-AT-EDGE`).
1173pub(crate) fn parse_wire_frame(
1174    bytes: &[u8],
1175    hide_always_options: bool,
1176) -> Result<Option<WireFrame>, String> {
1177    let incoming: RawIncoming = serde_json::from_slice(bytes)
1178        .map_err(|error| format!("ACP agent wrote an invalid JSON-RPC message: {error}."))?;
1179    match incoming {
1180        RawIncoming::ServerRequest { id, method, params } => {
1181            if method == "session/request_permission" {
1182                let parsed: RawPermissionParams = serde_json::from_value(params).map_err(|_| {
1183                    "ACP agent sent malformed session/request_permission parameters.".to_owned()
1184                })?;
1185                Ok(Some(WireFrame::PermissionRequest(normalize_permission(
1186                    id,
1187                    parsed,
1188                    hide_always_options,
1189                ))))
1190            } else {
1191                Ok(Some(WireFrame::UnknownServerRequest { id, method }))
1192            }
1193        }
1194        RawIncoming::Notification { method, params } => {
1195            if method != "session/update" {
1196                return Ok(None);
1197            }
1198            let update: RawUpdateNotification = serde_json::from_value(params)
1199                .map_err(|_| "ACP agent sent malformed session/update notification.".to_owned())?;
1200            Ok(
1201                normalize_update(update.update).map(|event| WireFrame::Update {
1202                    session_id: update.session_id,
1203                    event,
1204                }),
1205            )
1206        }
1207        RawIncoming::Result { id, result } => Ok(Some(WireFrame::Response { id, result })),
1208        RawIncoming::Error { id, error } => Ok(Some(WireFrame::Error {
1209            id,
1210            code: error.code,
1211            message: error.message,
1212            data: if error.data.is_null() {
1213                String::new()
1214            } else {
1215                error.data.to_string()
1216            },
1217        })),
1218        RawIncoming::Other(_) => Ok(None),
1219    }
1220}
1221
1222pub(crate) fn initialization_params() -> Value {
1223    json!({
1224        "protocolVersion": PROTOCOL_VERSION,
1225        "clientCapabilities": {
1226            "fs": {
1227                "readTextFile": false,
1228                "writeTextFile": false
1229            },
1230            "terminal": false
1231        },
1232        "clientInfo": {
1233            "name": "artifactize",
1234            "title": "Artifactize",
1235            "version": env!("CARGO_PKG_VERSION"),
1236        }
1237    })
1238}
1239
1240pub(crate) fn permission_selected_reply(id: RpcId, option_id: &str) -> Value {
1241    json!({
1242        "jsonrpc": "2.0",
1243        "id": id,
1244        "result": {
1245            "outcome": {
1246                "outcome": "selected",
1247                "optionId": option_id
1248            }
1249        }
1250    })
1251}
1252
1253pub(crate) fn permission_cancelled_reply(id: RpcId) -> Value {
1254    json!({
1255        "jsonrpc": "2.0",
1256        "id": id,
1257        "result": {
1258            "outcome": {
1259                "outcome": "cancelled"
1260            }
1261        }
1262    })
1263}
1264
1265pub(crate) fn method_not_found_reply(id: RpcId) -> Value {
1266    json!({
1267        "jsonrpc": "2.0",
1268        "id": id,
1269        "error": {
1270            "code": crate::llm::stdio_mcp::METHOD_NOT_FOUND,
1271            "message": "Artifactize does not provide this ACP capability."
1272        }
1273    })
1274}
1275
1276fn listed_with_thought(model: &ListedModel, config: &[ConfigOption]) -> ListedModel {
1277    let base = ListedModel::new(model.slug.clone(), model.display_name.clone());
1278    let Some(option) = config
1279        .iter()
1280        .find(|opt| opt.category == ConfigCategory::ThoughtLevel)
1281    else {
1282        return base;
1283    };
1284    base.with_efforts(
1285        option.choices.iter().map(|choice| choice.value.clone()),
1286        Some(option.current_value.clone()),
1287    )
1288}
1289
1290#[derive(Serialize)]
1291#[serde(rename_all = "camelCase")]
1292struct NewSessionParams<'a> {
1293    #[serde(serialize_with = "crate::platform::path_serde::native::serialize_path")]
1294    cwd: &'a Path,
1295    mcp_servers: &'a [McpServer],
1296}
1297
1298#[derive(Serialize)]
1299#[serde(rename_all = "camelCase")]
1300struct LoadSessionParams<'a> {
1301    session_id: &'a str,
1302    #[serde(serialize_with = "crate::platform::path_serde::native::serialize_path")]
1303    cwd: &'a Path,
1304    mcp_servers: &'a [McpServer],
1305}
1306
1307#[derive(Deserialize)]
1308#[serde(untagged)]
1309enum RawIncoming {
1310    ServerRequest {
1311        id: RpcId,
1312        method: String,
1313        #[serde(default)]
1314        params: Value,
1315    },
1316    Notification {
1317        method: String,
1318        #[serde(default)]
1319        params: Value,
1320    },
1321    Result {
1322        id: u64,
1323        result: Value,
1324    },
1325    Error {
1326        id: u64,
1327        error: RawRpcError,
1328    },
1329    Other(serde::de::IgnoredAny),
1330}
1331
1332#[derive(Deserialize)]
1333struct RawRpcError {
1334    code: i64,
1335    #[serde(default)]
1336    message: String,
1337    #[serde(default)]
1338    data: Value,
1339}
1340
1341#[derive(Deserialize)]
1342#[serde(rename_all = "camelCase")]
1343struct RawInitialized {
1344    protocol_version: u32,
1345    #[serde(default)]
1346    agent_capabilities: RawCapabilities,
1347}
1348
1349#[derive(Default, Deserialize)]
1350#[serde(rename_all = "camelCase")]
1351struct RawCapabilities {
1352    #[serde(default)]
1353    load_session: bool,
1354    #[serde(default)]
1355    mcp_capabilities: RawMcpCapabilities,
1356    #[serde(default)]
1357    auth: RawAuthCapabilities,
1358    #[serde(default, rename = "_meta")]
1359    meta: RawAgentMeta,
1360}
1361
1362#[derive(Default, Deserialize)]
1363struct RawMcpCapabilities {
1364    #[serde(default)]
1365    http: bool,
1366    #[serde(default)]
1367    sse: bool,
1368}
1369
1370#[derive(Default, Deserialize)]
1371struct RawAuthCapabilities {
1372    logout: Option<serde::de::IgnoredAny>,
1373}
1374
1375#[derive(Default, Deserialize)]
1376#[serde(rename_all = "camelCase")]
1377struct RawAgentMeta {
1378    #[serde(default)]
1379    antigravity: RawAntigravityCapabilities,
1380    #[serde(default)]
1381    system_prompt: RawSystemPrompt,
1382}
1383
1384#[derive(Default, Deserialize)]
1385#[serde(rename_all = "camelCase")]
1386struct RawAntigravityCapabilities {
1387    #[serde(default)]
1388    system_prompt: RawSystemPrompt,
1389}
1390
1391#[derive(Default, Deserialize)]
1392struct RawSystemPrompt {
1393    #[serde(default)]
1394    append: bool,
1395}
1396
1397#[derive(Deserialize)]
1398#[serde(rename_all = "camelCase")]
1399struct RawSession {
1400    session_id: String,
1401    #[serde(default)]
1402    config_options: Option<Vec<RawConfigOption>>,
1403    #[serde(default)]
1404    models: Option<RawLegacyModels>,
1405    #[serde(default)]
1406    modes: Option<RawLegacyModes>,
1407}
1408
1409#[derive(Deserialize)]
1410#[serde(rename_all = "camelCase")]
1411struct RawSessionLoadResult {
1412    #[serde(default)]
1413    session_id: Option<String>,
1414    #[serde(default)]
1415    config_options: Option<Vec<RawConfigOption>>,
1416    #[serde(default)]
1417    models: Option<RawLegacyModels>,
1418    #[serde(default)]
1419    modes: Option<RawLegacyModes>,
1420}
1421
1422#[derive(Deserialize)]
1423#[serde(rename_all = "camelCase")]
1424struct RawConfigOptionsReply {
1425    #[serde(default)]
1426    config_options: Vec<RawConfigOption>,
1427}
1428
1429#[derive(Deserialize)]
1430#[serde(rename_all = "camelCase")]
1431struct RawLegacyModels {
1432    #[serde(default)]
1433    current_model_id: String,
1434    #[serde(default)]
1435    available_models: Vec<RawLegacyModelEntry>,
1436}
1437
1438#[derive(Deserialize)]
1439#[serde(rename_all = "camelCase")]
1440struct RawLegacyModelEntry {
1441    model_id: String,
1442    #[serde(default)]
1443    name: Option<String>,
1444    #[serde(default)]
1445    description: Option<String>,
1446}
1447
1448#[derive(Deserialize)]
1449#[serde(rename_all = "camelCase")]
1450struct RawLegacyModes {
1451    #[serde(default)]
1452    current_mode_id: String,
1453    #[serde(default)]
1454    available_modes: Vec<RawLegacyModeEntry>,
1455}
1456
1457#[derive(Deserialize)]
1458#[serde(rename_all = "camelCase")]
1459struct RawLegacyModeEntry {
1460    id: String,
1461    #[serde(default)]
1462    name: Option<String>,
1463    #[serde(default)]
1464    description: Option<String>,
1465}
1466
1467#[derive(Deserialize)]
1468#[serde(tag = "type", rename_all = "snake_case")]
1469enum RawConfigOption {
1470    Select {
1471        id: String,
1472        #[serde(default)]
1473        name: Option<String>,
1474        #[serde(default)]
1475        category: Option<String>,
1476        #[serde(rename = "currentValue")]
1477        current_value: String,
1478        #[serde(default)]
1479        options: Vec<RawChoice>,
1480    },
1481    #[serde(other)]
1482    Other,
1483}
1484
1485#[derive(Deserialize)]
1486#[serde(untagged)]
1487enum RawChoice {
1488    Value {
1489        value: String,
1490        name: String,
1491        #[serde(default)]
1492        description: Option<String>,
1493    },
1494    Group {
1495        options: Vec<RawChoice>,
1496    },
1497    Other(serde::de::IgnoredAny),
1498}
1499
1500fn flatten_choices(raw: &[RawChoice], category: ConfigCategory, out: &mut Vec<ConfigChoice>) {
1501    for item in raw {
1502        match item {
1503            RawChoice::Value {
1504                value,
1505                name,
1506                description,
1507            } => {
1508                if !out.iter().any(|existing| existing.value == *value) {
1509                    out.push(ConfigChoice {
1510                        value: value.clone(),
1511                        name: name.clone(),
1512                        description: description.clone(),
1513                        bypass_warning: category == ConfigCategory::Mode
1514                            && is_bypass_mode(value, name),
1515                    });
1516                }
1517            }
1518            RawChoice::Group { options } => flatten_choices(options, category, out),
1519            RawChoice::Other(_) => {}
1520        }
1521    }
1522}
1523
1524fn is_bypass_mode(value: &str, name: &str) -> bool {
1525    let combined = format!("{value} {name}").to_ascii_lowercase();
1526    [
1527        "bypass",
1528        "yolo",
1529        "dangerously",
1530        "auto_approve",
1531        "auto-approve",
1532        "full_auto",
1533        "full-auto",
1534        "dontask",
1535        "don't ask",
1536    ]
1537    .iter()
1538    .any(|marker| combined.contains(marker))
1539}
1540
1541fn infer_category(id: &str, category: Option<&str>) -> ConfigCategory {
1542    match category {
1543        Some("model") => ConfigCategory::Model,
1544        Some("mode") => ConfigCategory::Mode,
1545        Some("thought_level") => ConfigCategory::ThoughtLevel,
1546        _ => match id {
1547            "model" => ConfigCategory::Model,
1548            "mode" => ConfigCategory::Mode,
1549            "thought_level" | "thinking" | "thinking_level" | "effort" => {
1550                ConfigCategory::ThoughtLevel
1551            }
1552            _ => ConfigCategory::Other,
1553        },
1554    }
1555}
1556
1557fn normalize_config_options(raw: Vec<RawConfigOption>) -> Vec<ConfigOption> {
1558    raw.into_iter()
1559        .filter_map(|opt| match opt {
1560            RawConfigOption::Select {
1561                id,
1562                name,
1563                category,
1564                current_value,
1565                options,
1566            } => {
1567                let category = infer_category(&id, category.as_deref());
1568                let mut choices = Vec::new();
1569                flatten_choices(&options, category, &mut choices);
1570                Some(ConfigOption {
1571                    name: name.unwrap_or_else(|| id.clone()),
1572                    id,
1573                    category,
1574                    current_value,
1575                    choices,
1576                })
1577            }
1578            RawConfigOption::Other => None,
1579        })
1580        .collect()
1581}
1582
1583fn normalize_session(raw: RawSession) -> OpenedSession {
1584    let mut config_options = raw
1585        .config_options
1586        .map(normalize_config_options)
1587        .unwrap_or_default();
1588    let mut uses_legacy_models = false;
1589    let mut uses_legacy_modes = false;
1590
1591    if !config_options
1592        .iter()
1593        .any(|opt| opt.category == ConfigCategory::Model)
1594        && let Some(models) = raw.models
1595    {
1596        uses_legacy_models = true;
1597        config_options.push(ConfigOption {
1598            id: "model".into(),
1599            name: "Model".into(),
1600            category: ConfigCategory::Model,
1601            current_value: models.current_model_id,
1602            choices: models
1603                .available_models
1604                .into_iter()
1605                .map(|entry| ConfigChoice {
1606                    name: entry.name.unwrap_or_else(|| entry.model_id.clone()),
1607                    value: entry.model_id,
1608                    description: entry.description,
1609                    bypass_warning: false,
1610                })
1611                .collect(),
1612        });
1613    }
1614    if !config_options
1615        .iter()
1616        .any(|opt| opt.category == ConfigCategory::Mode)
1617        && let Some(modes) = raw.modes
1618    {
1619        uses_legacy_modes = true;
1620        config_options.push(ConfigOption {
1621            id: "mode".into(),
1622            name: "Mode".into(),
1623            category: ConfigCategory::Mode,
1624            current_value: modes.current_mode_id,
1625            choices: modes
1626                .available_modes
1627                .into_iter()
1628                .map(|entry| {
1629                    let name = entry.name.unwrap_or_else(|| entry.id.clone());
1630                    let bypass_warning = is_bypass_mode(&entry.id, &name);
1631                    ConfigChoice {
1632                        value: entry.id,
1633                        name,
1634                        description: entry.description,
1635                        bypass_warning,
1636                    }
1637                })
1638                .collect(),
1639        });
1640    }
1641
1642    OpenedSession {
1643        session_id: raw.session_id,
1644        config_options,
1645        uses_legacy_models,
1646        uses_legacy_modes,
1647    }
1648}
1649
1650#[derive(Deserialize)]
1651#[serde(rename_all = "camelCase")]
1652struct RawUpdateNotification {
1653    session_id: String,
1654    update: RawUpdate,
1655}
1656
1657#[derive(Deserialize)]
1658#[serde(tag = "sessionUpdate", rename_all = "snake_case")]
1659enum RawUpdate {
1660    AgentMessageChunk {
1661        content: RawContentBlock,
1662    },
1663    AgentThoughtChunk {
1664        content: RawContentBlock,
1665    },
1666    ToolCall {
1667        #[serde(rename = "toolCallId")]
1668        tool_call_id: String,
1669        #[serde(default)]
1670        title: String,
1671        #[serde(default)]
1672        kind: Option<String>,
1673        #[serde(default)]
1674        status: Option<String>,
1675        #[serde(default)]
1676        locations: Vec<RawToolLocation>,
1677        #[serde(default)]
1678        content: Vec<RawToolContent>,
1679    },
1680    ToolCallUpdate {
1681        #[serde(rename = "toolCallId")]
1682        tool_call_id: String,
1683        #[serde(default)]
1684        title: Option<String>,
1685        #[serde(default)]
1686        kind: Option<String>,
1687        #[serde(default)]
1688        status: Option<String>,
1689        #[serde(default)]
1690        locations: Option<Vec<RawToolLocation>>,
1691        #[serde(default)]
1692        content: Option<Vec<RawToolContent>>,
1693    },
1694    Plan {
1695        #[serde(default)]
1696        entries: Vec<RawPlanEntry>,
1697    },
1698    ConfigOptionUpdate {
1699        #[serde(rename = "configOptions", default)]
1700        config_options: Vec<RawConfigOption>,
1701    },
1702    CurrentModeUpdate {
1703        #[serde(rename = "currentModeId", default)]
1704        current_mode_id: String,
1705    },
1706    #[serde(other)]
1707    Other,
1708}
1709
1710#[derive(Deserialize)]
1711#[serde(tag = "type", rename_all = "snake_case")]
1712enum RawContentBlock {
1713    Text {
1714        text: String,
1715    },
1716    #[serde(other)]
1717    Other,
1718}
1719
1720#[derive(Deserialize)]
1721#[serde(rename_all = "camelCase")]
1722struct RawToolLocation {
1723    path: String,
1724    #[serde(default)]
1725    line: Option<u32>,
1726}
1727
1728#[derive(Deserialize)]
1729#[serde(tag = "type", rename_all = "snake_case")]
1730enum RawToolContent {
1731    Content {
1732        content: RawContentBlock,
1733    },
1734    Diff {
1735        path: String,
1736        #[serde(rename = "oldText", default)]
1737        old_text: Option<String>,
1738        #[serde(rename = "newText", default)]
1739        new_text: String,
1740    },
1741    #[serde(other)]
1742    Other,
1743}
1744
1745#[derive(Deserialize)]
1746#[serde(rename_all = "camelCase")]
1747struct RawPlanEntry {
1748    content: String,
1749    #[serde(default)]
1750    status: Option<String>,
1751    #[serde(default)]
1752    priority: Option<String>,
1753}
1754
1755#[derive(Deserialize)]
1756#[serde(rename_all = "camelCase")]
1757struct RawPermissionParams {
1758    session_id: String,
1759    #[serde(default)]
1760    tool_call: Option<RawPermissionToolCall>,
1761    #[serde(default)]
1762    options: Vec<RawPermissionOption>,
1763}
1764
1765#[derive(Deserialize)]
1766#[serde(rename_all = "camelCase")]
1767struct RawPermissionToolCall {
1768    #[serde(default)]
1769    title: Option<String>,
1770    #[serde(default)]
1771    kind: Option<String>,
1772    #[serde(default)]
1773    locations: Vec<RawToolLocation>,
1774    #[serde(default)]
1775    raw_input: Option<Value>,
1776}
1777
1778#[derive(Deserialize)]
1779#[serde(rename_all = "camelCase")]
1780struct RawPermissionOption {
1781    option_id: String,
1782    name: String,
1783    kind: String,
1784}
1785
1786#[derive(Deserialize)]
1787#[serde(rename_all = "camelCase")]
1788struct RawPromptResult {
1789    stop_reason: StopReason,
1790}
1791
1792fn map_tool_kind(kind: Option<&str>) -> ToolKind {
1793    match kind {
1794        Some("read" | "search") => ToolKind::Read,
1795        Some("edit" | "delete" | "move") => ToolKind::Edit,
1796        Some("execute") => ToolKind::Command,
1797        _ => ToolKind::Other,
1798    }
1799}
1800
1801fn map_tool_status(status: Option<&str>) -> Option<ToolStatus> {
1802    match status {
1803        Some("pending") => Some(ToolStatus::Pending),
1804        Some("in_progress" | "running") => Some(ToolStatus::Running),
1805        Some("completed") => Some(ToolStatus::Completed),
1806        Some("failed" | "error") => Some(ToolStatus::Failed),
1807        Some("cancelled" | "canceled") => Some(ToolStatus::Cancelled),
1808        _ => None,
1809    }
1810}
1811
1812fn map_plan_status(status: Option<&str>) -> PlanStepStatus {
1813    match status {
1814        Some("in_progress") => PlanStepStatus::InProgress,
1815        Some("completed") => PlanStepStatus::Completed,
1816        Some("failed") => PlanStepStatus::Failed,
1817        _ => PlanStepStatus::Pending,
1818    }
1819}
1820
1821fn extract_tool_content(items: Vec<RawToolContent>) -> (Option<String>, Option<ToolDiff>, bool) {
1822    let mut output_parts = Vec::new();
1823    let mut diff = None;
1824    for item in items {
1825        match item {
1826            RawToolContent::Content {
1827                content: RawContentBlock::Text { text },
1828            } => output_parts.push(text),
1829            RawToolContent::Diff {
1830                path,
1831                old_text,
1832                new_text,
1833            } => {
1834                let (old_text, new_text, truncated) = bound_diff(old_text, new_text);
1835                diff = Some(ToolDiff {
1836                    path: platform::normalize_external_path(&path),
1837                    old_text,
1838                    new_text,
1839                    truncated,
1840                });
1841            }
1842            _ => {}
1843        }
1844    }
1845    if output_parts.is_empty() {
1846        (None, diff, false)
1847    } else {
1848        let joined = output_parts.join("\n");
1849        let (bounded, truncated) = bound_text(&joined, TOOL_OUTPUT_BYTES);
1850        (Some(bounded), diff, truncated)
1851    }
1852}
1853
1854fn bound_diff(old_text: Option<String>, new_text: String) -> (Option<String>, String, bool) {
1855    let half = DIFF_BYTES / 2;
1856    let (old_bounded, old_trunc) = match old_text {
1857        Some(text) => {
1858            let (b, t) = bound_text(&text, half);
1859            (Some(b), t)
1860        }
1861        None => (None, false),
1862    };
1863    let (new_bounded, new_trunc) = bound_text(&new_text, DIFF_BYTES.saturating_sub(half));
1864    (old_bounded, new_bounded, old_trunc || new_trunc)
1865}
1866
1867pub(crate) fn bound_text(text: &str, max_bytes: usize) -> (String, bool) {
1868    if text.len() <= max_bytes {
1869        return (text.to_owned(), false);
1870    }
1871    let mut end = max_bytes;
1872    while end > 0 && !text.is_char_boundary(end) {
1873        end -= 1;
1874    }
1875    (text[..end].to_owned(), true)
1876}
1877
1878fn normalize_update(raw: RawUpdate) -> Option<SessionEvent> {
1879    match raw {
1880        RawUpdate::AgentMessageChunk {
1881            content: RawContentBlock::Text { text },
1882        } => Some(SessionEvent::AgentMessageChunk { text }),
1883        RawUpdate::AgentThoughtChunk {
1884            content: RawContentBlock::Text { text },
1885        } => Some(SessionEvent::AgentThoughtChunk { text }),
1886        RawUpdate::ToolCall {
1887            tool_call_id,
1888            title,
1889            kind,
1890            status,
1891            locations,
1892            content,
1893        } => {
1894            let (output, diff, output_truncated) = extract_tool_content(content);
1895            let locations: Vec<ToolLocation> = locations
1896                .into_iter()
1897                .map(|loc| ToolLocation {
1898                    path: platform::normalize_external_path(&loc.path),
1899                    line: loc.line,
1900                })
1901                .collect();
1902            let summary = if !title.trim().is_empty() {
1903                title.clone()
1904            } else if let Some(first) = locations.first() {
1905                first.path.clone()
1906            } else {
1907                "Tool call".into()
1908            };
1909            Some(SessionEvent::ToolCall {
1910                call_id: tool_call_id,
1911                title,
1912                tool_kind: map_tool_kind(kind.as_deref()),
1913                status: map_tool_status(status.as_deref()).unwrap_or(ToolStatus::Running),
1914                summary,
1915                locations,
1916                output,
1917                diff,
1918                output_truncated,
1919            })
1920        }
1921        RawUpdate::ToolCallUpdate {
1922            tool_call_id,
1923            title,
1924            kind,
1925            status,
1926            locations,
1927            content,
1928        } => {
1929            let (output, diff, output_truncated) = content
1930                .map(extract_tool_content)
1931                .unwrap_or((None, None, false));
1932            let locations = locations.map(|locs| {
1933                locs.into_iter()
1934                    .map(|loc| ToolLocation {
1935                        path: platform::normalize_external_path(&loc.path),
1936                        line: loc.line,
1937                    })
1938                    .collect()
1939            });
1940            let summary = title.clone();
1941            Some(SessionEvent::ToolCallUpdate {
1942                call_id: tool_call_id,
1943                title,
1944                tool_kind: kind.as_deref().map(|k| map_tool_kind(Some(k))),
1945                status: map_tool_status(status.as_deref()),
1946                summary,
1947                locations,
1948                output,
1949                diff,
1950                output_truncated,
1951            })
1952        }
1953        RawUpdate::Plan { entries } => Some(SessionEvent::Plan {
1954            steps: entries
1955                .into_iter()
1956                .map(|entry| PlanStep {
1957                    content: entry.content,
1958                    status: map_plan_status(entry.status.as_deref()),
1959                    priority: entry.priority,
1960                })
1961                .collect(),
1962        }),
1963        RawUpdate::ConfigOptionUpdate { config_options } => {
1964            Some(SessionEvent::ConfigOptionsUpdated {
1965                options: normalize_config_options(config_options),
1966            })
1967        }
1968        RawUpdate::CurrentModeUpdate { current_mode_id } if !current_mode_id.is_empty() => {
1969            Some(SessionEvent::ModeChanged {
1970                mode_id: current_mode_id,
1971            })
1972        }
1973        _ => None,
1974    }
1975}
1976
1977fn normalize_permission(
1978    rpc_id: RpcId,
1979    raw: RawPermissionParams,
1980    hide_always_options: bool,
1981) -> IncomingPermission {
1982    let tool = raw.tool_call.unwrap_or(RawPermissionToolCall {
1983        title: None,
1984        kind: None,
1985        locations: Vec::new(),
1986        raw_input: None,
1987    });
1988    let title = tool
1989        .title
1990        .filter(|value| !value.trim().is_empty())
1991        .unwrap_or_else(|| "Agent permission request".into());
1992    let tool_kind = map_tool_kind(tool.kind.as_deref());
1993    let summary = if !tool.locations.is_empty() {
1994        let paths: Vec<_> = tool
1995            .locations
1996            .iter()
1997            .map(|loc| {
1998                let path = platform::normalize_external_path(&loc.path);
1999                match loc.line {
2000                    Some(line) => format!("{path}:{line}"),
2001                    None => path,
2002                }
2003            })
2004            .collect();
2005        format!("{title} ({})", paths.join(", "))
2006    } else {
2007        title.clone()
2008    };
2009    let detail = tool.raw_input.and_then(|value| {
2010        if value.is_null() {
2011            return None;
2012        }
2013        let formatted = match value {
2014            Value::String(text) => text,
2015            other => serde_json::to_string_pretty(&other).unwrap_or_else(|_| other.to_string()),
2016        };
2017        let cleaned = platform::clean_program_text(formatted.as_bytes());
2018        let (bounded, _) = bound_text(&cleaned, PERMISSION_DETAIL_BYTES);
2019        (!bounded.trim().is_empty()).then_some(bounded)
2020    });
2021    let options = raw
2022        .options
2023        .into_iter()
2024        .filter_map(|opt| {
2025            let kind = match opt.kind.as_str() {
2026                "allow_once" => PermissionOptionKind::AllowOnce,
2027                "allow_always" => PermissionOptionKind::AllowAlways,
2028                "reject_once" => PermissionOptionKind::RejectOnce,
2029                "reject_always" => PermissionOptionKind::RejectAlways,
2030                _ => return None,
2031            };
2032            if hide_always_options && kind.may_persist_in_agent_settings() {
2033                return None;
2034            }
2035            Some(PermissionOption {
2036                option_id: opt.option_id,
2037                name: opt.name,
2038                kind,
2039                persists_in_agent_settings: kind.may_persist_in_agent_settings(),
2040            })
2041        })
2042        .collect();
2043    IncomingPermission {
2044        rpc_id,
2045        session_id: raw.session_id,
2046        title,
2047        tool_kind,
2048        summary,
2049        detail,
2050        options,
2051    }
2052}
2053
2054#[cfg(test)]
2055mod tests {
2056    use super::*;
2057
2058    /// ACP v1 JSON Schema contract test for outbound client messages (`initialize`,
2059    /// permission responses, method-not-found) and inbound updates.
2060    #[test]
2061    fn acp_v1_schema_contract_validates_outbound_and_inbound_frames() {
2062        let init_schema = json!({
2063            "type": "object",
2064            "required": ["protocolVersion", "clientCapabilities", "clientInfo"],
2065            "properties": {
2066                "protocolVersion": { "const": 1 },
2067                "clientCapabilities": {
2068                    "type": "object",
2069                    "properties": {
2070                        "fs": {
2071                            "type": "object",
2072                            "properties": {
2073                                "readTextFile": { "const": false },
2074                                "writeTextFile": { "const": false }
2075                            },
2076                            "required": ["readTextFile", "writeTextFile"]
2077                        },
2078                        "terminal": { "const": false }
2079                    },
2080                    "required": ["fs", "terminal"]
2081                },
2082                "clientInfo": {
2083                    "type": "object",
2084                    "required": ["name", "version"]
2085                }
2086            }
2087        });
2088        let validator = jsonschema::validator_for(&init_schema).unwrap();
2089        assert!(validator.is_valid(&initialization_params()));
2090
2091        let perm_reply_schema = json!({
2092            "type": "object",
2093            "required": ["jsonrpc", "id", "result"],
2094            "properties": {
2095                "jsonrpc": { "const": "2.0" },
2096                "result": {
2097                    "type": "object",
2098                    "required": ["outcome"],
2099                    "properties": {
2100                        "outcome": {
2101                            "oneOf": [
2102                                {
2103                                    "type": "object",
2104                                    "required": ["outcome", "optionId"],
2105                                    "properties": {
2106                                        "outcome": { "const": "selected" },
2107                                        "optionId": { "type": "string", "minLength": 1 }
2108                                    }
2109                                },
2110                                {
2111                                    "type": "object",
2112                                    "required": ["outcome"],
2113                                    "properties": {
2114                                        "outcome": { "const": "cancelled" }
2115                                    }
2116                                }
2117                            ]
2118                        }
2119                    }
2120                }
2121            }
2122        });
2123        let perm_validator = jsonschema::validator_for(&perm_reply_schema).unwrap();
2124        assert!(
2125            perm_validator.is_valid(&permission_selected_reply(RpcId::Number(7), "allow-once"))
2126        );
2127        assert!(perm_validator.is_valid(&permission_cancelled_reply(RpcId::Number(8))));
2128
2129        // Inbound tool_call + diff + thought + plan + permission parsing at the edge.
2130        let thought_line = json!({
2131            "jsonrpc": "2.0",
2132            "method": "session/update",
2133            "params": {
2134                "sessionId": "s1",
2135                "update": {
2136                    "sessionUpdate": "agent_thought_chunk",
2137                    "content": { "type": "text", "text": "Analyzing diff..." }
2138                }
2139            }
2140        });
2141        let frame = parse_wire_frame(thought_line.to_string().as_bytes(), false)
2142            .unwrap()
2143            .unwrap();
2144        assert!(matches!(
2145            frame,
2146            WireFrame::Update {
2147                event: SessionEvent::AgentThoughtChunk { text },
2148                ..
2149            } if text == "Analyzing diff..."
2150        ));
2151
2152        let perm_line = json!({
2153            "jsonrpc": "2.0",
2154            "id": 99,
2155            "method": "session/request_permission",
2156            "params": {
2157                "sessionId": "s1",
2158                "toolCall": {
2159                    "title": "Run cargo test",
2160                    "kind": "execute",
2161                    "rawInput": { "cmd": "cargo test" }
2162                },
2163                "options": [
2164                    { "optionId": "once", "name": "Allow once", "kind": "allow_once" },
2165                    { "optionId": "always", "name": "Always allow", "kind": "allow_always" }
2166                ]
2167            }
2168        });
2169        let frame = parse_wire_frame(perm_line.to_string().as_bytes(), false)
2170            .unwrap()
2171            .unwrap();
2172        let WireFrame::PermissionRequest(req) = frame else {
2173            panic!("expected permission request");
2174        };
2175        assert_eq!(req.options.len(), 2);
2176        assert!(!req.options[0].persists_in_agent_settings);
2177        assert!(req.options[1].persists_in_agent_settings);
2178
2179        // When a preset hides always options with unverified persistence scopes:
2180        let frame_hidden = parse_wire_frame(perm_line.to_string().as_bytes(), true)
2181            .unwrap()
2182            .unwrap();
2183        let WireFrame::PermissionRequest(req_hidden) = frame_hidden else {
2184            panic!("expected permission request");
2185        };
2186        assert_eq!(req_hidden.options.len(), 1);
2187        assert_eq!(req_hidden.options[0].option_id, "once");
2188
2189        // Unknown server request maps to UnknownServerRequest (answered with -32601).
2190        let unknown = json!({
2191            "jsonrpc": "2.0",
2192            "id": 12,
2193            "method": "fs/read_text_file",
2194            "params": {}
2195        });
2196        let frame = parse_wire_frame(unknown.to_string().as_bytes(), false)
2197            .unwrap()
2198            .unwrap();
2199        assert!(matches!(
2200            frame,
2201            WireFrame::UnknownServerRequest { method, .. } if method == "fs/read_text_file"
2202        ));
2203    }
2204
2205    #[test]
2206    fn normalize_session_handles_legacy_models_and_modes_with_bypass_flag() {
2207        let raw: RawSession = serde_json::from_value(json!({
2208            "sessionId": "s-legacy",
2209            "models": {
2210                "currentModelId": "m1",
2211                "availableModels": [{ "modelId": "m1", "name": "Model One" }]
2212            },
2213            "modes": {
2214                "currentModeId": "ask",
2215                "availableModes": [
2216                    { "id": "ask", "name": "Ask" },
2217                    { "id": "bypassPermissions", "name": "Bypass Permissions" }
2218                ]
2219            }
2220        }))
2221        .unwrap();
2222        let session = normalize_session(raw);
2223        assert!(session.uses_legacy_models);
2224        assert!(session.uses_legacy_modes);
2225        let mode = session
2226            .config_options
2227            .iter()
2228            .find(|opt| opt.category == ConfigCategory::Mode)
2229            .unwrap();
2230        assert!(!mode.choices[0].bypass_warning);
2231        assert!(mode.choices[1].bypass_warning);
2232    }
2233
2234    #[test]
2235    fn legacy_mode_confirmation_requires_reported_mode_and_rpc_errors_redact_secrets() {
2236        assert_eq!(extract_confirmed_legacy_mode(&json!({})), None);
2237        assert_eq!(
2238            extract_confirmed_legacy_mode(&json!({ "currentModeId": "ask" })),
2239            Some("ask".into())
2240        );
2241        assert_eq!(
2242            extract_confirmed_legacy_mode(&json!({ "modes": { "currentModeId": "plan" } })),
2243            Some("plan".into())
2244        );
2245
2246        let redactor = StreamRedactor::new(["sk-acp-super-secret-value-999".to_owned()]);
2247        let problem = classify_rpc_error(
2248            "Fixture",
2249            "sign in",
2250            &redactor,
2251            "session/prompt",
2252            -32001,
2253            "Upstream refused key sk-acp-super-secret-value-999 immediately",
2254            "",
2255        );
2256        let Problem::Failed(msg) = problem else {
2257            panic!("expected Problem::Failed, got {problem:?}");
2258        };
2259        assert!(!msg.contains("sk-acp-super-secret-value-999"), "{msg}");
2260        assert!(msg.contains("[REDACTED]"), "{msg}");
2261    }
2262}