Skip to main content

ertangle_adapter/
acp.rs

1//! Native Agent Client Protocol adapter.
2//!
3//! M0 used for OpenCode (`opencode acp`), which is the only one among four agents that provides a structured
4//! protocol natively with zero extra dependencies, and was therefore implemented as the first structured adapter.
5//!
6//! ACP subset covered: `initialize`, `session/new`, `session/load` (resumption), `session/prompt`,
7//! `session/cancel`,
8//! as well as server→client `session/update` (streaming) and `session/request_permission` (approvals).
9
10use crate::stream::StreamBuf;
11use crate::{AgentControl, AgentEvent, SessionSpec};
12use anyhow::{anyhow, bail, Context, Result};
13use ertangle_core::{new_id, Decision, PermissionRequest, SessionStatus};
14use serde_json::{json, Value};
15use std::collections::HashMap;
16use std::io::{BufRead, BufReader, Write};
17use std::process::{Child, ChildStdin, Command, Stdio};
18use std::sync::atomic::{AtomicI64, Ordering};
19use std::sync::mpsc::{self, Sender};
20use std::sync::{Arc, Mutex};
21use std::time::{Duration, Instant};
22use tr::tr;
23
24const CALL_TIMEOUT: Duration = Duration::from_secs(30);
25const PROMPT_TIMEOUT: Duration = Duration::from_secs(3600);
26/// `session/load` must wait for the agent to replay the entire history, which takes longer than a normal call for long conversations.
27const LOAD_TIMEOUT: Duration = Duration::from_secs(180);
28/// Some ACP agents (e.g. agy) keep streaming `session/load` history replay after the load response.
29/// The replay is considered finished once no `session/update` has arrived for this long.
30const REPLAY_QUIET: Duration = Duration::from_millis(800);
31/// Upper bound on waiting for the post-load replay to go quiet.
32const REPLAY_MAX_WAIT: Duration = Duration::from_secs(20);
33/// A turn with no `session/update` for this long is reported as possibly stalled.
34/// (agy has been observed accepting `session/prompt` and then never calling the model.)
35const STALL_AFTER: Duration = Duration::from_secs(180);
36/// How often the stall watchdog checks in-flight turns.
37const STALL_POLL: Duration = Duration::from_secs(15);
38
39/// Tracks in-flight `session/prompt` turns.
40///
41/// ACP agents such as agy accept a second `session/prompt` while one is still running and may
42/// answer it immediately; status must only return to Idle once *every* turn has finished,
43/// otherwise a hung first turn is hidden behind a false Idle.
44#[derive(Debug, Default)]
45struct TurnTracker {
46    inflight: usize,
47    /// When the oldest still-running turn started (reset when all turns finish).
48    started: Option<Instant>,
49    /// When the stall warning was last emitted for the current quiet period.
50    warned_at: Option<Instant>,
51}
52
53impl TurnTracker {
54    fn begin(&mut self, now: Instant) {
55        if self.inflight == 0 {
56            self.started = Some(now);
57        }
58        self.inflight = self.inflight.saturating_add(1);
59    }
60
61    /// Ends one turn. Returns `None` while other turns are still running, otherwise
62    /// `Some(warned)` where `warned` tells whether a stall warning should be cleared.
63    fn end(&mut self) -> Option<bool> {
64        self.inflight = self.inflight.saturating_sub(1);
65        if self.inflight > 0 {
66            return None;
67        }
68        self.started = None;
69        Some(self.warned_at.take().is_some())
70    }
71
72    /// Returns how long the agent has been silent if a turn is running, has been quiet for at
73    /// least `threshold`, and no warning was issued yet for this quiet period.
74    fn stalled(
75        &mut self,
76        now: Instant,
77        last_update: Instant,
78        threshold: Duration,
79    ) -> Option<Duration> {
80        let started = self.started?;
81        let quiet_since = started.max(last_update);
82        let quiet = now.saturating_duration_since(quiet_since);
83        if quiet < threshold || self.warned_at.is_some_and(|w| w >= quiet_since) {
84            return None;
85        }
86        self.warned_at = Some(now);
87        Some(quiet)
88    }
89}
90
91/// Collected answers for a multi-field elicitation: field key -> (multi-select, answers).
92type ElicitationAnswers = Arc<Mutex<HashMap<String, (bool, Vec<String>)>>>;
93
94/// Pending question state for ACP elicitation or tool-call fallback.
95enum PendingAcpQuestion {
96    Elicitation {
97        rpc_id: Value,
98        key: String,
99        multi_select: bool,
100        total: usize,
101        answers: ElicitationAnswers,
102        /// Maps a displayed option label back to the value required by the agent schema.
103        option_values: HashMap<String, String>,
104    },
105    ToolCall {
106        total: usize,
107        answers: Arc<Mutex<Vec<String>>>,
108    },
109}
110
111/// Builds form content that conforms to the ACP elicitation schema.
112///
113/// Single-select fields carry a scalar string; only multi-select fields carry an array.
114fn elicitation_accept_content(entries: &[(String, bool, Vec<String>)]) -> Value {
115    let mut content = serde_json::Map::new();
116    for (key, multi_select, answers) in entries {
117        let value = if !multi_select && answers.len() == 1 {
118            answers
119                .first()
120                .map(|a| json!(a))
121                .unwrap_or_else(|| json!(""))
122        } else {
123            json!(answers)
124        };
125        content.insert(key.clone(), value);
126    }
127    Value::Object(content)
128}
129
130/// Builds the response for a completed elicitation. Skipped fields are omitted so a
131/// companion "Other" field cannot discard a real selection; a fully skipped form is declined.
132fn elicitation_response(entries: &[(String, bool, Vec<String>)]) -> Value {
133    let answered: Vec<_> = entries
134        .iter()
135        .filter(|(_, _, answers)| !answers.is_empty())
136        .cloned()
137        .collect();
138    if answered.is_empty() {
139        return json!({ "action": "decline" });
140    }
141    json!({
142        "action": "accept",
143        "content": elicitation_accept_content(&answered)
144    })
145}
146
147struct Conn {
148    /// Agent ID represented by this adapter (`agent` field in quota events).
149    agent: String,
150    /// Quota marked as rate limited with `reached=true`, not yet cleared by a successful turn.
151    limited: std::sync::atomic::AtomicBool,
152    /// Quota query support (Antigravity `agy -p /quota`, Copilot `account.getQuota`): agent kind, executable and environment variables.
153    quota_prog: Option<QuotaProg>,
154    /// Prevents running multiple quota query background processes concurrently.
155    quota_refreshing: std::sync::atomic::AtomicBool,
156    /// Our own session ID (for event correlation).
157    session_id: String,
158    /// Agent's ACP session ID (for prompt / cancel).
159    acp_session: Mutex<String>,
160    stdin: Mutex<ChildStdin>,
161    next_id: AtomicI64,
162    pending: Mutex<HashMap<i64, Sender<Value>>>,
163    /// Approvals: internal req id -> (JSON-RPC id, options)
164    perms: Mutex<HashMap<String, (Value, Vec<Value>)>>,
165    /// Interactive questions: internal qst id -> pending question state
166    questions: Mutex<HashMap<String, PendingAcpQuestion>>,
167    /// Line buffer for streaming output (combines token-level chunks into complete lines).
168    stream: Mutex<StreamBuf>,
169    /// Notifies the idle-flush thread whenever a streaming chunk is buffered.
170    stream_poke: Sender<()>,
171    /// Collaboration instructions prepended to the first prompt (cleared once taken).
172    prepend_once: Mutex<Option<String>>,
173    /// Agent declared image block support during initialize (`promptCapabilities.image`).
174    image_ok: std::sync::atomic::AtomicBool,
175    /// `session/load` in progress: the agent replays history via `session/update`; updates during this period are discarded,
176    /// otherwise the transcript would duplicate. Cleared once the replay has gone quiet after the load response
177    /// (see [`wait_until_quiet`]), or at the latest when the next `session/prompt` is sent.
178    loading: std::sync::atomic::AtomicBool,
179    /// When the last `session/update` arrived (including discarded replay updates).
180    last_update: Mutex<std::time::Instant>,
181    /// In-flight prompt turns (see [`TurnTracker`]).
182    turns: Mutex<TurnTracker>,
183    /// Permission policy: directly auto-approved by adapter when `Auto` / `Bypass`.
184    tx: Sender<AgentEvent>,
185}
186
187impl Conn {
188    fn emit(&self, ev: AgentEvent) {
189        // Write failure means the receiver channel is closed; nothing to do.
190        let _ = self.tx.send(ev);
191    }
192
193    fn write(&self, v: &Value) -> Result<()> {
194        let mut line = serde_json::to_string(v)?;
195        line.push('\n');
196        let mut w = self.stdin.lock().unwrap_or_else(|e| e.into_inner());
197        w.write_all(line.as_bytes())?;
198        w.flush()?;
199        Ok(())
200    }
201
202    fn respond(&self, id: &Value, result: Value) {
203        // Ignore response write errors if agent stdin is already closed.
204        let _ = self.write(&json!({"jsonrpc":"2.0","id":id,"result":result}));
205    }
206
207    fn respond_error(&self, id: &Value, code: i64, message: &str) {
208        // Ignore response write errors if agent stdin is already closed.
209        let _ = self.write(&json!({
210            "jsonrpc":"2.0","id":id,
211            "error":{"code":code,"message":message}
212        }));
213    }
214
215    /// Sends a request and waits for response.
216    fn call(&self, method: &str, params: Value, timeout: Duration) -> Result<Value> {
217        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
218        let (s, r) = mpsc::channel();
219        self.pending
220            .lock()
221            .unwrap_or_else(|e| e.into_inner())
222            .insert(id, s);
223        self.write(&json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}))?;
224        let msg = r
225            .recv_timeout(timeout)
226            .map_err(|_| anyhow!(tr!("`{method}` 逾時", method = method)))?;
227        if let Some(err) = msg.get("error") {
228            bail!(
229                "{}",
230                tr!("`{method}` 失敗:{err}", method = method, err = err)
231            );
232        }
233        Ok(msg.get("result").cloned().unwrap_or(Value::Null))
234    }
235
236    /// Sends a prompt and waits for the entire turn to complete.
237    fn prompt(&self, text: &str, atts: &[ertangle_core::Attachment]) -> Result<()> {
238        let sid = self
239            .acp_session
240            .lock()
241            .unwrap_or_else(|e| e.into_inner())
242            .clone();
243        if sid.is_empty() {
244            bail!("{}", tr!("session 尚未就緒"));
245        }
246        let effective = take_effective_prompt(&self.prepend_once, text);
247        // Any session/update arriving before the first session/prompt on a resumed session is
248        // asynchronous history replay from session/load; stop discarding only once we prompt.
249        self.loading.store(false, Ordering::SeqCst);
250        self.turns
251            .lock()
252            .unwrap_or_else(|e| e.into_inner())
253            .begin(Instant::now());
254        self.emit(AgentEvent::Status(SessionStatus::Busy));
255        let res = self.call(
256            "session/prompt",
257            json!({ "sessionId": sid, "prompt": prompt_blocks(&effective, atts, self.image_ok.load(Ordering::SeqCst)) }),
258            PROMPT_TIMEOUT,
259        );
260        let ended = self.turns.lock().unwrap_or_else(|e| e.into_inner()).end();
261        if let Some(warned) = ended {
262            self.flush_stream();
263            if warned {
264                self.emit(AgentEvent::Note(String::new()));
265            }
266            self.emit(AgentEvent::Status(SessionStatus::Idle));
267        }
268        if res.is_ok() {
269            if let Some(q) = recovered_quota(&self.agent, &self.limited) {
270                self.emit(AgentEvent::Quota(q));
271            }
272        }
273        res.map(|_| ())
274    }
275
276    /// Warns (once per quiet period) when a running turn has produced no `session/update` for
277    /// [`STALL_AFTER`]. Skipped while waiting on the user for a permission or question.
278    fn check_stall(&self, now: Instant) {
279        let waiting_on_user = !self
280            .perms
281            .lock()
282            .unwrap_or_else(|e| e.into_inner())
283            .is_empty()
284            || !self
285                .questions
286                .lock()
287                .unwrap_or_else(|e| e.into_inner())
288                .is_empty();
289        if waiting_on_user {
290            return;
291        }
292        let last = *self.last_update.lock().unwrap_or_else(|e| e.into_inner());
293        let quiet = self
294            .turns
295            .lock()
296            .unwrap_or_else(|e| e.into_inner())
297            .stalled(now, last, STALL_AFTER);
298        let Some(quiet) = quiet else { return };
299        self.flush_stream();
300        let note = tr!(
301            "agent 已 {mins} 分鐘沒有任何回應,可能卡住;可用 /cancel 中斷本回合後重送",
302            mins = quiet.as_secs() / 60
303        );
304        self.emit(AgentEvent::Output(format!("⚠ {note}\n")));
305        self.emit(AgentEvent::Note(note));
306    }
307
308    /// If the error text indicates rate limiting, emits `reached=true` and sets flag (subsequent successful turns will clear it).
309    fn report_rate_limit(&self, error_text: &str) {
310        if let Some(q) = rate_limit_quota(&self.agent, error_text) {
311            self.limited.store(true, Ordering::SeqCst);
312            self.emit(AgentEvent::Quota(q));
313        }
314    }
315
316    /// Asynchronously queries Antigravity quota (non-blocking), running at most one query at a time.
317    fn refresh_quota_async(self: &Arc<Self>) {
318        let Some((kind, prog, env)) = self.quota_prog.clone() else {
319            return;
320        };
321        if self
322            .quota_refreshing
323            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
324            .is_err()
325        {
326            return;
327        }
328        let conn = self.clone();
329        std::thread::spawn(move || {
330            struct Guard<'a>(&'a std::sync::atomic::AtomicBool);
331            // Safe Rust: atomic store is infallible, ensuring Drop cannot panic.
332            impl Drop for Guard<'_> {
333                fn drop(&mut self) {
334                    self.0.store(false, Ordering::SeqCst);
335                }
336            }
337            let _guard = Guard(&conn.quota_refreshing);
338            let quota = match kind {
339                ertangle_core::AgentKind::Copilot => {
340                    query_copilot_quota(&prog, &env).and_then(|raw| {
341                        let reached = conn.limited.load(Ordering::SeqCst);
342                        parse_copilot_quota_json(&raw, reached, ertangle_core::now_millis())
343                    })
344                }
345                _ => query_agy_quota(&prog, &env).and_then(|raw| {
346                    let reached = conn.limited.load(Ordering::SeqCst);
347                    parse_agy_quota_json(&raw, reached)
348                }),
349            };
350            if let Some(q) = quota {
351                conn.emit(AgentEvent::Quota(q));
352            }
353        });
354    }
355
356    fn on_update(&self, msg: &Value) {
357        let update = msg
358            .get("params")
359            .and_then(|p| p.get("update"))
360            .unwrap_or(&Value::Null);
361        let kind = update["sessionUpdate"].as_str().unwrap_or("");
362        match kind {
363            "available_commands_update" => {
364                let names: Vec<String> = update["availableCommands"]
365                    .as_array()
366                    .into_iter()
367                    .flatten()
368                    .filter_map(|c| c["name"].as_str())
369                    .map(|n| n.trim_start_matches('/').to_string())
370                    .collect();
371                self.emit(AgentEvent::Commands(names));
372            }
373            "usage_update" => {
374                // ACP: `used` (current context tokens) and `size` (window size).
375                if let Some(used) = update["used"].as_u64() {
376                    self.emit(AgentEvent::Context {
377                        used,
378                        window: update["size"].as_u64(),
379                    });
380                }
381            }
382            "error" => {
383                self.report_rate_limit(&update.to_string());
384            }
385            "agent_message_chunk" => {
386                if let Some(t) = update
387                    .get("content")
388                    .and_then(|c| c.get("text"))
389                    .and_then(|t| t.as_str())
390                {
391                    let chunk = self
392                        .stream
393                        .lock()
394                        .unwrap_or_else(|e| e.into_inner())
395                        .push_chunk("msg", t);
396                    self.send_chunk(chunk);
397                    // Ignore stream poke wakeup failure.
398                    let _ = self.stream_poke.send(());
399                }
400            }
401            "agent_thought_chunk" => {
402                if let Some(t) = update
403                    .get("content")
404                    .and_then(|c| c.get("text"))
405                    .and_then(|t| t.as_str())
406                {
407                    let chunk = self
408                        .stream
409                        .lock()
410                        .unwrap_or_else(|e| e.into_inner())
411                        .push_chunk("think", t);
412                    self.send_chunk(chunk);
413                    // Ignore stream poke wakeup failure.
414                    let _ = self.stream_poke.send(());
415                }
416            }
417            "tool_call" => {
418                self.flush_stream();
419                let name = tool_name(update);
420                let raw_input = &update["rawInput"];
421                let input = raw_input.to_string();
422                // ACP emits an empty rawInput placeholder before the real elicitation request.
423                // Creating a question here would show "{}" instead of the actual prompt.
424                let empty_placeholder = raw_input.as_object().is_some_and(|obj| obj.is_empty())
425                    || raw_input.as_str().is_some_and(str::is_empty);
426                if !empty_placeholder && crate::question::is_question_tool(&name) {
427                    let questions =
428                        crate::question::parse_tool_call_questions(&self.session_id, &name, &input);
429                    if !questions.is_empty() {
430                        let total = questions.len();
431                        let shared_answers = Arc::new(Mutex::new(Vec::new()));
432                        let mut q_map = self.questions.lock().unwrap_or_else(|e| e.into_inner());
433                        for q in questions {
434                            q_map.insert(
435                                q.id.clone(),
436                                PendingAcpQuestion::ToolCall {
437                                    total,
438                                    answers: Arc::clone(&shared_answers),
439                                },
440                            );
441                            self.emit(AgentEvent::Question(q));
442                        }
443                    }
444                }
445                self.emit(AgentEvent::ToolCall {
446                    name,
447                    input,
448                    ok: None,
449                    output: None,
450                });
451            }
452            "tool_call_update" => {
453                // ACP reports the same tool incrementally with pending/in_progress; only completed/failed
454                // is the final result. Previously "not completed" was treated as failure, causing successful
455                // shell calls to emit an extra `✗ failed` line.
456                let Some(ok) = tool_update_ok(update) else {
457                    return;
458                };
459                let name = tool_name(update);
460                let output = tool_result_text(update);
461                self.emit(AgentEvent::ToolCall {
462                    name,
463                    input: String::new(),
464                    ok: Some(ok),
465                    output,
466                });
467            }
468            _ => {}
469        }
470    }
471
472    /// Flushes remaining buffered lines (called before switching event types or tool calls).
473    fn flush_stream(&self) {
474        let chunk = self
475            .stream
476            .lock()
477            .unwrap_or_else(|e| e.into_inner())
478            .flush_chunk();
479        self.send_chunk(chunk);
480    }
481
482    /// Flushes buffered text after a stream pause *without* a trailing newline, so the
483    /// next chunk continues the same transcript line instead of splitting it mid-token.
484    fn idle_flush_stream(&self) {
485        let chunk = self
486            .stream
487            .lock()
488            .unwrap_or_else(|e| e.into_inner())
489            .idle_flush_chunk();
490        self.send_chunk(chunk);
491    }
492
493    fn send_chunk(&self, chunk: crate::stream::Chunk) {
494        if chunk.text.is_empty() {
495            return;
496        }
497        let ev = if chunk.append {
498            AgentEvent::OutputAppend(chunk.text)
499        } else {
500            AgentEvent::Output(chunk.text)
501        };
502        self.emit(ev);
503    }
504
505    fn on_permission(&self, msg: &Value) {
506        let jid = extract_request_id(msg);
507        let params = &msg["params"];
508        let options = params["options"].as_array().cloned().unwrap_or_default();
509
510        // Always forward to daemon: rule engine and session policy (auto/bypass auto-approval) are evaluated there.
511        let req = new_id("perm");
512        let title = params
513            .get("toolCall")
514            .and_then(|tc| tc.get("title"))
515            .and_then(|t| t.as_str())
516            .unwrap_or("permission")
517            .to_string();
518        let detail = params
519            .get("toolCall")
520            .and_then(|tc| tc.get("rawInput"))
521            .map_or_else(String::new, |v| v.to_string());
522        self.perms
523            .lock()
524            .unwrap_or_else(|e| e.into_inner())
525            .insert(req.clone(), (jid, options));
526        self.emit(AgentEvent::Permission(PermissionRequest {
527            req,
528            session: self.session_id.clone(),
529            title,
530            detail,
531        }));
532    }
533
534    fn resolve(&self, req: &str, decision: Decision) -> Result<()> {
535        let entry = self
536            .perms
537            .lock()
538            .unwrap_or_else(|e| e.into_inner())
539            .remove(req);
540        let Some((jid, options)) = entry else {
541            bail!("{}", tr!("未知的核准請求:{req}", req = req));
542        };
543        self.respond(&jid, decision_result(decision, &options));
544        Ok(())
545    }
546
547    fn on_elicitation(&self, msg: &Value) {
548        let jid = extract_request_id(msg);
549        let params = &msg["params"];
550        let list = crate::question::parse_acp_elicitations(&self.session_id, params);
551        if list.is_empty() {
552            self.respond_error(&jid, -32602, "invalid elicitation params");
553            return;
554        }
555        let total = list.len();
556        let shared_answers = Arc::new(Mutex::new(HashMap::new()));
557        let mut q_map = self.questions.lock().unwrap_or_else(|e| e.into_inner());
558        for (q, key) in list {
559            let option_values = q
560                .options
561                .iter()
562                .filter_map(|opt| opt.value.clone().map(|value| (opt.label.clone(), value)))
563                .collect();
564            q_map.insert(
565                q.id.clone(),
566                PendingAcpQuestion::Elicitation {
567                    rpc_id: jid.clone(),
568                    key,
569                    multi_select: q.multi_select,
570                    total,
571                    answers: Arc::clone(&shared_answers),
572                    option_values,
573                },
574            );
575            self.emit(AgentEvent::Question(q));
576        }
577    }
578
579    fn resolve_question(&self, id: &str, answers: &[String]) -> Result<()> {
580        let entry = self
581            .questions
582            .lock()
583            .unwrap_or_else(|e| e.into_inner())
584            .remove(id);
585        let Some(pending) = entry else {
586            bail!("{}", tr!("未知的問題請求:{id}", id = id));
587        };
588        match pending {
589            PendingAcpQuestion::Elicitation {
590                rpc_id,
591                key,
592                multi_select,
593                total,
594                answers: shared_answers,
595                option_values,
596            } => {
597                // An empty answer means the human skipped this field, which is normal for
598                // companion fields such as "Other". Keep it as an omitted field instead of
599                // declining the whole form; a real selection in another field still wins.
600                let submitted: Vec<String> = answers
601                    .iter()
602                    .map(|answer| {
603                        option_values
604                            .get(answer)
605                            .cloned()
606                            .unwrap_or_else(|| answer.clone())
607                    })
608                    .collect();
609                let mut map = shared_answers.lock().unwrap_or_else(|e| e.into_inner());
610                map.insert(key, (multi_select, submitted));
611                if map.len() < total {
612                    return Ok(());
613                }
614                let entries: Vec<(String, bool, Vec<String>)> = map
615                    .iter()
616                    .map(|(k, (multi, ans))| (k.clone(), *multi, ans.clone()))
617                    .collect();
618                drop(map);
619
620                let mut q_map = self.questions.lock().unwrap_or_else(|e| e.into_inner());
621                q_map.retain(|_, v| match v {
622                    PendingAcpQuestion::Elicitation { rpc_id: r, .. } => r != &rpc_id,
623                    _ => true,
624                });
625                drop(q_map);
626
627                self.respond(&rpc_id, elicitation_response(&entries));
628            }
629            PendingAcpQuestion::ToolCall {
630                total,
631                answers: shared_answers,
632            } => {
633                let mut list = shared_answers.lock().unwrap_or_else(|e| e.into_inner());
634                if answers.is_empty() {
635                    // Preserve one slot per skipped question so a grouped request still completes.
636                    list.push(String::new());
637                } else {
638                    list.extend(answers.iter().cloned());
639                }
640                if list.len() >= total {
641                    let ans_str = list.join("\n");
642                    self.emit(AgentEvent::Output(format!("↳ {ans_str}\n")));
643                }
644            }
645        }
646        Ok(())
647    }
648}
649
650/// Translates normalized [`Decision`] to ACP `outcome`.
651fn decision_result(decision: Decision, options: &[Value]) -> Value {
652    let wanted: &[&str] = match decision {
653        Decision::Allow => &["allow_once", "allow_always"],
654        Decision::AllowAlways => &["allow_always", "allow_once"],
655        Decision::Deny => &["reject_once", "reject_always"],
656    };
657    let chosen = options
658        .iter()
659        .find(|o| wanted.contains(&o["kind"].as_str().unwrap_or("")))
660        .or_else(|| options.first());
661
662    match (decision, chosen) {
663        (Decision::Deny, None) => json!({"outcome":{"outcome":"cancelled"}}),
664        (_, Some(o)) => json!({"outcome":{"outcome":"selected","optionId": o["optionId"]}}),
665        _ => json!({"outcome":{"outcome":"cancelled"}}),
666    }
667}
668
669fn tool_name(update: &Value) -> String {
670    update["title"]
671        .as_str()
672        .or_else(|| update["kind"].as_str())
673        .or_else(|| update["toolCallId"].as_str())
674        .unwrap_or("tool")
675        .to_string()
676}
677
678/// Status of `tool_call_update`: `Some(true)` succeeded, `Some(false)` failed, `None` progress only.
679fn tool_update_ok(update: &Value) -> Option<bool> {
680    match update["status"].as_str().unwrap_or("") {
681        "completed" => Some(true),
682        "failed" => Some(false),
683        _ => None,
684    }
685}
686
687/// Extracts plain text from ACP `content` (`ToolCallContent::Content`) to avoid showing JSON envelopes in transcripts.
688/// Falls back to `rawOutput` when no text content is available.
689fn tool_result_text(update: &Value) -> Option<String> {
690    let mut parts: Vec<&str> = Vec::new();
691    for item in update
692        .get("content")
693        .and_then(|c| c.as_array())
694        .into_iter()
695        .flatten()
696    {
697        if let Some(t) = item
698            .get("content")
699            .and_then(|c| c.get("text"))
700            .and_then(|t| t.as_str())
701            .or_else(|| item.get("text").and_then(|t| t.as_str()))
702            .filter(|t| !t.trim().is_empty())
703        {
704            parts.push(t);
705        }
706    }
707    let text = if parts.is_empty() {
708        match update.get("rawOutput") {
709            Some(Value::Null) | None => return None,
710            Some(v) => v.as_str().map_or_else(|| v.to_string(), str::to_string),
711        }
712    } else {
713        parts.join("\n")
714    };
715    Some(truncate_chars(&text, 4000))
716}
717
718/// Truncates excessively long tool output to prevent transcripts and event logs from ballooning.
719fn truncate_chars(s: &str, max: usize) -> String {
720    if s.chars().count() <= max {
721        return s.to_string();
722    }
723    let mut out: String = s.chars().take(max).collect();
724    out.push('…');
725    out
726}
727
728/// Whether error text indicates rate limiting / quota exhaustion (`RESOURCE_EXHAUSTED`, HTTP 429, `quota exceeded`, `rate limit`).
729fn is_rate_limit_error(text: &str) -> bool {
730    let lower = text.to_ascii_lowercase();
731    if lower.contains("resource_exhausted")
732        || lower.contains("quota exceeded")
733        || lower.contains("rate limit")
734        || lower.contains("rate_limit")
735    {
736        return true;
737    }
738    // Standalone `429` (surrounded by non-digits) to avoid matching `4290` etc.
739    let b = lower.as_bytes();
740    lower.match_indices("429").any(|(i, _)| {
741        i.checked_sub(1)
742            .and_then(|prev| b.get(prev))
743            .is_none_or(|c| !c.is_ascii_digit())
744            && b.get(i + 3).is_none_or(|c| !c.is_ascii_digit())
745    })
746}
747
748/// Rate limit error -> "quota reached" `Quota` (no percentage, only `reached` flag); returns `None` for other errors.
749fn rate_limit_quota(agent: &str, error_text: &str) -> Option<ertangle_core::Quota> {
750    is_rate_limit_error(error_text).then(|| ertangle_core::Quota {
751        agent: agent.to_string(),
752        windows: Vec::new(),
753        reached: true,
754        warning: false,
755        updated_ms: ertangle_core::now_millis(),
756    })
757}
758
759/// After a successful turn: if previously rate-limited, emits recovered (`reached=false`) quota and clears flag; otherwise `None`.
760fn recovered_quota(
761    agent: &str,
762    limited: &std::sync::atomic::AtomicBool,
763) -> Option<ertangle_core::Quota> {
764    limited
765        .swap(false, Ordering::SeqCst)
766        .then(|| ertangle_core::Quota {
767            agent: agent.to_string(),
768            windows: Vec::new(),
769            reached: false,
770            warning: false,
771            updated_ms: ertangle_core::now_millis(),
772        })
773}
774
775/// Safely extracts ID from a JSON-RPC message; returns safe fallback (`Value::Null`) if missing or null.
776pub(crate) fn extract_request_id(msg: &Value) -> Value {
777    match msg.get("id") {
778        Some(id) if !id.is_null() => id.clone(),
779        _ => Value::Null,
780    }
781}
782
783fn reader_loop(conn: Arc<Conn>, stdout: impl BufRead) {
784    for line in stdout.lines() {
785        let Ok(line) = line else { break };
786        if line.trim().is_empty() {
787            continue;
788        }
789        let Ok(msg): Result<Value, _> = serde_json::from_str(&line) else {
790            continue;
791        };
792
793        if let Some(method) = msg.get("method").and_then(|m| m.as_str()) {
794            match msg.get("id") {
795                Some(_) => match method {
796                    "session/request_permission" => conn.on_permission(&msg),
797                    "elicitation/create" => conn.on_elicitation(&msg),
798                    _ => {
799                        let id = extract_request_id(&msg);
800                        conn.respond_error(&id, -32601, "not supported");
801                    }
802                },
803                None if method == "session/update" => {
804                    *conn.last_update.lock().unwrap_or_else(|e| e.into_inner()) =
805                        std::time::Instant::now();
806                    if !conn.loading.load(Ordering::SeqCst) {
807                        conn.on_update(&msg);
808                    }
809                }
810                None => {}
811            }
812        } else if let Some(id) = msg.get("id").and_then(|v| v.as_i64()) {
813            if let Some(s) = conn
814                .pending
815                .lock()
816                .unwrap_or_else(|e| e.into_inner())
817                .remove(&id)
818            {
819                // Ignore send result if the waiter already timed out and dropped.
820                let _ = s.send(msg);
821            }
822        }
823    }
824    conn.emit(AgentEvent::Exited(None));
825}
826
827struct AcpControl {
828    conn: Arc<Conn>,
829    child: Arc<Mutex<Child>>,
830    /// Most recently reported `configOptions` (wrapped as `{"configOptions": [...]}`), used to validate and find configId during runtime switches.
831    options: Mutex<Value>,
832}
833
834impl AgentControl for AcpControl {
835    fn send_input(&self, text: &str) -> Result<()> {
836        self.send_input_with(text, &[])
837    }
838
839    fn send_input_with(&self, text: &str, atts: &[ertangle_core::Attachment]) -> Result<()> {
840        let conn = self.conn.clone();
841        let text = text.to_string();
842        let atts = atts.to_vec();
843        std::thread::spawn(move || {
844            if let Err(e) = conn.prompt(&text, &atts) {
845                tracing::warn!("ACP prompt 失敗:{e}");
846                if ertangle_core::looks_like_limit(&e.to_string()) {
847                    conn.emit(AgentEvent::Limited(e.to_string()));
848                } else {
849                    // Otherwise the failure is only in the daemon log and the turn looks silently dropped.
850                    let note = tr!("ACP prompt 失敗:{err}", err = e);
851                    conn.emit(AgentEvent::Output(format!("⚠ {note}\n")));
852                    conn.emit(AgentEvent::Note(note));
853                }
854                conn.report_rate_limit(&e.to_string());
855            }
856            conn.refresh_quota_async();
857        });
858        Ok(())
859    }
860
861    /// `session/set_config_option`; response includes complete `configOptions`, also updating the cache.
862    fn set_config(&self, model: Option<&str>, effort: Option<&str>) -> Result<Option<String>> {
863        let sid = self
864            .conn
865            .acp_session
866            .lock()
867            .unwrap_or_else(|e| e.into_inner())
868            .clone();
869        let mut applied = None;
870        let mut jobs = Vec::new();
871        {
872            let opts = self.options.lock().unwrap_or_else(|e| e.into_inner());
873            if let Some(m) = model {
874                jobs.push(("model", pick_model_option(&opts, m)?));
875            }
876            if let Some(e) = effort {
877                jobs.push(("effort", pick_effort_option(&opts, e)?));
878            }
879        }
880        for (what, (config_id, value)) in jobs {
881            let r = self
882                .conn
883                .call(
884                    "session/set_config_option",
885                    json!({ "sessionId": sid, "configId": config_id, "value": value }),
886                    CALL_TIMEOUT,
887                )
888                .with_context(|| tr!("設定 {what} `{value}` 失敗", what = what, value = value))?;
889            if let Some(opts) = r.get("configOptions").filter(|co| co.is_array()) {
890                *self.options.lock().unwrap_or_else(|e| e.into_inner()) =
891                    json!({ "configOptions": opts });
892            }
893            if what == "model" {
894                applied = Some(value);
895            }
896        }
897        Ok(applied)
898    }
899
900    fn cancel(&self) -> Result<()> {
901        let sid = self
902            .conn
903            .acp_session
904            .lock()
905            .unwrap_or_else(|e| e.into_inner())
906            .clone();
907        if sid.is_empty() {
908            return Ok(());
909        }
910        self.conn.write(&json!({
911            "jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":sid}
912        }))
913    }
914
915    fn pid(&self) -> Option<u32> {
916        Some(self.child.lock().unwrap_or_else(|e| e.into_inner()).id())
917    }
918
919    fn kill(&self) -> Result<()> {
920        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
921        // Terminate the process group or process, ignoring signal send errors.
922        let _ = crate::signal_pgid(pid, "-KILL").or_else(|_| crate::signal_pid(pid, "-KILL"));
923        self.child
924            .lock()
925            .unwrap_or_else(|e| e.into_inner())
926            .kill()
927            .ok();
928        Ok(())
929    }
930
931    fn sleep(&self) -> Result<()> {
932        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
933        crate::signal_pgid(pid, "-STOP").or_else(|_| crate::signal_pid(pid, "-STOP"))
934    }
935
936    fn wake(&self) -> Result<()> {
937        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
938        crate::signal_pgid(pid, "-CONT").or_else(|_| crate::signal_pid(pid, "-CONT"))
939    }
940
941    fn resolve_permission(&self, req: &str, decision: Decision) -> Result<()> {
942        self.conn.resolve(req, decision)
943    }
944
945    fn resolve_question(&self, id: &str, answers: &[String]) -> Result<()> {
946        self.conn.resolve_question(id, answers)
947    }
948
949    fn transport(&self) -> &'static str {
950        "acp"
951    }
952}
953
954/// Takes the one-time collaboration prefix to prepend before the first prompt.
955fn take_effective_prompt(prepend_once: &Mutex<Option<String>>, text: &str) -> String {
956    match prepend_once
957        .lock()
958        .unwrap_or_else(|e| e.into_inner())
959        .take()
960    {
961        Some(prefix) if !prefix.trim().is_empty() => {
962            format!("{}\n\n{}", prefix.trim_end(), text)
963        }
964        _ => text.to_string(),
965    }
966}
967
968/// ACP prompt blocks: text (including inlined text files); adds image blocks if agent supports images, otherwise describes images as a text line.
969fn prompt_blocks(text: &str, atts: &[ertangle_core::Attachment], image_ok: bool) -> Value {
970    let mut blocks =
971        vec![json!({ "type": "text", "text": ertangle_core::compose_text(text, atts, !image_ok) })];
972    if image_ok {
973        for a in atts.iter().filter(|a| a.is_image()) {
974            if let Some(data) = &a.data {
975                blocks.push(json!({ "type": "image", "data": data, "mimeType": a.mime }));
976            }
977        }
978    }
979    Value::Array(blocks)
980}
981
982/// Returns true when `session/new` / `session/load` `configOptions` includes a model selector.
983fn has_model_option(new: &Value) -> bool {
984    new["configOptions"].as_array().is_some_and(|opts| {
985        opts.iter()
986            .any(|o| o["category"] == "model" || o["id"] == "model")
987    })
988}
989
990/// Returns true when `session/new` / `session/load` `configOptions` includes an effort selector.
991fn has_effort_option(new: &Value) -> bool {
992    let is_effort = |s: &str| {
993        let s = s.to_ascii_lowercase();
994        s.contains("effort") || s.contains("reasoning") || s.contains("thought")
995    };
996    new["configOptions"].as_array().is_some_and(|opts| {
997        opts.iter().any(|o| {
998            is_effort(o["id"].as_str().unwrap_or(""))
999                || is_effort(o["category"].as_str().unwrap_or(""))
1000        })
1001    })
1002}
1003
1004/// Finds model option from `session/new` response `configOptions` and validates `wanted`.
1005/// Returns `(configId, value)`; returns a clear error if the agent reported no model options or the value is not in the list.
1006fn pick_model_option(new: &Value, wanted: &str) -> Result<(String, String)> {
1007    let opts = new["configOptions"].as_array().cloned().unwrap_or_default();
1008    let opt = opts
1009        .iter()
1010        .find(|o| o["category"] == "model" || o["id"] == "model")
1011        .ok_or_else(|| {
1012            anyhow!(tr!(
1013                "此 agent 沒有回報可選的 model (configOptions 無 model 項)"
1014            ))
1015        })?;
1016    let id = opt["id"].as_str().unwrap_or("model").to_string();
1017    // Options may be flat [{value,name}] or grouped [{options:[...]}]
1018    let mut values: Vec<String> = Vec::new();
1019    for o in opt["options"].as_array().into_iter().flatten() {
1020        if let Some(v) = o["value"].as_str() {
1021            values.push(v.to_string());
1022        }
1023        for g in o["options"].as_array().into_iter().flatten() {
1024            if let Some(v) = g["value"].as_str() {
1025                values.push(v.to_string());
1026            }
1027        }
1028    }
1029    if !values.is_empty() && !values.iter().any(|v| v == wanted) {
1030        bail!(
1031            "{}",
1032            tr!(
1033                "未知的 model `{wanted}`;可用:{list}",
1034                wanted = wanted,
1035                list = values.join(", ")
1036            )
1037        );
1038    }
1039    Ok((id, wanted.to_string()))
1040}
1041
1042/// Finds reasoning effort option from `session/new` `configOptions` (id or category containing effort/reasoning/thought).
1043fn pick_effort_option(new: &Value, wanted: &str) -> Result<(String, String)> {
1044    let opts = new["configOptions"].as_array().cloned().unwrap_or_default();
1045    let is_effort = |s: &str| {
1046        let s = s.to_ascii_lowercase();
1047        s.contains("effort") || s.contains("reasoning") || s.contains("thought")
1048    };
1049    let opt = opts
1050        .iter()
1051        .find(|o| {
1052            is_effort(o["id"].as_str().unwrap_or(""))
1053                || is_effort(o["category"].as_str().unwrap_or(""))
1054        })
1055        .ok_or_else(|| {
1056            anyhow!(tr!(
1057                "此 agent 沒有回報可設定的 effort (configOptions 無相關項)"
1058            ))
1059        })?;
1060    let id = opt["id"].as_str().unwrap_or("effort").to_string();
1061    let values: Vec<String> = opt["options"]
1062        .as_array()
1063        .into_iter()
1064        .flatten()
1065        .filter_map(|o| o["value"].as_str().map(str::to_string))
1066        .collect();
1067    if !values.is_empty() && !values.iter().any(|v| v == wanted) {
1068        bail!(
1069            "{}",
1070            tr!(
1071                "effort `{wanted}` 不在可用清單:{list}",
1072                wanted = wanted,
1073                list = values.join(", ")
1074            )
1075        );
1076    }
1077    Ok((id, wanted.to_string()))
1078}
1079
1080/// Extra CLI flags passed to `copilot --acp` on fresh session startup.
1081///
1082/// Copilot CLI rejects `--model auto` unless `--reasoning-effort none` is also set
1083/// (it otherwise applies a default reasoning effort and fails `session/new`).
1084fn copilot_cli_args(spec: &SessionSpec) -> Vec<String> {
1085    if spec.kind != ertangle_core::AgentKind::Copilot || spec.resume.is_some() {
1086        return Vec::new();
1087    }
1088    let mut out = Vec::new();
1089    if let Some(m) = &spec.model {
1090        out.push("--model".to_string());
1091        out.push(m.clone());
1092    }
1093    if spec.model.as_deref() == Some("auto") {
1094        out.push("--reasoning-effort".to_string());
1095        out.push("none".to_string());
1096    } else if let Some(e) = &spec.effort {
1097        out.push("--reasoning-effort".to_string());
1098        out.push(e.clone());
1099    }
1100    out
1101}
1102
1103pub fn start(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
1104    let (default_prog, args) = spec
1105        .kind
1106        .acp_command()
1107        .with_context(|| tr!("此 agent 不支援原生結構化協定"))?;
1108    let prog = match spec.bin.as_deref() {
1109        Some(b) => crate::which(b).with_context(|| tr!("找不到指定的執行檔 `{b}`", b = b))?,
1110        None => crate::which(default_prog)
1111            .with_context(|| tr!("找不到 `{prog}`", prog = default_prog))?,
1112    };
1113
1114    let mut cmd = Command::new(&prog);
1115    cmd.args(args);
1116    cmd.args(copilot_cli_args(&spec));
1117    cmd.args(&spec.args)
1118        .current_dir(&spec.cwd)
1119        .stdin(Stdio::piped())
1120        .stdout(Stdio::piped())
1121        .stderr(Stdio::piped());
1122    for k in crate::env_removals(&spec.kind) {
1123        cmd.env_remove(k);
1124    }
1125    for (k, v) in &spec.env {
1126        cmd.env(k, v);
1127    }
1128    #[cfg(unix)]
1129    {
1130        use std::os::unix::process::CommandExt;
1131        cmd.process_group(0);
1132    }
1133    let mut child = cmd
1134        .spawn()
1135        .with_context(|| tr!("無法啟動 `{prog} acp`", prog = prog.display()))?;
1136
1137    let stdin = child.stdin.take().with_context(|| tr!("取得 stdin 失敗"))?;
1138    let stderr_tail = child.stderr.take().map(crate::stderr::StderrTail::spawn);
1139    let stdout = child
1140        .stdout
1141        .take()
1142        .with_context(|| tr!("取得 stdout 失敗"))?;
1143
1144    let quota_prog = if matches!(
1145        spec.kind,
1146        ertangle_core::AgentKind::Antigravity | ertangle_core::AgentKind::Copilot
1147    ) {
1148        Some((spec.kind.clone(), prog.clone(), spec.env.clone()))
1149    } else {
1150        None
1151    };
1152
1153    let (stream_poke, stream_rx) = mpsc::channel();
1154    let conn = Arc::new(Conn {
1155        agent: spec.kind.id().to_string(),
1156        limited: std::sync::atomic::AtomicBool::new(false),
1157        quota_prog,
1158        quota_refreshing: std::sync::atomic::AtomicBool::new(false),
1159        session_id: spec.id.clone(),
1160        acp_session: Mutex::new(String::new()),
1161        stdin: Mutex::new(stdin),
1162        next_id: AtomicI64::new(1),
1163        pending: Mutex::new(HashMap::new()),
1164        perms: Mutex::new(HashMap::new()),
1165        questions: Mutex::new(HashMap::new()),
1166        stream: Mutex::new(StreamBuf::default()),
1167        stream_poke,
1168        prepend_once: Mutex::new(spec.system_append.clone().filter(|s| !s.trim().is_empty())),
1169        image_ok: std::sync::atomic::AtomicBool::new(false),
1170        loading: std::sync::atomic::AtomicBool::new(false),
1171        last_update: Mutex::new(std::time::Instant::now()),
1172        turns: Mutex::new(TurnTracker::default()),
1173        tx: tx.clone(),
1174    });
1175
1176    {
1177        let weak = Arc::downgrade(&conn);
1178        std::thread::spawn(move || {
1179            // Exits once the connection is dropped (session ended).
1180            loop {
1181                std::thread::sleep(STALL_POLL);
1182                let Some(c) = weak.upgrade() else { return };
1183                c.check_stall(Instant::now());
1184            }
1185        });
1186    }
1187
1188    {
1189        let weak = Arc::downgrade(&conn);
1190        std::thread::spawn(move || {
1191            // Flush trailing partial lines after 250ms of stream silence so internal
1192            // background-task turns without `conn.prompt()` don't leak into the next prompt.
1193            while stream_rx.recv().is_ok() {
1194                loop {
1195                    match stream_rx.recv_timeout(Duration::from_millis(250)) {
1196                        Ok(()) => continue,
1197                        Err(mpsc::RecvTimeoutError::Timeout) => {
1198                            if let Some(c) = weak.upgrade() {
1199                                c.idle_flush_stream();
1200                            }
1201                            break;
1202                        }
1203                        Err(mpsc::RecvTimeoutError::Disconnected) => return,
1204                    }
1205                }
1206            }
1207        });
1208    }
1209
1210    {
1211        let conn = conn.clone();
1212        std::thread::spawn(move || reader_loop(conn, BufReader::new(stdout)));
1213    }
1214
1215    let child = Arc::new(Mutex::new(child));
1216    {
1217        let child = child.clone();
1218        let tx = tx.clone();
1219        std::thread::spawn(move || {
1220            // Poll with try_wait (rather than blocking wait) to avoid holding the lock indefinitely, which would deadlock `kill()`.
1221            let code = loop {
1222                let status = {
1223                    let mut c = child.lock().unwrap_or_else(|e| e.into_inner());
1224                    c.try_wait()
1225                };
1226                match status {
1227                    Ok(Some(s)) => break s.code(),
1228                    Ok(None) => std::thread::sleep(Duration::from_millis(100)),
1229                    Err(_) => break None,
1230                }
1231            };
1232            if let Some(t) = &stderr_tail {
1233                t.report_exit(code, &tx);
1234            }
1235            // Ignore exit event if the receiver is already closed.
1236            let _ = tx.send(AgentEvent::Exited(code));
1237        });
1238    }
1239
1240    // Handshake.
1241    let init = conn.call(
1242        "initialize",
1243        json!({
1244            "protocolVersion": 1,
1245            "clientInfo": {
1246                "name": "ertangle",
1247                "version": env!("CARGO_PKG_VERSION")
1248            },
1249            "clientCapabilities": {
1250                "fs": { "readTextFile": false, "writeTextFile": false },
1251                "elicitation": { "form": {} }
1252            }
1253        }),
1254        CALL_TIMEOUT,
1255    )?;
1256    tracing::debug!("ACP initialize: {init}");
1257    conn.image_ok.store(
1258        init.get("agentCapabilities")
1259            .and_then(|ac| ac.get("promptCapabilities"))
1260            .and_then(|pc| pc.get("image"))
1261            .and_then(|v| v.as_bool())
1262            .unwrap_or(false),
1263        Ordering::SeqCst,
1264    );
1265
1266    let mcp_servers = match &spec.mcp_exe {
1267        Some(exe) => {
1268            let mut args = vec!["mcp".to_string(), "--session".to_string(), spec.id.clone()];
1269            if let Some((_, sock)) = spec.env.iter().find(|(k, _)| k == "ERTANGLE_SOCKET") {
1270                args.push("--socket".to_string());
1271                args.push(sock.clone());
1272            }
1273            json!([{
1274                "name": "ertangle",
1275                "command": exe.to_string_lossy(),
1276                "args": args,
1277                "env": []
1278            }])
1279        }
1280        None => json!([]),
1281    };
1282    // Only agents declaring `loadSession` can be reconnected later.
1283    let can_load = init
1284        .get("agentCapabilities")
1285        .and_then(|ac| ac.get("loadSession"))
1286        .and_then(|v| v.as_bool())
1287        .unwrap_or(false);
1288    let (sid, new) = match &spec.resume {
1289        Some(id) => {
1290            if !can_load {
1291                bail!(
1292                    "{}",
1293                    tr!(
1294                        "{kind} 沒有宣告 loadSession,無法接續對話",
1295                        kind = spec.kind
1296                    )
1297                );
1298            }
1299            conn.loading.store(true, Ordering::SeqCst);
1300            let loaded = conn.call(
1301                "session/load",
1302                json!({ "sessionId": id, "cwd": spec.cwd.to_string_lossy(), "mcpServers": mcp_servers }),
1303                LOAD_TIMEOUT,
1304            );
1305            // Some ACP agents (e.g. agy) stream `session/load` replay updates after returning the response.
1306            // Keep discarding until the replay goes quiet; otherwise it lands after the initial prompt
1307            // and buries the user's message under the old conversation.
1308            *conn.last_update.lock().unwrap_or_else(|e| e.into_inner()) = std::time::Instant::now();
1309            wait_until_quiet(
1310                || *conn.last_update.lock().unwrap_or_else(|e| e.into_inner()),
1311                REPLAY_QUIET,
1312                REPLAY_MAX_WAIT,
1313            );
1314            conn.loading.store(false, Ordering::SeqCst);
1315            // Flush buffer after replay ends; ignore if empty.
1316            let _ = conn
1317                .stream
1318                .lock()
1319                .unwrap_or_else(|e| e.into_inner())
1320                .flush();
1321            (id.clone(), loaded?)
1322        }
1323        None => {
1324            let new = conn.call(
1325                "session/new",
1326                json!({ "cwd": spec.cwd.to_string_lossy(), "mcpServers": mcp_servers }),
1327                CALL_TIMEOUT,
1328            )?;
1329            let sid = new
1330                .get("sessionId")
1331                .and_then(|v| v.as_str())
1332                .with_context(|| tr!("`session/new` 未回傳 sessionId"))?
1333                .to_string();
1334            (sid, new)
1335        }
1336    };
1337    *conn.acp_session.lock().unwrap_or_else(|e| e.into_inner()) = sid.clone();
1338    if can_load {
1339        // Ignore event send if the receiver is already closed.
1340        let _ = tx.send(AgentEvent::NativeId(sid.clone()));
1341    }
1342    // When resuming, model/effort already exist in agent conversation; do not reset if response lacks configOptions.
1343    let has_options =
1344        spec.resume.is_none() || new.get("configOptions").is_some_and(|co| co.is_array());
1345    let is_copilot = spec.kind == ertangle_core::AgentKind::Copilot;
1346    if let Some(wanted) = spec.model.as_ref().filter(|_| has_options) {
1347        if !is_copilot || has_model_option(&new) {
1348            let (config_id, value) = pick_model_option(&new, wanted)?;
1349            conn.call(
1350                "session/set_config_option",
1351                json!({ "sessionId": sid, "configId": config_id, "value": value }),
1352                CALL_TIMEOUT,
1353            )
1354            .with_context(|| tr!("設定 model `{value}` 失敗", value = value))?;
1355            // Ignore event send if the receiver is already closed.
1356            let _ = tx.send(AgentEvent::Model(value));
1357        } else if spec.resume.is_none() {
1358            // Copilot received `--model` on the CLI when configOptions omitted `model`.
1359            let _ = tx.send(AgentEvent::Model(wanted.clone()));
1360        }
1361    }
1362    if let Some(e) = spec.effort.as_ref().filter(|_| has_options) {
1363        if !is_copilot || has_effort_option(&new) {
1364            let (config_id, value) = pick_effort_option(&new, e)?;
1365            conn.call(
1366                "session/set_config_option",
1367                json!({ "sessionId": sid, "configId": config_id, "value": value }),
1368                CALL_TIMEOUT,
1369            )
1370            .with_context(|| tr!("設定 effort `{value}` 失敗", value = value))?;
1371        }
1372    }
1373    let has_initial_prompt = spec
1374        .initial_prompt
1375        .as_deref()
1376        .is_some_and(|p| !p.trim().is_empty());
1377    // Ignore event send if the receiver is already closed.
1378    let _ = tx.send(AgentEvent::Status(if has_initial_prompt {
1379        SessionStatus::Busy
1380    } else {
1381        SessionStatus::Idle
1382    }));
1383    conn.refresh_quota_async();
1384
1385    let control = AcpControl {
1386        conn,
1387        child,
1388        options: Mutex::new(
1389            json!({ "configOptions": new.get("configOptions").cloned().unwrap_or(Value::Null) }),
1390        ),
1391    };
1392
1393    if let Some(p) = &spec.initial_prompt {
1394        control.send_input_with(p, &spec.initial_attachments)?;
1395    }
1396
1397    Ok(Box::new(control))
1398}
1399
1400/// Blocks until `last_activity()` is at least `quiet` old, or `max` has elapsed in total.
1401fn wait_until_quiet(
1402    last_activity: impl Fn() -> std::time::Instant,
1403    quiet: Duration,
1404    max: Duration,
1405) {
1406    let start = std::time::Instant::now();
1407    loop {
1408        let idle = last_activity().elapsed();
1409        let waited = start.elapsed();
1410        if idle >= quiet || waited >= max {
1411            return;
1412        }
1413        std::thread::sleep((quiet - idle).min(max - waited));
1414    }
1415}
1416
1417#[cfg(test)]
1418mod turn_tracker_tests {
1419    use super::*;
1420
1421    const T: Duration = Duration::from_secs(180);
1422
1423    #[test]
1424    fn idle_only_after_last_concurrent_turn_ends() {
1425        let mut t = TurnTracker::default();
1426        let now = Instant::now();
1427        t.begin(now);
1428        t.begin(now);
1429        assert_eq!(
1430            t.end(),
1431            None,
1432            "second turn finishing early must not report Idle"
1433        );
1434        assert_eq!(t.end(), Some(false));
1435    }
1436
1437    #[test]
1438    fn end_without_begin_does_not_underflow() {
1439        let mut t = TurnTracker::default();
1440        assert_eq!(t.end(), Some(false));
1441    }
1442
1443    #[test]
1444    fn no_stall_when_no_turn_running() {
1445        let mut t = TurnTracker::default();
1446        let now = Instant::now();
1447        assert_eq!(t.stalled(now + T * 2, now, T), None);
1448    }
1449
1450    #[test]
1451    fn warns_once_per_quiet_period_and_rearms_after_activity() {
1452        let mut t = TurnTracker::default();
1453        let start = Instant::now();
1454        t.begin(start);
1455        assert_eq!(t.stalled(start + T / 2, start, T), None);
1456        assert_eq!(t.stalled(start + T, start, T), Some(T));
1457        assert_eq!(t.stalled(start + T * 2, start, T), None, "already warned");
1458        let activity = start + T * 3;
1459        assert_eq!(t.stalled(activity + T, activity, T), Some(T));
1460        assert_eq!(t.end(), Some(true), "warning must be cleared on Idle");
1461    }
1462
1463    #[test]
1464    fn quiet_period_counts_from_turn_start_not_stale_update() {
1465        let mut t = TurnTracker::default();
1466        let old_update = Instant::now();
1467        let start = old_update + T * 5;
1468        t.begin(start);
1469        assert_eq!(t.stalled(start + T / 2, old_update, T), None);
1470    }
1471}
1472
1473#[cfg(test)]
1474mod replay_wait_tests {
1475    use super::*;
1476    use std::time::Instant;
1477
1478    #[test]
1479    fn returns_once_activity_goes_quiet() {
1480        let start = Instant::now();
1481        // Activity keeps arriving for the first 150ms, then stops.
1482        let last = || {
1483            let now = Instant::now();
1484            if now.duration_since(start) < Duration::from_millis(150) {
1485                now
1486            } else {
1487                start + Duration::from_millis(150)
1488            }
1489        };
1490        wait_until_quiet(last, Duration::from_millis(100), Duration::from_secs(5));
1491        let took = start.elapsed();
1492        assert!(
1493            took >= Duration::from_millis(250),
1494            "returned too early: {took:?}"
1495        );
1496        assert!(took < Duration::from_secs(2), "waited too long: {took:?}");
1497    }
1498
1499    #[test]
1500    fn gives_up_after_max_wait_when_activity_never_stops() {
1501        let start = Instant::now();
1502        wait_until_quiet(
1503            Instant::now,
1504            Duration::from_millis(100),
1505            Duration::from_millis(200),
1506        );
1507        let took = start.elapsed();
1508        assert!(
1509            took >= Duration::from_millis(200),
1510            "returned too early: {took:?}"
1511        );
1512        assert!(took < Duration::from_secs(2), "waited too long: {took:?}");
1513    }
1514
1515    #[test]
1516    fn returns_immediately_when_already_quiet() {
1517        let past = Instant::now() - Duration::from_secs(1);
1518        let start = Instant::now();
1519        wait_until_quiet(|| past, Duration::from_millis(100), Duration::from_secs(5));
1520        assert!(start.elapsed() < Duration::from_millis(50));
1521    }
1522}
1523
1524#[cfg(test)]
1525mod model_tests {
1526    use super::*;
1527
1528    #[test]
1529    fn elicitation_content_uses_scalar_for_single_select() {
1530        let entries = vec![
1531            ("strategy".to_string(), false, vec!["balanced".to_string()]),
1532            (
1533                "tags".to_string(),
1534                true,
1535                vec!["api".to_string(), "ui".to_string()],
1536            ),
1537        ];
1538        assert_eq!(
1539            elicitation_accept_content(&entries),
1540            json!({ "strategy": "balanced", "tags": ["api", "ui"] })
1541        );
1542        assert_eq!(
1543            elicitation_accept_content(&[("custom".to_string(), false, Vec::new())]),
1544            json!({ "custom": [] })
1545        );
1546    }
1547
1548    #[test]
1549    fn elicitation_response_keeps_selection_when_other_field_is_skipped() {
1550        let entries = vec![
1551            ("A1".to_string(), false, vec!["Postgres".to_string()]),
1552            ("A2".to_string(), false, Vec::new()),
1553        ];
1554        assert_eq!(
1555            elicitation_response(&entries),
1556            json!({ "action": "accept", "content": { "A1": "Postgres" } })
1557        );
1558        assert_eq!(
1559            elicitation_response(&[("A2".to_string(), false, Vec::new())]),
1560            json!({ "action": "decline" })
1561        );
1562    }
1563
1564    #[test]
1565    fn extracts_request_id_with_safe_fallback() {
1566        assert_eq!(extract_request_id(&json!({"id": 123})), json!(123));
1567        assert_eq!(extract_request_id(&json!({"id": "req-1"})), json!("req-1"));
1568        assert_eq!(extract_request_id(&json!({"id": null})), Value::Null);
1569        assert_eq!(
1570            extract_request_id(&json!({"method": "session/update"})),
1571            Value::Null
1572        );
1573        assert_eq!(extract_request_id(&json!(42)), Value::Null);
1574        assert_eq!(extract_request_id(&json!([])), Value::Null);
1575    }
1576
1577    #[test]
1578    fn picks_model_option_and_validates() {
1579        let new = json!({"sessionId":"x","configOptions":[
1580            {"id":"mode","category":"mode","options":[{"value":"a"}]},
1581            {"id":"model","category":"model","type":"select","options":[
1582                {"value":"p/m1","name":"M1"},{"value":"p/m2","name":"M2"}]}]});
1583        assert_eq!(pick_model_option(&new, "p/m2").unwrap().1, "p/m2");
1584        let e = pick_model_option(&new, "zzz").unwrap_err().to_string();
1585        assert!(e.contains("p/m1") && e.contains("zzz"));
1586        assert!(pick_model_option(&json!({"sessionId":"x"}), "a").is_err());
1587
1588        let copilot_new = json!({"sessionId":"x","configOptions":[
1589            {"id":"mode","category":"mode"},
1590            {"id":"allow_all","category":"permissions"}
1591        ]});
1592        assert!(!has_model_option(&copilot_new));
1593        assert!(!has_effort_option(&copilot_new));
1594        assert!(has_model_option(&new));
1595    }
1596
1597    #[test]
1598    fn copilot_cli_args_forces_reasoning_effort_none_for_auto_model() {
1599        let base = SessionSpec {
1600            id: "s".into(),
1601            kind: ertangle_core::AgentKind::Copilot,
1602            cwd: std::env::temp_dir(),
1603            transport: ertangle_protocol::Transport::Structured,
1604            bin: None,
1605            args: vec![],
1606            model: None,
1607            effort: None,
1608            allowed_tools: vec![],
1609            disallowed_tools: vec![],
1610            read_only: false,
1611            sandbox: None,
1612            env: vec![],
1613            permission: ertangle_core::PermissionPolicy::Auto,
1614            mcp_exe: None,
1615            system_append: None,
1616            initial_prompt: None,
1617            initial_attachments: vec![],
1618            resume: None,
1619            cols: 80,
1620            rows: 24,
1621        };
1622
1623        assert!(copilot_cli_args(&base).is_empty());
1624
1625        let auto_no_effort = SessionSpec {
1626            model: Some("auto".into()),
1627            ..base.clone()
1628        };
1629        assert_eq!(
1630            copilot_cli_args(&auto_no_effort),
1631            vec!["--model", "auto", "--reasoning-effort", "none"]
1632        );
1633
1634        let auto_with_effort = SessionSpec {
1635            model: Some("auto".into()),
1636            effort: Some("medium".into()),
1637            ..base.clone()
1638        };
1639        assert_eq!(
1640            copilot_cli_args(&auto_with_effort),
1641            vec!["--model", "auto", "--reasoning-effort", "none"]
1642        );
1643
1644        let explicit_model = SessionSpec {
1645            model: Some("claude-sonnet-4.5".into()),
1646            effort: Some("high".into()),
1647            ..base.clone()
1648        };
1649        assert_eq!(
1650            copilot_cli_args(&explicit_model),
1651            vec!["--model", "claude-sonnet-4.5", "--reasoning-effort", "high"]
1652        );
1653
1654        let resumed = SessionSpec {
1655            model: Some("auto".into()),
1656            resume: Some("prev".into()),
1657            ..base
1658        };
1659        assert!(copilot_cli_args(&resumed).is_empty());
1660    }
1661
1662    #[test]
1663    fn prepend_once_applies_only_to_first_prompt() {
1664        let p = Mutex::new(Some("[ertangle 協作說明]\n規則\n".to_string()));
1665        let first = take_effective_prompt(&p, "做任務 A");
1666        assert!(first.starts_with("[ertangle 協作說明]\n規則\n\n做任務 A"));
1667        let second = take_effective_prompt(&p, "做任務 B");
1668        assert_eq!(second, "做任務 B");
1669    }
1670
1671    #[test]
1672    fn tool_updates_only_report_final_states() {
1673        assert_eq!(tool_update_ok(&json!({"status":"pending"})), None);
1674        assert_eq!(tool_update_ok(&json!({"status":"in_progress"})), None);
1675        assert_eq!(tool_update_ok(&json!({})), None);
1676        assert_eq!(tool_update_ok(&json!({"status":"completed"})), Some(true));
1677        assert_eq!(tool_update_ok(&json!({"status":"failed"})), Some(false));
1678    }
1679
1680    #[test]
1681    fn tool_result_text_unwraps_acp_content() {
1682        let u = json!({"content":[{"type":"content","content":{"type":"text","text":"a\nb"}}]});
1683        assert_eq!(tool_result_text(&u).as_deref(), Some("a\nb"));
1684
1685        let u = json!({"content":[
1686            {"type":"content","content":{"type":"text","text":"x"}},
1687            {"type":"content","content":{"type":"text","text":"y"}}]});
1688        assert_eq!(tool_result_text(&u).as_deref(), Some("x\ny"));
1689
1690        assert_eq!(tool_result_text(&json!({})), None);
1691        // Diff content has no plain text: do not print raw JSON.
1692        assert_eq!(
1693            tool_result_text(&json!({"content":[{"type":"diff","path":"a.rs"}]})),
1694            None
1695        );
1696        // Fall back to rawOutput when content is absent.
1697        assert_eq!(
1698            tool_result_text(&json!({"rawOutput":{"exit":0}})).as_deref(),
1699            Some("{\"exit\":0}")
1700        );
1701    }
1702
1703    #[test]
1704    fn long_tool_output_is_truncated() {
1705        let s = "x".repeat(10);
1706        assert_eq!(truncate_chars(&s, 4), "xxxx…");
1707        assert_eq!(truncate_chars("abc", 4), "abc");
1708    }
1709}
1710
1711/// Agent kind, executable and environment used for quota queries.
1712type QuotaProg = (
1713    ertangle_core::AgentKind,
1714    std::path::PathBuf,
1715    Vec<(String, String)>,
1716);
1717
1718const QUOTA_QUERY_TIMEOUT: Duration = Duration::from_secs(15);
1719
1720/// Executes `agy --output-format json -p /quota` to obtain raw JSON; returns `None` on failure or timeout.
1721fn query_agy_quota(prog: &std::path::Path, env: &[(String, String)]) -> Option<String> {
1722    let mut cmd = Command::new(prog);
1723    cmd.args(["--output-format", "json", "-p", "/quota"])
1724        .stdin(Stdio::null())
1725        .stdout(Stdio::piped())
1726        .stderr(Stdio::null());
1727    for k in crate::env_removals(&ertangle_core::AgentKind::Antigravity) {
1728        cmd.env_remove(k);
1729    }
1730    for (k, v) in env {
1731        cmd.env(k, v);
1732    }
1733    let mut child = cmd.spawn().ok()?;
1734    let deadline = std::time::Instant::now() + QUOTA_QUERY_TIMEOUT;
1735    let status = loop {
1736        match child.try_wait() {
1737            Ok(Some(s)) => break s,
1738            Ok(None) if std::time::Instant::now() < deadline => {
1739                std::thread::sleep(Duration::from_millis(50));
1740            }
1741            _ => {
1742                // Force-kill and reap the child process on quota query timeout, ignoring errors.
1743                let _ = child.kill();
1744                let _ = child.wait();
1745                return None;
1746            }
1747        }
1748    };
1749    if !status.success() {
1750        return None;
1751    }
1752    let mut out = String::new();
1753    if let Some(mut so) = child.stdout.take() {
1754        use std::io::Read;
1755        so.read_to_string(&mut out).ok()?;
1756    }
1757    Some(out)
1758}
1759
1760/// Reads one `Content-Length` framed message body from `r`.
1761fn read_lsp_frame<R: std::io::BufRead>(r: &mut R) -> Option<String> {
1762    let mut len: Option<usize> = None;
1763    loop {
1764        let mut line = String::new();
1765        if r.read_line(&mut line).ok()? == 0 {
1766            return None;
1767        }
1768        let line = line.trim();
1769        if line.is_empty() {
1770            break;
1771        }
1772        if let Some((k, v)) = line.split_once(':') {
1773            if k.trim().eq_ignore_ascii_case("content-length") {
1774                len = v.trim().parse().ok();
1775            }
1776        }
1777    }
1778    let mut buf = vec![0u8; len?];
1779    r.read_exact(&mut buf).ok()?;
1780    String::from_utf8(buf).ok()
1781}
1782
1783/// Queries Copilot `account.getQuota` over `copilot --headless --no-auto-update --stdio`; returns the raw JSON-RPC response.
1784fn query_copilot_quota(prog: &std::path::Path, env: &[(String, String)]) -> Option<String> {
1785    use std::io::Write;
1786    let mut cmd = Command::new(prog);
1787    cmd.args(["--headless", "--no-auto-update", "--stdio"])
1788        .stdin(Stdio::piped())
1789        .stdout(Stdio::piped())
1790        .stderr(Stdio::null());
1791    for k in crate::env_removals(&ertangle_core::AgentKind::Copilot) {
1792        cmd.env_remove(k);
1793    }
1794    for (k, v) in env {
1795        cmd.env(k, v);
1796    }
1797    let mut child = cmd.spawn().ok()?;
1798    let body = r#"{"jsonrpc":"2.0","id":1,"method":"account.getQuota","params":{}}"#;
1799    let mut stdin = child.stdin.take();
1800    let stdout = child.stdout.take();
1801    let sent = stdin.as_mut().is_some_and(|si| {
1802        write!(si, "Content-Length: {}\r\n\r\n{body}", body.len())
1803            .and_then(|()| si.flush())
1804            .is_ok()
1805    });
1806    let result = match (sent, stdout) {
1807        (true, Some(so)) => {
1808            let (tx, rx) = mpsc::channel();
1809            std::thread::spawn(move || {
1810                let mut r = std::io::BufReader::new(so);
1811                // Receiver may have timed out and gone away; nothing to do then.
1812                let _ = tx.send(read_lsp_frame(&mut r));
1813            });
1814            rx.recv_timeout(QUOTA_QUERY_TIMEOUT).ok().flatten()
1815        }
1816        _ => None,
1817    };
1818    // Force-kill and reap so the process never lingers, ignoring errors.
1819    drop(stdin);
1820    let _ = child.kill();
1821    let _ = child.wait();
1822    result
1823}
1824
1825/// Parses a Copilot `account.getQuota` response into `Quota`.
1826pub(crate) fn parse_copilot_quota_json(
1827    raw: &str,
1828    reached: bool,
1829    now_ms: u64,
1830) -> Option<ertangle_core::Quota> {
1831    let v: Value = serde_json::from_str(raw.trim()).ok()?;
1832    let snaps = v
1833        .get("result")
1834        .and_then(|r| r.get("quotaSnapshots"))
1835        .or_else(|| v.get("quotaSnapshots"))
1836        .and_then(|s| s.as_object())?;
1837    let mut windows = Vec::new();
1838    let mut exhausted = false;
1839    for (name, b) in snaps {
1840        let unlimited = b["isUnlimitedEntitlement"].as_bool() == Some(true);
1841        if b["hasQuota"].as_bool() == Some(false)
1842            || (!unlimited && b["entitlementRequests"].as_f64().unwrap_or(0.0) <= 0.0)
1843        {
1844            continue;
1845        }
1846        let used_percent = if unlimited {
1847            0.0
1848        } else {
1849            let remaining = b["remainingPercentage"].as_f64().unwrap_or(100.0);
1850            (100.0 - remaining).clamp(0.0, 100.0) as f32
1851        };
1852        if !unlimited
1853            && used_percent >= 100.0
1854            && b["usageAllowedWithExhaustedQuota"].as_bool() != Some(true)
1855        {
1856            exhausted = true;
1857        }
1858        // `account.getQuota` may return the snapshot time itself, so only keep future resets.
1859        let resets_at_ms = b["resetDate"]
1860            .as_str()
1861            .and_then(parse_rfc3339_utc_ms)
1862            .filter(|&ms| ms > now_ms);
1863        windows.push(ertangle_core::QuotaWindow {
1864            name: name.clone(),
1865            used_percent,
1866            resets_at_ms,
1867        });
1868    }
1869    if windows.is_empty() {
1870        return None;
1871    }
1872    windows.sort_by_key(|w| {
1873        let rank = match w.name.as_str() {
1874            "premium_interactions" => 0,
1875            "chat" => 1,
1876            "completions" => 2,
1877            _ => 3,
1878        };
1879        (rank, w.name.clone())
1880    });
1881    Some(ertangle_core::Quota {
1882        agent: "copilot".into(),
1883        windows,
1884        reached: reached || exhausted,
1885        warning: false,
1886        updated_ms: now_ms,
1887    })
1888}
1889
1890/// Parses output of `agy --output-format json -p /quota` into `Quota`.
1891pub(crate) fn parse_agy_quota_json(raw: &str, reached: bool) -> Option<ertangle_core::Quota> {
1892    let v: Value = serde_json::from_str(raw.trim()).ok()?;
1893    let groups = v
1894        .get("command")
1895        .and_then(|c| c.get("data"))
1896        .and_then(|d| d.get("groups"))
1897        .and_then(|g| g.as_array())?;
1898    let mut windows = Vec::new();
1899    for g in groups {
1900        let group_name = g["name"].as_str().unwrap_or("");
1901        let Some(buckets) = g["buckets"].as_array() else {
1902            continue;
1903        };
1904        for b in buckets {
1905            let Some(remaining) = b["remaining_fraction"].as_f64() else {
1906                continue;
1907            };
1908            let id = b["id"].as_str().unwrap_or("");
1909            let win_raw = b["window"].as_str().unwrap_or("");
1910            let name = agy_window_name(group_name, id, win_raw);
1911            let used_percent = ((1.0 - remaining) * 100.0).clamp(0.0, 100.0) as f32;
1912            let resets_at_ms = b["reset_time"].as_str().and_then(parse_rfc3339_utc_ms);
1913            windows.push(ertangle_core::QuotaWindow {
1914                name,
1915                used_percent,
1916                resets_at_ms,
1917            });
1918        }
1919    }
1920    if windows.is_empty() {
1921        return None;
1922    }
1923    windows.sort_by_key(|w| {
1924        let rank = match w.name.as_str() {
1925            "5h" => 0,
1926            "7d" => 1,
1927            n if n.starts_with("argon") => 2,
1928            "3p-5h" => 3,
1929            "3p-7d" => 4,
1930            _ => 5,
1931        };
1932        (rank, w.name.clone())
1933    });
1934    let primary_exhausted = windows
1935        .iter()
1936        .any(|w| matches!(w.name.as_str(), "5h" | "7d") && w.used_percent >= 100.0);
1937    Some(ertangle_core::Quota {
1938        agent: "antigravity".into(),
1939        windows,
1940        reached: reached || primary_exhausted,
1941        warning: false,
1942        updated_ms: ertangle_core::now_millis(),
1943    })
1944}
1945
1946fn agy_window_name(group_name: &str, id: &str, window: &str) -> String {
1947    if id == "gemini-5h" || (group_name == "Gemini Models" && window == "5h") {
1948        return "5h".into();
1949    }
1950    if id == "gemini-weekly" || (group_name == "Gemini Models" && window == "weekly") {
1951        return "7d".into();
1952    }
1953    if id.contains("argon") || group_name.contains("Argon") {
1954        return match window {
1955            "5h" => "argon-5h".into(),
1956            "weekly" => "argon-7d".into(),
1957            other if !other.is_empty() => format!("argon-{other}"),
1958            _ => "argon".into(),
1959        };
1960    }
1961    if id.starts_with("3p-") || group_name.contains("Claude") {
1962        return match window {
1963            "5h" => "3p-5h".into(),
1964            "weekly" => "3p-7d".into(),
1965            _ => id.into(),
1966        };
1967    }
1968    match window {
1969        "weekly" => "7d".into(),
1970        other if !other.is_empty() => other.into(),
1971        _ => id.into(),
1972    }
1973}
1974
1975/// Parses UTC RFC 3339 timestamp string (`YYYY-MM-DDTHH:MM:SSZ` or with fractional seconds) to epoch milliseconds.
1976pub(crate) fn parse_rfc3339_utc_ms(s: &str) -> Option<u64> {
1977    let s = s.strip_suffix('Z')?;
1978    let (date, time) = s.split_once('T')?;
1979    let mut dp = date.split('-');
1980    let y: i64 = dp.next()?.parse().ok()?;
1981    let m: i64 = dp.next()?.parse().ok()?;
1982    let d: i64 = dp.next()?.parse().ok()?;
1983    if dp.next().is_some() || !(1..=12).contains(&m) || !(1..=31).contains(&d) {
1984        return None;
1985    }
1986    let hms = time.split('.').next()?;
1987    let mut tp = hms.split(':');
1988    let hh: i64 = tp.next()?.parse().ok()?;
1989    let mm: i64 = tp.next()?.parse().ok()?;
1990    let ss: i64 = tp.next()?.parse().ok()?;
1991    if tp.next().is_some()
1992        || !(0..=23).contains(&hh)
1993        || !(0..=59).contains(&mm)
1994        || !(0..=60).contains(&ss)
1995    {
1996        return None;
1997    }
1998    // Howard Hinnant's civil-from-days inverse: convert to days since Unix epoch.
1999    let y_adj = y - if m <= 2 { 1 } else { 0 };
2000    let era = y_adj.div_euclid(400);
2001    let yoe = y_adj.rem_euclid(400);
2002    let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + d - 1;
2003    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
2004    let days = era * 146097 + doe - 719468;
2005    let secs = days
2006        .checked_mul(86_400)?
2007        .checked_add(hh.checked_mul(3_600)?)?
2008        .checked_add(mm.checked_mul(60)?)?
2009        .checked_add(ss)?;
2010    u64::try_from(secs).ok()?.checked_mul(1_000)
2011}
2012
2013#[cfg(test)]
2014mod rate_limit_tests {
2015    use super::*;
2016
2017    #[test]
2018    fn detects_rate_limit_errors() {
2019        let samples = [
2020            r#"`session/prompt` 失敗:{"code":-32000,"message":"RESOURCE_EXHAUSTED: Quota exceeded for metric"}"#,
2021            r#"{"code":429,"message":"Too Many Requests"}"#,
2022            r#"{"message":"You have hit the rate limit"}"#,
2023            r#"{"sessionUpdate":"error","error":{"message":"HTTP 429"}}"#,
2024        ];
2025        for s in samples {
2026            let q = rate_limit_quota("antigravity", s).expect(s);
2027            assert!(q.reached);
2028            assert_eq!(q.agent, "antigravity");
2029            assert!(q.windows.is_empty());
2030        }
2031    }
2032
2033    #[test]
2034    fn recovery_clears_limit_once() {
2035        let flag = std::sync::atomic::AtomicBool::new(false);
2036        assert!(recovered_quota("antigravity", &flag).is_none());
2037        flag.store(true, Ordering::SeqCst);
2038        let q = recovered_quota("antigravity", &flag).expect("reset");
2039        assert!(!q.reached && !q.warning && q.windows.is_empty());
2040        assert_eq!(q.agent, "antigravity");
2041        assert!(recovered_quota("antigravity", &flag).is_none());
2042    }
2043
2044    #[test]
2045    fn ignores_other_errors() {
2046        for s in [
2047            r#"{"code":-32603,"message":"internal error"}"#,
2048            r#"{"message":"tokens used: 14290"}"#,
2049            r#"{"message":"invalid params"}"#,
2050        ] {
2051            assert!(rate_limit_quota("antigravity", s).is_none(), "{s}");
2052        }
2053    }
2054
2055    #[test]
2056    fn parses_rfc3339_utc_ms() {
2057        assert_eq!(parse_rfc3339_utc_ms("1970-01-01T00:00:00Z"), Some(0));
2058        assert_eq!(
2059            parse_rfc3339_utc_ms("2026-11-19T15:43:56Z"),
2060            Some(1_795_103_036_000)
2061        );
2062        assert_eq!(
2063            parse_rfc3339_utc_ms("2026-11-19T15:43:56.123Z"),
2064            Some(1_795_103_036_000)
2065        );
2066        assert!(parse_rfc3339_utc_ms("2026-11-19T15:43:56+08:00").is_none());
2067    }
2068
2069    #[test]
2070    fn parses_agy_quota_json_sample() {
2071        let sample = r#"{
2072            "conversation_id": "",
2073            "status": "SUCCESS",
2074            "command": {
2075                "name": "usage",
2076                "data": {
2077                    "groups": [
2078                        {
2079                            "name": "Gemini Models",
2080                            "buckets": [
2081                                {"id": "gemini-weekly", "window": "weekly", "remaining_fraction": 0.39, "reset_time": "2026-11-25T13:49:39Z"},
2082                                {"id": "gemini-5h", "window": "5h", "remaining_fraction": 0.93, "reset_time": "2026-11-19T15:43:56Z"}
2083                            ]
2084                        },
2085                        {
2086                            "name": "Claude and GPT models",
2087                            "buckets": [
2088                                {"id": "3p-weekly", "window": "weekly", "remaining_fraction": 0.10, "reset_time": "2026-11-26T10:58:54Z"},
2089                                {"id": "3p-5h", "window": "5h", "remaining_fraction": 1, "reset_time": "2026-11-19T15:58:54Z"}
2090                            ]
2091                        },
2092                        {
2093                            "name": "Gemini 4 Argon",
2094                            "buckets": [
2095                                {"id": "gemini-argon-wtu-weekly", "window": "weekly", "remaining_fraction": 0.78, "reset_time": "2026-11-25T13:41:45Z"}
2096                            ]
2097                        }
2098                    ]
2099                }
2100            }
2101        }"#;
2102        let q = parse_agy_quota_json(sample, false).expect("valid agy quota");
2103        assert_eq!(q.agent, "antigravity");
2104        assert!(!q.reached);
2105        assert_eq!(q.windows.len(), 5);
2106        assert_eq!(q.windows[0].name, "5h");
2107        assert!((q.windows[0].used_percent - 7.0).abs() < 0.01);
2108        assert_eq!(q.windows[1].name, "7d");
2109        assert!((q.windows[1].used_percent - 61.0).abs() < 0.01);
2110        assert_eq!(q.windows[2].name, "argon-7d");
2111        assert_eq!(q.windows[3].name, "3p-5h");
2112        assert_eq!(q.windows[4].name, "3p-7d");
2113        assert_eq!(q.windows[0].resets_at_ms, Some(1_795_103_036_000));
2114        assert_eq!(q.max_used(), 61.0);
2115        assert_eq!(q.max_used_live(0), 61.0);
2116        assert!(!q.reached);
2117    }
2118
2119    #[test]
2120    fn marks_reached_when_primary_window_exhausted() {
2121        let sample = r#"{"command":{"name":"usage","data":{"groups":[{"name":"Gemini Models","buckets":[{"id":"gemini-5h","window":"5h","remaining_fraction":0.0}]}]}}}"#;
2122        let q = parse_agy_quota_json(sample, false).expect("exhausted");
2123        assert!(q.reached);
2124        assert!((q.windows[0].used_percent - 100.0).abs() < 0.01);
2125        assert!(parse_agy_quota_json("not json", false).is_none());
2126    }
2127
2128    #[test]
2129    fn copilot_quota_skips_inactive_and_not_reached() {
2130        let sample = r#"{"result":{"quotaSnapshots":{
2131            "chat":{"hasQuota":true,"entitlementRequests":100,"remainingPercentage":99.8,"resetDate":"2026-11-19T15:43:56Z"},
2132            "completions":{"hasQuota":true,"entitlementRequests":100,"remainingPercentage":100},
2133            "premium_interactions":{"hasQuota":false,"entitlementRequests":0,"remainingPercentage":0}}}}"#;
2134        let q = parse_copilot_quota_json(sample, false, 0).expect("valid");
2135        assert_eq!(q.agent, "copilot");
2136        assert!(!q.reached);
2137        let names: Vec<_> = q.windows.iter().map(|w| w.name.as_str()).collect();
2138        assert_eq!(names, ["chat", "completions"]);
2139        assert!((q.windows[0].used_percent - 0.2).abs() < 0.01);
2140    }
2141
2142    #[test]
2143    fn copilot_quota_exhausted_sets_reached() {
2144        let sample = r#"{"quotaSnapshots":{"premium_interactions":{"hasQuota":true,"entitlementRequests":100,"remainingPercentage":0,"usageAllowedWithExhaustedQuota":false}}}"#;
2145        let q = parse_copilot_quota_json(sample, false, 0).expect("exhausted");
2146        assert!(q.reached);
2147        let ok = r#"{"quotaSnapshots":{"premium_interactions":{"hasQuota":true,"entitlementRequests":100,"remainingPercentage":0,"usageAllowedWithExhaustedQuota":true}}}"#;
2148        assert!(!parse_copilot_quota_json(ok, false, 0).expect("ok").reached);
2149    }
2150
2151    #[test]
2152    fn copilot_quota_unlimited_and_reset_filtering() {
2153        let sample = r#"{"result":{"quotaSnapshots":{
2154            "chat":{"isUnlimitedEntitlement":true,"remainingPercentage":0,"resetDate":"2026-11-19T15:43:56Z"},
2155            "completions":{"entitlementRequests":10,"remainingPercentage":50,"resetDate":"2026-11-19T15:43:56Z"}}}}"#;
2156        let past = parse_copilot_quota_json(sample, false, 1_795_103_036_000).expect("past");
2157        assert_eq!(past.windows[0].used_percent, 0.0);
2158        assert!(!past.reached);
2159        assert!(past.windows.iter().all(|w| w.resets_at_ms.is_none()));
2160        let future = parse_copilot_quota_json(sample, false, 1_795_103_035_999).expect("future");
2161        assert_eq!(future.windows[1].resets_at_ms, Some(1_795_103_036_000));
2162    }
2163
2164    #[test]
2165    fn copilot_quota_invalid_json_is_none() {
2166        assert!(parse_copilot_quota_json("not json", false, 0).is_none());
2167    }
2168}