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