Skip to main content

ertangle_adapter/
codex.rs

1//! Native adapter for Codex (`codex app-server`).
2//!
3//! Codex's app server is JSON-RPC over stdio (experimental, but has a stable and self-describing interface:
4//! `codex app-server generate-json-schema` outputs the complete schema).
5//!
6//! Subset used:
7//! * `initialize`
8//! * `thread/start` → `thread.id`
9//! * `turn/start` (with `input`)
10//! * `turn/interrupt`
11//! * Notifications: `item/agentMessage/delta`, `item/completed`, `turn/completed`,
12//!   `thread/tokenUsage/updated`
13//! * Approvals (server→client requests): `item/commandExecution/requestApproval`,
14//!   `item/fileChange/requestApproval`
15
16use crate::stream::StreamBuf;
17use crate::{AgentControl, AgentEvent, SessionSpec};
18use anyhow::{anyhow, bail, Context, Result};
19use ertangle_core::{
20    new_id, Cost, Decision, PermissionRequest, QuestionOption, SessionStatus, UserQuestion,
21};
22use serde_json::{json, Value};
23use std::collections::HashMap;
24use std::io::{BufRead, BufReader, Write};
25use std::process::{Child, ChildStdin, Command, Stdio};
26use std::sync::atomic::{AtomicI64, Ordering};
27use std::sync::mpsc::{self, Sender};
28use std::sync::{Arc, Mutex};
29use std::time::Duration;
30use tr::tr;
31
32const CALL_TIMEOUT: Duration = Duration::from_secs(60);
33
34/// Collected answers for a multi-field elicitation: field key -> (multi-select, answers).
35type ElicitationAnswers = Arc<Mutex<HashMap<String, (bool, Vec<String>)>>>;
36
37struct PendingQuestion {
38    rpc_id: Value,
39    method: String,
40    q_key: String,
41    multi_select: bool,
42    total: usize,
43    answers: ElicitationAnswers,
44}
45
46/// Codex `-c` override that approves every tool of our own MCP server without a prompt.
47///
48/// Must target `mcp_servers.<id>`: the `apps.<id>` table only configures connectors, and the
49/// default `auto` mode still prompts for tools not annotated read-only (`ertangle_send`, ...).
50const AUTO_APPROVE_ERTANGLE_MCP: &str =
51    "mcp_servers.ertangle.default_tools_approval_mode=\"approve\"";
52
53/// Key `parse_acp_elicitations` gives to a form-less prompt (e.g. an MCP tool-call approval).
54const CONFIRM_KEY: &str = "answer";
55const CONFIRM_ALLOW: &str = "Allow";
56const CONFIRM_DENY: &str = "Deny";
57
58/// A form-less elicitation is a plain confirmation: offer Allow / Deny instead of
59/// making the user type a free-form answer.
60fn add_confirm_options(list: &mut [(UserQuestion, String)]) {
61    for (q, key) in list.iter_mut() {
62        if key == CONFIRM_KEY && q.options.is_empty() && !q.multi_select {
63            q.options = vec![
64                QuestionOption::plain(CONFIRM_ALLOW),
65                QuestionOption::plain(CONFIRM_DENY),
66            ];
67        }
68    }
69}
70
71/// Builds elicitation form content that conforms to the schema.
72fn elicitation_content(entries: &[(String, bool, Vec<String>)]) -> Value {
73    let mut content = serde_json::Map::new();
74    for (key, multi_select, answers) in entries {
75        let value = if !multi_select && answers.len() == 1 {
76            json!(answers[0])
77        } else {
78            json!(answers)
79        };
80        content.insert(key.clone(), value);
81    }
82    Value::Object(content)
83}
84
85/// Build the JSON-RPC result for Codex `item/tool/requestUserInput`.
86fn user_input_answer_result(answers: &[String], key: &str) -> Value {
87    let mut answers_by_id = serde_json::Map::new();
88    if !answers.is_empty() {
89        answers_by_id.insert(
90            key.to_string(),
91            json!({ "answers": answers, "other": null }),
92        );
93    }
94    json!({ "answers": answers_by_id })
95}
96
97struct Conn {
98    session_id: String,
99    stdin: Mutex<ChildStdin>,
100    next_id: AtomicI64,
101    pending: Mutex<HashMap<i64, Sender<Value>>>,
102    /// Approvals: internal req id -> JSON-RPC id.
103    perms: Mutex<HashMap<String, Value>>,
104    /// Interactive questions: internal qst id -> pending question info.
105    questions: Mutex<HashMap<String, PendingQuestion>>,
106    /// Current thread / turn id.
107    thread: Mutex<String>,
108    turn: Mutex<String>,
109    stream: Mutex<StreamBuf>,
110    /// Error text already reported in this turn (avoid duplicate reporting between `error` notifications and `turn/completed`).
111    last_error: Mutex<Option<String>>,
112    tx: Sender<AgentEvent>,
113}
114
115impl Conn {
116    fn write(&self, v: &Value) -> Result<()> {
117        let mut line = serde_json::to_string(v)?;
118        line.push('\n');
119        let mut w = self.stdin.lock().unwrap_or_else(|e| e.into_inner());
120        w.write_all(line.as_bytes())?;
121        w.flush()?;
122        Ok(())
123    }
124
125    /// Sends a request and waits for response.
126    fn call(&self, method: &str, params: Value, timeout: Duration) -> Result<Value> {
127        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
128        let (s, r) = mpsc::channel();
129        self.pending
130            .lock()
131            .unwrap_or_else(|e| e.into_inner())
132            .insert(id, s);
133        self.write(&json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}))?;
134        let msg = r
135            .recv_timeout(timeout)
136            .map_err(|_| anyhow!(tr!("`{method}` 逾時", method = method)))?;
137        if let Some(err) = msg.get("error") {
138            bail!(
139                "{}",
140                tr!("`{method}` 失敗:{err}", method = method, err = err)
141            );
142        }
143        Ok(msg.get("result").cloned().unwrap_or(Value::Null))
144    }
145
146    fn flush_stream(&self) {
147        let text = self
148            .stream
149            .lock()
150            .unwrap_or_else(|e| e.into_inner())
151            .flush();
152        if !text.is_empty() {
153            let _ = self.tx.send(AgentEvent::Output(text));
154        }
155    }
156
157    /// Processes a single stdout line.
158    fn on_line(&self, line: &str) {
159        let Ok(msg) = serde_json::from_str::<Value>(line) else {
160            return;
161        };
162        // 1) Response to a request we sent.
163        if let Some(id) = msg.get("id") {
164            if msg.get("method").is_none() {
165                let id = id.as_i64().unwrap_or(-1);
166                if let Some(s) = self
167                    .pending
168                    .lock()
169                    .unwrap_or_else(|e| e.into_inner())
170                    .remove(&id)
171                {
172                    let _ = s.send(msg);
173                }
174                return;
175            }
176        }
177        let method = msg["method"].as_str().unwrap_or("");
178        // 2) Server -> client requests (requiring our response).
179        if msg.get("id").is_some() && !method.is_empty() {
180            self.on_server_request(method, &msg);
181            return;
182        }
183        // 3) Notifications.
184        self.on_notification(method, &msg["params"]);
185    }
186
187    fn on_server_request(&self, method: &str, msg: &Value) {
188        let params = &msg["params"];
189        if method == "item/tool/requestUserInput" {
190            let list = crate::question::parse_codex_user_inputs(&self.session_id, params);
191            if !list.is_empty() {
192                let id = msg.get("id").cloned().unwrap_or(Value::Null);
193                let total = list.len();
194                let shared_answers = Arc::new(Mutex::new(HashMap::new()));
195                let mut q_map = self.questions.lock().unwrap_or_else(|e| e.into_inner());
196                for (q, q_key) in list {
197                    q_map.insert(
198                        q.id.clone(),
199                        PendingQuestion {
200                            rpc_id: id.clone(),
201                            method: method.to_string(),
202                            q_key,
203                            multi_select: q.multi_select,
204                            total,
205                            answers: Arc::clone(&shared_answers),
206                        },
207                    );
208                    let _ = self.tx.send(AgentEvent::Question(q));
209                }
210                return;
211            }
212        }
213        if method == "mcpServer/elicitation/request"
214            && (params.get("requestedSchema").is_some() || params.get("options").is_some())
215        {
216            let mut list = crate::question::parse_acp_elicitations(&self.session_id, params);
217            add_confirm_options(&mut list);
218            if !list.is_empty() {
219                let id = msg.get("id").cloned().unwrap_or(Value::Null);
220                let total = list.len();
221                let shared_answers = Arc::new(Mutex::new(HashMap::new()));
222                let mut q_map = self.questions.lock().unwrap_or_else(|e| e.into_inner());
223                for (q, q_key) in list {
224                    let mut answers = shared_answers.lock().unwrap_or_else(|e| e.into_inner());
225                    answers.insert(q_key.clone(), (q.multi_select, Vec::new()));
226                    drop(answers);
227                    q_map.insert(
228                        q.id.clone(),
229                        PendingQuestion {
230                            rpc_id: id.clone(),
231                            method: method.to_string(),
232                            q_key,
233                            multi_select: q.multi_select,
234                            total,
235                            answers: Arc::clone(&shared_answers),
236                        },
237                    );
238                    let _ = self.tx.send(AgentEvent::Question(q));
239                }
240                return;
241            }
242        }
243        let (title, detail, kind) = match method {
244            "item/commandExecution/requestApproval" | "execCommandApproval" => {
245                let cmd = params["command"].as_str().unwrap_or("(command)");
246                let cwd = params["cwd"].as_str().unwrap_or("");
247                (
248                    "Bash".to_string(),
249                    format!("{cmd}\n({cwd})"),
250                    ApprovalKind::Command,
251                )
252            }
253            "item/fileChange/requestApproval" | "applyPatchApproval" => {
254                let reason = params["reason"].as_str().unwrap_or("file change");
255                ("Edit".to_string(), reason.to_string(), ApprovalKind::File)
256            }
257            "mcpServer/elicitation/request" => {
258                let tool_name = params["_meta"]["tool_name"]
259                    .as_str()
260                    .or_else(|| params["serverName"].as_str())
261                    .unwrap_or("tool");
262                let msg_text = params["message"]
263                    .as_str()
264                    .unwrap_or("MCP tool call approval");
265                (
266                    format!("MCP ({tool_name})"),
267                    msg_text.to_string(),
268                    ApprovalKind::McpElicitation,
269                )
270            }
271            "item/permissions/requestApproval" => {
272                let reason = params["reason"].as_str().unwrap_or("permissions request");
273                (
274                    "Permissions".to_string(),
275                    reason.to_string(),
276                    ApprovalKind::Permissions,
277                )
278            }
279            other => {
280                // Always return an error for unrecognized requests to prevent Codex from hanging.
281                let id = msg.get("id").cloned().unwrap_or(Value::Null);
282                let _ = self.write(&json!({
283                    "jsonrpc":"2.0","id":id,
284                    "error":{"code":-32601,"message":format!("ertangle 不支援 {other}")}
285                }));
286                return;
287            }
288        };
289        let req = new_id("perm");
290        let id = msg.get("id").cloned().unwrap_or(Value::Null);
291        self.perms
292            .lock()
293            .unwrap_or_else(|e| e.into_inner())
294            .insert(req.clone(), json!({"id": id, "kind": kind.as_str()}));
295        let _ = self.tx.send(AgentEvent::Permission(PermissionRequest {
296            req,
297            session: self.session_id.clone(),
298            title,
299            detail,
300        }));
301    }
302
303    fn on_notification(&self, method: &str, p: &Value) {
304        match method {
305            "item/agentMessage/delta" => {
306                if let Some(d) = p["delta"].as_str() {
307                    let out = self
308                        .stream
309                        .lock()
310                        .unwrap_or_else(|e| e.into_inner())
311                        .push("msg", d);
312                    if !out.is_empty() {
313                        let _ = self.tx.send(AgentEvent::Output(out));
314                    }
315                }
316            }
317            "item/reasoning/textDelta" | "item/reasoning/summaryTextDelta" => {
318                let key = if p.get("delta").is_some() {
319                    "delta"
320                } else {
321                    "textDelta"
322                };
323                if let Some(d) = p[key].as_str() {
324                    let out = self
325                        .stream
326                        .lock()
327                        .unwrap_or_else(|e| e.into_inner())
328                        .push("think", d);
329                    if !out.is_empty() {
330                        let _ = self.tx.send(AgentEvent::Output(out));
331                    }
332                }
333            }
334            "turn/started" => {
335                if let Some(id) = p["turn"]["id"].as_str() {
336                    *self.turn.lock().unwrap_or_else(|e| e.into_inner()) = id.to_string();
337                }
338                *self.last_error.lock().unwrap_or_else(|e| e.into_inner()) = None;
339                let _ = self.tx.send(AgentEvent::Status(SessionStatus::Busy));
340            }
341            "turn/completed" => {
342                self.flush_stream();
343                let failed = !p["turn"]["error"].is_null();
344                if failed {
345                    self.report_error(&p["turn"]["error"]);
346                }
347                let _ = self.tx.send(AgentEvent::Status(if failed {
348                    SessionStatus::Failed
349                } else {
350                    SessionStatus::Idle
351                }));
352            }
353            "item/completed" => self.on_item_completed(&p["item"]),
354            "thread/tokenUsage/updated" => {
355                let last = &p["tokenUsage"]["last"];
356                if let Some(used) = last["totalTokens"].as_u64() {
357                    let _ = self.tx.send(AgentEvent::Context {
358                        used,
359                        window: p["tokenUsage"]["modelContextWindow"].as_u64(),
360                    });
361                }
362                let total = &p["tokenUsage"]["total"];
363                let cost = Cost {
364                    usd: 0.0,
365                    input_tokens: total["inputTokens"].as_u64().unwrap_or(0),
366                    output_tokens: total["outputTokens"].as_u64().unwrap_or(0),
367                };
368                let _ = self.tx.send(AgentEvent::Cost(cost));
369            }
370            "account/rateLimits/updated" => {
371                if let Some(q) = parse_rate_limits(&p["rateLimits"]) {
372                    let _ = self.tx.send(AgentEvent::Quota(q));
373                }
374            }
375            "thread/started" => {
376                if let Some(id) = p["thread"]["id"].as_str() {
377                    *self.thread.lock().unwrap_or_else(|e| e.into_inner()) = id.to_string();
378                }
379            }
380            "error" => {
381                tracing::warn!("codex error 通知:{}", p);
382                // When `willRetry: true`, Codex retries automatically; not considered failure, don't disturb the user.
383                if p["willRetry"].as_bool() != Some(true) {
384                    let err = if p["error"].is_null() { p } else { &p["error"] };
385                    self.report_error(err);
386                }
387            }
388            _ => {}
389        }
390    }
391
392    /// Forwards Codex errors (`error` from `error` notifications, or `turn.error`) to transcript and status note.
393    /// Reports identical text only once per turn.
394    fn report_error(&self, err: &Value) {
395        let text = error_text(err);
396        {
397            let mut last = self.last_error.lock().unwrap_or_else(|e| e.into_inner());
398            if last.as_deref() == Some(text.as_str()) {
399                return;
400            }
401            *last = Some(text.clone());
402        }
403        if ertangle_core::looks_like_limit(&text) {
404            let _ = self.tx.send(AgentEvent::Limited(text));
405            return;
406        }
407        let mut note = tr!("codex 錯誤:{text}", text = text);
408        if is_auth_error(err) {
409            note.push_str(&tr!("(請執行 `codex login`)"));
410        }
411        let _ = self.tx.send(AgentEvent::Output(format!("⚠ {note}\n")));
412        let _ = self.tx.send(AgentEvent::Note(note));
413    }
414
415    fn on_item_completed(&self, item: &Value) {
416        match item["type"].as_str().unwrap_or("") {
417            "commandExecution" => {
418                self.flush_stream();
419                let _ = self.tx.send(AgentEvent::ToolCall {
420                    name: "Bash".to_string(),
421                    input: item["command"].as_str().unwrap_or("").to_string(),
422                    ok: item["exitCode"].as_i64().map(|c| c == 0),
423                    output: item["aggregatedOutput"].as_str().map(|s| s.to_string()),
424                });
425            }
426            "fileChange" => {
427                self.flush_stream();
428                let _ = self.tx.send(AgentEvent::ToolCall {
429                    name: "Edit".to_string(),
430                    input: item["changes"].to_string(),
431                    ok: Some(item["status"].as_str() == Some("completed")),
432                    output: None,
433                });
434            }
435            "mcpToolCall" | "McpToolCall" => {
436                self.flush_stream();
437                let tool = item["tool"].as_str().unwrap_or("mcp");
438                let server = item["server"].as_str().unwrap_or("");
439                let name = if server.is_empty() {
440                    tool.to_string()
441                } else {
442                    format!("{server}:{tool}")
443                };
444                let ok = item["status"].as_str().map(|s| s == "completed");
445                let output = item["result"]["content"].as_array().and_then(|arr| {
446                    let texts: Vec<&str> = arr.iter().filter_map(|c| c["text"].as_str()).collect();
447                    if texts.is_empty() {
448                        None
449                    } else {
450                        Some(texts.join("\n"))
451                    }
452                });
453                let _ = self.tx.send(AgentEvent::ToolCall {
454                    name,
455                    input: item["arguments"].to_string(),
456                    ok,
457                    output,
458                });
459            }
460            "agentMessage" => {
461                // Text was already emitted via deltas; here only finalize.
462                self.flush_stream();
463            }
464            _ => {}
465        }
466    }
467}
468
469/// Error text: prefers `message`, otherwise uses the first 300 characters of the full JSON.
470fn error_text(err: &Value) -> String {
471    match err["message"].as_str().filter(|m| !m.is_empty()) {
472        Some(m) => m.to_string(),
473        None => err.to_string().chars().take(300).collect(),
474    }
475}
476
477/// Whether this is an authentication error (401, token revoked, unauthorized).
478fn is_auth_error(err: &Value) -> bool {
479    let t = err.to_string().to_ascii_lowercase();
480    t.contains("401") || t.contains("token_revoked") || t.contains("unauthorized")
481}
482
483#[derive(Clone, Copy, Debug, PartialEq, Eq)]
484enum ApprovalKind {
485    Command,
486    File,
487    McpElicitation,
488    Permissions,
489}
490
491impl ApprovalKind {
492    fn as_str(self) -> &'static str {
493        match self {
494            ApprovalKind::Command => "command",
495            ApprovalKind::File => "file",
496            ApprovalKind::McpElicitation => "mcp_elicitation",
497            ApprovalKind::Permissions => "permissions",
498        }
499    }
500}
501
502// ---------------------------------------------------------------------------
503// Control handle
504// ---------------------------------------------------------------------------
505
506struct CodexControl {
507    conn: Arc<Conn>,
508    child: Arc<Mutex<Child>>,
509    /// Runtime switched model/effort; included in every `turn/start`.
510    overrides: Mutex<(Option<String>, Option<String>)>,
511}
512
513impl CodexControl {
514    fn thread_id(&self) -> Result<String> {
515        let t = self
516            .conn
517            .thread
518            .lock()
519            .unwrap_or_else(|e| e.into_inner())
520            .clone();
521        if t.is_empty() {
522            bail!("{}", tr!("codex thread 尚未就緒"));
523        }
524        Ok(t)
525    }
526}
527
528impl AgentControl for CodexControl {
529    fn send_input(&self, text: &str) -> Result<()> {
530        self.send_input_with(text, &[])
531    }
532
533    fn send_input_with(&self, text: &str, atts: &[ertangle_core::Attachment]) -> Result<()> {
534        let thread_id = self.thread_id()?;
535        let _ = self.conn.tx.send(AgentEvent::Status(SessionStatus::Busy));
536        let mut params = json!({
537            "threadId": thread_id,
538            "input": turn_input(text, atts)
539        });
540        let (m, e) = self
541            .overrides
542            .lock()
543            .unwrap_or_else(|e| e.into_inner())
544            .clone();
545        if let Some(m) = m {
546            params["model"] = json!(m);
547        }
548        if let Some(e) = e {
549            params["effort"] = json!(e);
550        }
551        self.conn.call("turn/start", params, CALL_TIMEOUT)?;
552        Ok(())
553    }
554
555    /// Saved to pass `model`/`effort` in the next `turn/start` (schema confirms both are `TurnStartParams` fields).
556    fn set_config(&self, model: Option<&str>, effort: Option<&str>) -> Result<Option<String>> {
557        if let Some(e) = effort {
558            crate::check_effort(e)?;
559        }
560        let mut o = self.overrides.lock().unwrap_or_else(|e| e.into_inner());
561        if let Some(m) = model {
562            o.0 = Some(m.to_string());
563        }
564        if let Some(e) = effort {
565            o.1 = Some(e.to_string());
566        }
567        Ok(model.map(str::to_string))
568    }
569
570    fn cancel(&self) -> Result<()> {
571        let thread_id = self.thread_id()?;
572        let turn_id = self
573            .conn
574            .turn
575            .lock()
576            .unwrap_or_else(|e| e.into_inner())
577            .clone();
578        if turn_id.is_empty() {
579            return Ok(());
580        }
581        self.conn.call(
582            "turn/interrupt",
583            json!({ "threadId": thread_id, "turnId": turn_id }),
584            CALL_TIMEOUT,
585        )?;
586        Ok(())
587    }
588
589    fn pid(&self) -> Option<u32> {
590        Some(self.child.lock().unwrap_or_else(|e| e.into_inner()).id())
591    }
592
593    fn kill(&self) -> Result<()> {
594        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
595        let _ = crate::signal_pgid(pid, "-KILL").or_else(|_| crate::signal_pid(pid, "-KILL"));
596        self.child
597            .lock()
598            .unwrap_or_else(|e| e.into_inner())
599            .kill()
600            .ok();
601        Ok(())
602    }
603
604    fn sleep(&self) -> Result<()> {
605        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
606        crate::signal_pgid(pid, "-STOP").or_else(|_| crate::signal_pid(pid, "-STOP"))
607    }
608
609    fn wake(&self) -> Result<()> {
610        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
611        crate::signal_pgid(pid, "-CONT").or_else(|_| crate::signal_pid(pid, "-CONT"))
612    }
613
614    fn resolve_permission(&self, req: &str, decision: Decision) -> Result<()> {
615        let entry = self
616            .conn
617            .perms
618            .lock()
619            .unwrap_or_else(|e| e.into_inner())
620            .remove(req);
621        let Some(entry) = entry else {
622            bail!("{}", tr!("未知的核准請求:{req}", req = req));
623        };
624        let id = entry.get("id").cloned().unwrap_or(Value::Null);
625        let kind = match entry["kind"].as_str() {
626            Some("file") => ApprovalKind::File,
627            Some("mcp_elicitation") => ApprovalKind::McpElicitation,
628            Some("permissions") => ApprovalKind::Permissions,
629            _ => ApprovalKind::Command,
630        };
631        match kind {
632            ApprovalKind::McpElicitation => {
633                let result = match decision {
634                    Decision::Allow | Decision::AllowAlways => json!({
635                        "action": "accept",
636                        "content": {}
637                    }),
638                    Decision::Deny => json!({
639                        "action": "decline"
640                    }),
641                };
642                self.conn.write(&json!({
643                    "jsonrpc": "2.0",
644                    "id": id,
645                    "result": result
646                }))
647            }
648            ApprovalKind::Permissions => {
649                let result = match decision {
650                    Decision::Allow | Decision::AllowAlways => json!({
651                        "permissions": {},
652                        "scope": "turn"
653                    }),
654                    Decision::Deny => json!({
655                        "permissions": null
656                    }),
657                };
658                self.conn.write(&json!({
659                    "jsonrpc": "2.0",
660                    "id": id,
661                    "result": result
662                }))
663            }
664            ApprovalKind::Command | ApprovalKind::File => {
665                // Codex decision is a camelCase string.
666                let verdict = match (kind, decision) {
667                    (_, Decision::Allow) => "accept",
668                    (_, Decision::AllowAlways) => "acceptForSession",
669                    (_, Decision::Deny) => "decline",
670                };
671                self.conn.write(&json!({
672                    "jsonrpc": "2.0",
673                    "id": id,
674                    "result": { "decision": verdict }
675                }))
676            }
677        }
678    }
679
680    fn resolve_question(&self, id: &str, answers: &[String]) -> Result<()> {
681        let entry = self
682            .conn
683            .questions
684            .lock()
685            .unwrap_or_else(|e| e.into_inner())
686            .remove(id);
687        let Some(PendingQuestion {
688            rpc_id,
689            method,
690            q_key,
691            multi_select,
692            total,
693            answers: shared_answers,
694        }) = entry
695        else {
696            bail!("{}", tr!("未知的問題請求:{id}", id = id));
697        };
698
699        let denied = q_key == CONFIRM_KEY && answers == [CONFIRM_DENY];
700        if answers.is_empty() || denied {
701            let mut q_map = self
702                .conn
703                .questions
704                .lock()
705                .unwrap_or_else(|e| e.into_inner());
706            q_map.retain(|_, v| v.rpc_id != rpc_id);
707            drop(q_map);
708
709            let result = if method == "item/tool/requestUserInput" {
710                json!({ "answers": {} })
711            } else {
712                json!({ "action": "decline" })
713            };
714            return self.conn.write(&json!({
715                "jsonrpc": "2.0",
716                "id": rpc_id,
717                "result": result
718            }));
719        }
720
721        let mut map = shared_answers.lock().unwrap_or_else(|e| e.into_inner());
722        map.insert(q_key, (multi_select, answers.to_vec()));
723        if map.len() == total {
724            let mut q_map = self
725                .conn
726                .questions
727                .lock()
728                .unwrap_or_else(|e| e.into_inner());
729            q_map.retain(|_, v| v.rpc_id != rpc_id);
730            drop(q_map);
731
732            if method == "item/tool/requestUserInput" {
733                let result = if map.len() == 1 {
734                    if let Some((k, (_, ans))) = map.iter().next() {
735                        user_input_answer_result(ans, k)
736                    } else {
737                        json!({ "answers": {} })
738                    }
739                } else {
740                    let mut answers_by_id = serde_json::Map::new();
741                    for (k, (_, ans)) in map.iter() {
742                        answers_by_id.insert(k.clone(), json!({ "answers": ans, "other": null }));
743                    }
744                    json!({ "answers": answers_by_id })
745                };
746                self.conn.write(&json!({
747                    "jsonrpc": "2.0",
748                    "id": rpc_id,
749                    "result": result
750                }))
751            } else {
752                let entries: Vec<(String, bool, Vec<String>)> = map
753                    .iter()
754                    .map(|(k, (multi, ans))| (k.clone(), *multi, ans.clone()))
755                    .collect();
756                drop(map);
757                self.conn.write(&json!({
758                    "jsonrpc": "2.0",
759                    "id": rpc_id,
760                    "result": {
761                        "action": "accept",
762                        "content": elicitation_content(&entries)
763                    }
764                }))
765            }
766        } else {
767            Ok(())
768        }
769    }
770
771    fn transport(&self) -> &'static str {
772        "app-server"
773    }
774}
775
776// ---------------------------------------------------------------------------
777// Startup
778// ---------------------------------------------------------------------------
779
780pub fn start(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
781    let prog = match spec.bin.as_deref() {
782        Some(b) => crate::which(b).with_context(|| tr!("找不到指定的執行檔 `{b}`", b = b))?,
783        None => crate::which("codex").with_context(|| tr!("找不到 `{prog}`", prog = "codex"))?,
784    };
785    let mut cmd = Command::new(prog);
786    cmd.arg("app-server");
787    cmd.args(spec.permission.codex_flags());
788    let sandbox = resolve_codex_sandbox(&spec, is_bwrap_usable());
789    if sandbox == "danger-full-access" {
790        cmd.args(["-c", "sandbox_mode=\"danger-full-access\""]);
791    } else {
792        // Give workspace-write sandbox network access by default to avoid Linux bwrap --unshare-net triggering
793        // `loopback: Failed RTM_NEWADDR: Operation not permitted`
794        cmd.args(["-c", "sandbox_workspace_write.network_access=true"]);
795    }
796    if let Some(exe) = &spec.mcp_exe {
797        let sock_opt = spec
798            .env
799            .iter()
800            .find(|(k, _)| k == "ERTANGLE_SOCKET")
801            .map(|(_, v)| v.as_str());
802
803        let mut mcp_args = vec![
804            "\"mcp\"".to_string(),
805            format!("\"--session\",{:?}", spec.id),
806        ];
807        if let Some(sock) = sock_opt {
808            mcp_args.push(format!("\"--socket\",{:?}", sock));
809        }
810
811        cmd.args([
812            "-c",
813            &format!("mcp_servers.ertangle.command={:?}", exe.to_string_lossy()),
814            "-c",
815            &format!("mcp_servers.ertangle.args=[{}]", mcp_args.join(",")),
816        ]);
817        if let Some(sock) = sock_opt {
818            cmd.args([
819                "-c",
820                &format!("mcp_servers.ertangle.env.ERTANGLE_SOCKET={:?}", sock),
821            ]);
822        }
823        if spec.permission.auto_approves() {
824            cmd.args(["-c", AUTO_APPROVE_ERTANGLE_MCP]);
825        }
826    }
827    cmd.args(&spec.args);
828    cmd.current_dir(&spec.cwd)
829        .stdin(Stdio::piped())
830        .stdout(Stdio::piped())
831        .stderr(Stdio::piped());
832    for (k, v) in &spec.env {
833        cmd.env(k, v);
834    }
835    #[cfg(unix)]
836    {
837        use std::os::unix::process::CommandExt;
838        cmd.process_group(0);
839    }
840
841    let mut child = cmd
842        .spawn()
843        .with_context(|| tr!("無法啟動 `codex app-server`"))?;
844    let stdin = child
845        .stdin
846        .take()
847        .with_context(|| tr!("取得 codex stdin 失敗"))?;
848    let stderr_tail = child.stderr.take().map(crate::stderr::StderrTail::spawn);
849    let stdout = child
850        .stdout
851        .take()
852        .with_context(|| tr!("取得 codex stdout 失敗"))?;
853
854    let conn = Arc::new(Conn {
855        session_id: spec.id.clone(),
856        stdin: Mutex::new(stdin),
857        next_id: AtomicI64::new(1),
858        pending: Mutex::new(HashMap::new()),
859        perms: Mutex::new(HashMap::new()),
860        questions: Mutex::new(HashMap::new()),
861        thread: Mutex::new(String::new()),
862        turn: Mutex::new(String::new()),
863        stream: Mutex::new(StreamBuf::default()),
864        last_error: Mutex::new(None),
865        tx: tx.clone(),
866    });
867
868    {
869        let conn = conn.clone();
870        std::thread::spawn(move || {
871            let reader = BufReader::new(stdout);
872            for line in reader.lines() {
873                match line {
874                    Ok(l) => conn.on_line(&l),
875                    Err(_) => break,
876                }
877            }
878            // stdout closed = process exited: discard pending requests so handshake does not wait for timeout.
879            conn.pending
880                .lock()
881                .unwrap_or_else(|e| e.into_inner())
882                .clear();
883        });
884    }
885
886    let child = Arc::new(Mutex::new(child));
887    {
888        let child = child.clone();
889        let tx = tx.clone();
890        std::thread::spawn(move || {
891            let code = loop {
892                let status = {
893                    let mut c = child.lock().unwrap_or_else(|e| e.into_inner());
894                    c.try_wait()
895                };
896                match status {
897                    Ok(Some(s)) => break s.code(),
898                    Ok(None) => std::thread::sleep(Duration::from_millis(100)),
899                    Err(_) => break None,
900                }
901            };
902            if let Some(t) = &stderr_tail {
903                t.report_exit(code, &tx);
904            }
905            let _ = tx.send(AgentEvent::Exited(code));
906        });
907    }
908
909    // Handshake: initialize -> thread/start.
910    conn.call(
911        "initialize",
912        json!({ "clientInfo": { "name": "ertangle", "title": "ertangle", "version": env!("CARGO_PKG_VERSION") } }),
913        CALL_TIMEOUT,
914    )
915    .with_context(|| tr!("codex `initialize` 失敗"))?;
916
917    // When resuming, use `thread/resume` instead (historical turns are in response, not replayed via notifications).
918    let method = if spec.resume.is_some() {
919        "thread/resume"
920    } else {
921        "thread/start"
922    };
923    let started = conn
924        .call(method, thread_open_params(&spec), CALL_TIMEOUT)
925        .with_context(|| tr!("codex `{method}` 失敗", method = method))?;
926    let tid = started["thread"]["id"]
927        .as_str()
928        .with_context(|| tr!("`{method}` 未回傳 thread id", method = method))?
929        .to_string();
930    *conn.thread.lock().unwrap_or_else(|e| e.into_inner()) = tid.clone();
931    let _ = tx.send(AgentEvent::NativeId(tid));
932    if let Some(model) = started["model"].as_str() {
933        let _ = tx.send(AgentEvent::Model(model.to_string()));
934    }
935    // Query account quota once on startup (skipped if not logged in or unsupported by older codex versions).
936    if let Ok(r) = conn.call("account/rateLimits/read", json!({}), CALL_TIMEOUT) {
937        if let Some(q) = parse_rate_limits(&r["rateLimits"]) {
938            let _ = tx.send(AgentEvent::Quota(q));
939        }
940    }
941    let _ = tx.send(AgentEvent::Status(SessionStatus::Idle));
942
943    let control = CodexControl {
944        conn,
945        child,
946        overrides: Mutex::new((None, None)),
947    };
948    if let Some(p) = &spec.initial_prompt {
949        control.send_input_with(p, &spec.initial_attachments)?;
950    }
951    Ok(Box::new(control))
952}
953
954/// Parses Codex `RateLimitSnapshot` (shared between `account/rateLimits/read` and update notifications).
955pub(crate) fn parse_rate_limits(snap: &Value) -> Option<ertangle_core::Quota> {
956    let mut windows = Vec::new();
957    for key in ["primary", "secondary"] {
958        let w = &snap[key];
959        let Some(pct) = w["usedPercent"].as_f64() else {
960            continue;
961        };
962        windows.push(ertangle_core::QuotaWindow {
963            name: w["windowDurationMins"]
964                .as_u64()
965                .map(ertangle_core::window_name)
966                .unwrap_or_else(|| key.to_string()),
967            used_percent: pct as f32,
968            resets_at_ms: w["resetsAt"].as_u64().map(|s| s * 1000),
969        });
970    }
971    if windows.is_empty() {
972        return None;
973    }
974    let reached = !snap["rateLimitReachedType"].is_null()
975        || snap["spendControlReached"].as_bool() == Some(true);
976    Some(ertangle_core::Quota {
977        agent: "codex".into(),
978        windows,
979        reached,
980        warning: false,
981        updated_ms: ertangle_core::now_millis(),
982    })
983}
984
985/// `thread/start` parameters: cwd, approvalPolicy, plus optional model and sandbox (official doc examples:
986/// `"model"`, `"sandbox": "workspace-write"`; `read_only` maps to `read-only`).
987/// Codex `turn/start` input: text (including inlined text files) plus data URL images.
988fn turn_input(text: &str, atts: &[ertangle_core::Attachment]) -> Value {
989    let mut items =
990        vec![json!({ "type": "text", "text": ertangle_core::compose_text(text, atts, false) })];
991    for a in atts.iter().filter(|a| a.is_image()) {
992        if let Some(data) = &a.data {
993            items.push(json!({ "type": "image", "url": format!("data:{};base64,{data}", a.mime) }));
994        }
995    }
996    Value::Array(items)
997}
998
999/// Parameters for `thread/start` or `thread/resume` (when `spec.resume` is set).
1000/// Both accept the same set of override fields; resumption additionally includes `threadId` and uses `excludeTurns` to omit historical turns.
1001fn thread_open_params(spec: &SessionSpec) -> Value {
1002    let mut p = thread_start_params(spec);
1003    if let Some(id) = &spec.resume {
1004        p["threadId"] = json!(id);
1005        p["excludeTurns"] = json!(true);
1006    }
1007    p
1008}
1009
1010/// Checks whether bwrap can create user namespaces and sandboxes normally on Linux.
1011///
1012/// On environments like Ubuntu 24.04+ with `kernel.apparmor_restrict_unprivileged_userns = 1`,
1013/// bwrap without an AppArmor profile authorization fails when creating uid maps (`Permission denied`).
1014/// In this case, fall back to `danger-full-access` to prevent Codex from aborting on command execution.
1015#[cfg(target_os = "linux")]
1016pub fn is_bwrap_usable() -> bool {
1017    static CACHE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1018    *CACHE.get_or_init(|| {
1019        if let Ok(val) =
1020            std::fs::read_to_string("/proc/sys/kernel/apparmor_restrict_unprivileged_userns")
1021        {
1022            if val.trim() == "1" {
1023                return false;
1024            }
1025        }
1026        std::process::Command::new("bwrap")
1027            .args(["--ro-bind", "/", "/", "--", "true"])
1028            .stdin(std::process::Stdio::null())
1029            .stdout(std::process::Stdio::null())
1030            .stderr(std::process::Stdio::null())
1031            .status()
1032            .map(|s| s.success())
1033            .unwrap_or(false)
1034    })
1035}
1036
1037#[cfg(not(target_os = "linux"))]
1038pub fn is_bwrap_usable() -> bool {
1039    true
1040}
1041
1042/// Resolves the sandbox mode used by Codex.
1043///
1044/// Respects `spec.sandbox` if explicitly specified; if `None`, falls back to `"danger-full-access"`
1045/// when `bwrap` cannot run normally or `permission` is `Bypass`, otherwise selects `"read-only"`
1046/// or `"workspace-write"` based on `read_only`.
1047pub fn resolve_codex_sandbox(spec: &SessionSpec, bwrap_ok: bool) -> String {
1048    if let Some(s) = &spec.sandbox {
1049        return s.clone();
1050    }
1051    if !bwrap_ok || spec.permission == ertangle_core::PermissionPolicy::Bypass {
1052        "danger-full-access".to_string()
1053    } else if spec.read_only {
1054        "read-only".to_string()
1055    } else {
1056        "workspace-write".to_string()
1057    }
1058}
1059
1060fn thread_start_params(spec: &SessionSpec) -> Value {
1061    let mut p = json!({
1062        "cwd": spec.cwd.to_string_lossy(),
1063        "approvalPolicy": spec.permission.codex_approval_policy(),
1064    });
1065    if let Some(m) = &spec.model {
1066        p["model"] = json!(m);
1067    }
1068    let mut config = json!({
1069        "sandbox_workspace_write": {
1070            "network_access": true
1071        }
1072    });
1073    if let Some(e) = &spec.effort {
1074        // Thread-level config override, equivalent to `-c model_reasoning_effort=...`.
1075        config["model_reasoning_effort"] = json!(e);
1076    }
1077    p["config"] = config;
1078    let sandbox = resolve_codex_sandbox(spec, is_bwrap_usable());
1079    p["sandbox"] = json!(sandbox);
1080    if let Some(inst) = spec.system_append.as_deref().filter(|s| !s.is_empty()) {
1081        p["developerInstructions"] = json!(inst);
1082    }
1083    p
1084}
1085
1086#[cfg(test)]
1087mod tests {
1088
1089    #[test]
1090    fn auto_approve_override_targets_mcp_server_with_valid_mode() {
1091        assert!(AUTO_APPROVE_ERTANGLE_MCP.starts_with("mcp_servers.ertangle."));
1092        assert!(AUTO_APPROVE_ERTANGLE_MCP.ends_with("=\"approve\""));
1093    }
1094
1095    #[test]
1096    fn formless_elicitation_gets_allow_deny_options() {
1097        let params = json!({ "message": "Allow ertangle_send?", "requestedSchema": { "type": "object", "properties": {} } });
1098        let mut list = crate::question::parse_acp_elicitations("ses", &params);
1099        add_confirm_options(&mut list);
1100        let labels: Vec<_> = list[0].0.options.iter().map(|o| o.label.as_str()).collect();
1101        assert_eq!(labels, ["Allow", "Deny"]);
1102    }
1103
1104    #[test]
1105    fn real_form_fields_keep_their_own_options() {
1106        let params =
1107            json!({ "requestedSchema": { "properties": { "env": { "enum": ["a", "b"] } } } });
1108        let mut list = crate::question::parse_acp_elicitations("ses", &params);
1109        add_confirm_options(&mut list);
1110        let labels: Vec<_> = list[0].0.options.iter().map(|o| o.label.as_str()).collect();
1111        assert_eq!(labels, ["a", "b"]);
1112        let params =
1113            json!({ "requestedSchema": { "properties": { "name": { "type": "string" } } } });
1114        let mut list = crate::question::parse_acp_elicitations("ses", &params);
1115        add_confirm_options(&mut list);
1116        assert!(
1117            list[0].0.options.is_empty(),
1118            "free-text field must stay free-text"
1119        );
1120    }
1121    use super::*;
1122
1123    #[test]
1124    fn elicitation_content_uses_scalar_for_single_select() {
1125        let entries = vec![
1126            ("env".to_string(), false, vec!["production".to_string()]),
1127            (
1128                "features".to_string(),
1129                true,
1130                vec!["a".to_string(), "b".to_string()],
1131            ),
1132        ];
1133        assert_eq!(
1134            elicitation_content(&entries),
1135            json!({ "env": "production", "features": ["a", "b"] })
1136        );
1137    }
1138
1139    #[test]
1140    fn user_input_answer_result_has_codex_shape() {
1141        let result = user_input_answer_result(&["Postgres".into(), "Redis".into()], "db");
1142        assert_eq!(
1143            result,
1144            json!({ "answers": { "db": { "answers": ["Postgres", "Redis"], "other": null } } })
1145        );
1146        assert_eq!(
1147            user_input_answer_result(&[], "db"),
1148            json!({ "answers": {} })
1149        );
1150    }
1151
1152    #[test]
1153    fn approval_verdict_mapping() {
1154        // Only validates the mapping table itself (no need to actually run codex).
1155        let cases = [
1156            (ApprovalKind::Command, Decision::Allow, "accept"),
1157            (
1158                ApprovalKind::Command,
1159                Decision::AllowAlways,
1160                "acceptForSession",
1161            ),
1162            (ApprovalKind::File, Decision::Deny, "decline"),
1163        ];
1164        for (kind, d, want) in cases {
1165            let got = match (kind, d) {
1166                (_, Decision::Allow) => "accept",
1167                (_, Decision::AllowAlways) => "acceptForSession",
1168                (_, Decision::Deny) => "decline",
1169            };
1170            assert_eq!(got, want);
1171        }
1172
1173        assert_eq!(ApprovalKind::Command.as_str(), "command");
1174        assert_eq!(ApprovalKind::File.as_str(), "file");
1175        assert_eq!(ApprovalKind::McpElicitation.as_str(), "mcp_elicitation");
1176        assert_eq!(ApprovalKind::Permissions.as_str(), "permissions");
1177
1178        // Validate return structure for MCP elicitation and permissions
1179        let mcp_allow = match Decision::Allow {
1180            Decision::Allow | Decision::AllowAlways => json!({"action": "accept", "content": {}}),
1181            Decision::Deny => json!({"action": "decline"}),
1182        };
1183        assert_eq!(mcp_allow["action"], "accept");
1184
1185        let mcp_deny = match Decision::Deny {
1186            Decision::Allow | Decision::AllowAlways => json!({"action": "accept", "content": {}}),
1187            Decision::Deny => json!({"action": "decline"}),
1188        };
1189        assert_eq!(mcp_deny["action"], "decline");
1190
1191        let perm_allow = match Decision::Allow {
1192            Decision::Allow | Decision::AllowAlways => json!({"permissions": {}, "scope": "turn"}),
1193            Decision::Deny => json!({"permissions": null}),
1194        };
1195        assert_eq!(perm_allow["scope"], "turn");
1196        assert!(perm_allow["permissions"].is_object());
1197
1198        let perm_deny = match Decision::Deny {
1199            Decision::Allow | Decision::AllowAlways => json!({"permissions": {}, "scope": "turn"}),
1200            Decision::Deny => json!({"permissions": null}),
1201        };
1202        assert!(perm_deny["permissions"].is_null());
1203    }
1204
1205    #[test]
1206    fn thread_start_carries_model_and_sandbox() {
1207        let spec = SessionSpec {
1208            id: "s".into(),
1209            kind: ertangle_core::AgentKind::Codex,
1210            cwd: "/tmp".into(),
1211            transport: ertangle_protocol::Transport::Structured,
1212            bin: None,
1213            args: vec![],
1214            model: Some("m1".into()),
1215            effort: Some("high".into()),
1216            allowed_tools: vec![],
1217            disallowed_tools: vec![],
1218            read_only: false,
1219            sandbox: Some("workspace-write".into()),
1220            env: vec![],
1221            permission: ertangle_core::PermissionPolicy::Auto,
1222            mcp_exe: None,
1223            system_append: None,
1224            initial_prompt: None,
1225            initial_attachments: vec![],
1226            resume: None,
1227            cols: 80,
1228            rows: 24,
1229        };
1230        let p = thread_start_params(&spec);
1231        assert_eq!(p["model"], "m1");
1232        assert_eq!(p["sandbox"], "workspace-write");
1233        assert_eq!(p["config"]["model_reasoning_effort"], "high");
1234        assert_eq!(
1235            p["config"]["sandbox_workspace_write"]["network_access"],
1236            true
1237        );
1238        assert!(p.get("developerInstructions").is_none());
1239        let mut ro = spec.clone();
1240        ro.sandbox = Some("read-only".into());
1241        ro.read_only = true;
1242        assert_eq!(thread_start_params(&ro)["sandbox"], "read-only");
1243
1244        let mut bypass = spec.clone();
1245        bypass.sandbox = None;
1246        bypass.permission = ertangle_core::PermissionPolicy::Bypass;
1247        assert_eq!(
1248            thread_start_params(&bypass)["sandbox"],
1249            "danger-full-access"
1250        );
1251        // New conversations do not carry threadId; resumption includes it while keeping other override fields intact.
1252        assert!(thread_open_params(&spec)["threadId"].is_null());
1253        let mut re = spec.clone();
1254        re.resume = Some("thr-1".into());
1255        let p = thread_open_params(&re);
1256        assert_eq!(p["threadId"], "thr-1");
1257        assert_eq!(p["excludeTurns"], true);
1258        assert_eq!(p["model"], "m1");
1259        ro.system_append = Some("collab".into());
1260        let p_ro = thread_start_params(&ro);
1261        assert_eq!(p_ro["sandbox"], "read-only");
1262        assert_eq!(p_ro["developerInstructions"], "collab");
1263    }
1264
1265    #[test]
1266    fn codex_sandbox_resolution() {
1267        let spec = SessionSpec {
1268            id: "s".into(),
1269            kind: ertangle_core::AgentKind::Codex,
1270            cwd: "/tmp".into(),
1271            transport: ertangle_protocol::Transport::Structured,
1272            bin: None,
1273            args: vec![],
1274            model: Some("m1".into()),
1275            effort: Some("high".into()),
1276            allowed_tools: vec![],
1277            disallowed_tools: vec![],
1278            read_only: false,
1279            sandbox: None,
1280            env: vec![],
1281            permission: ertangle_core::PermissionPolicy::Auto,
1282            mcp_exe: None,
1283            system_append: None,
1284            initial_prompt: None,
1285            initial_attachments: vec![],
1286            resume: None,
1287            cols: 80,
1288            rows: 24,
1289        };
1290
1291        // bwrap_ok = true: decided by read_only and permission
1292        assert_eq!(resolve_codex_sandbox(&spec, true), "workspace-write");
1293        let mut ro = spec.clone();
1294        ro.read_only = true;
1295        assert_eq!(resolve_codex_sandbox(&ro, true), "read-only");
1296        let mut bypass = spec.clone();
1297        bypass.permission = ertangle_core::PermissionPolicy::Bypass;
1298        assert_eq!(resolve_codex_sandbox(&bypass, true), "danger-full-access");
1299
1300        // bwrap_ok = false: falls back to danger-full-access under AppArmor / userns restrictions
1301        assert_eq!(resolve_codex_sandbox(&spec, false), "danger-full-access");
1302        assert_eq!(resolve_codex_sandbox(&ro, false), "danger-full-access");
1303        assert_eq!(resolve_codex_sandbox(&bypass, false), "danger-full-access");
1304
1305        // Always respect explicit spec.sandbox setting
1306        let mut explicit = spec.clone();
1307        explicit.sandbox = Some("workspace-write".into());
1308        assert_eq!(resolve_codex_sandbox(&explicit, true), "workspace-write");
1309        assert_eq!(resolve_codex_sandbox(&explicit, false), "workspace-write");
1310
1311        explicit.sandbox = Some("read-only".into());
1312        assert_eq!(resolve_codex_sandbox(&explicit, true), "read-only");
1313        assert_eq!(resolve_codex_sandbox(&explicit, false), "read-only");
1314    }
1315
1316    #[test]
1317    fn error_text_and_auth_detection() {
1318        let e = json!({"message":"boom","codexErrorInfo":"other"});
1319        assert_eq!(error_text(&e), "boom");
1320        assert!(!is_auth_error(&e));
1321        let a = json!({"message":"x","codexErrorInfo":"unauthorized"});
1322        assert!(is_auth_error(&a));
1323        assert!(is_auth_error(&json!({"message":"HTTP 401"})));
1324        let long = json!({"detail":"y".repeat(1000)});
1325        assert_eq!(error_text(&long).chars().count(), 300);
1326    }
1327
1328    #[test]
1329    fn parses_codex_rate_limit_snapshot() {
1330        let snap = json!({"primary":{"usedPercent":42,"windowDurationMins":300,"resetsAt":1797125904},
1331            "secondary":{"usedPercent":7,"windowDurationMins":10080,"resetsAt":1797725904},
1332            "rateLimitReachedType":null,"spendControlReached":false});
1333        let q = parse_rate_limits(&snap).unwrap();
1334        assert_eq!(q.agent, "codex");
1335        assert_eq!(q.windows[0].name, "5h");
1336        assert_eq!(q.windows[1].name, "7d");
1337        assert!(!q.reached);
1338        let hit = json!({"primary":{"usedPercent":100,"windowDurationMins":300},"rateLimitReachedType":"rate_limit_reached"});
1339        assert!(parse_rate_limits(&hit).unwrap().reached);
1340        assert!(parse_rate_limits(&json!({})).is_none());
1341    }
1342}