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    /// Antigravity-specific: executable and environment variables for `agy --output-format json -p /quota`.
153    quota_prog: Option<(std::path::PathBuf, Vec<(String, String)>)>,
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        // 寫入失敗代表接收端通道已關閉,無需處理
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        // 若 agent stdin 已關閉則忽略回應寫入錯誤
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        // 若 agent stdin 已關閉則忽略回應寫入錯誤
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((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: 原子操作 store 保證不失敗,確保 Drop 不會 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            if let Some(raw) = query_agy_quota(&prog, &env) {
339                let reached = conn.limited.load(Ordering::SeqCst);
340                if let Some(q) = parse_agy_quota_json(&raw, reached) {
341                    conn.emit(AgentEvent::Quota(q));
342                }
343            }
344        });
345    }
346
347    fn on_update(&self, msg: &Value) {
348        let update = msg
349            .get("params")
350            .and_then(|p| p.get("update"))
351            .unwrap_or(&Value::Null);
352        let kind = update["sessionUpdate"].as_str().unwrap_or("");
353        match kind {
354            "available_commands_update" => {
355                let names: Vec<String> = update["availableCommands"]
356                    .as_array()
357                    .into_iter()
358                    .flatten()
359                    .filter_map(|c| c["name"].as_str())
360                    .map(|n| n.trim_start_matches('/').to_string())
361                    .collect();
362                self.emit(AgentEvent::Commands(names));
363            }
364            "usage_update" => {
365                // ACP: `used` (current context tokens) and `size` (window size).
366                if let Some(used) = update["used"].as_u64() {
367                    self.emit(AgentEvent::Context {
368                        used,
369                        window: update["size"].as_u64(),
370                    });
371                }
372            }
373            "error" => {
374                self.report_rate_limit(&update.to_string());
375            }
376            "agent_message_chunk" => {
377                if let Some(t) = update
378                    .get("content")
379                    .and_then(|c| c.get("text"))
380                    .and_then(|t| t.as_str())
381                {
382                    let chunk = self
383                        .stream
384                        .lock()
385                        .unwrap_or_else(|e| e.into_inner())
386                        .push_chunk("msg", t);
387                    self.send_chunk(chunk);
388                    // 串流提示喚醒失敗則忽略
389                    let _ = self.stream_poke.send(());
390                }
391            }
392            "agent_thought_chunk" => {
393                if let Some(t) = update
394                    .get("content")
395                    .and_then(|c| c.get("text"))
396                    .and_then(|t| t.as_str())
397                {
398                    let chunk = self
399                        .stream
400                        .lock()
401                        .unwrap_or_else(|e| e.into_inner())
402                        .push_chunk("think", t);
403                    self.send_chunk(chunk);
404                    // 串流提示喚醒失敗則忽略
405                    let _ = self.stream_poke.send(());
406                }
407            }
408            "tool_call" => {
409                self.flush_stream();
410                let name = tool_name(update);
411                let raw_input = &update["rawInput"];
412                let input = raw_input.to_string();
413                // ACP emits an empty rawInput placeholder before the real elicitation request.
414                // Creating a question here would show "{}" instead of the actual prompt.
415                let empty_placeholder = raw_input.as_object().is_some_and(|obj| obj.is_empty())
416                    || raw_input.as_str().is_some_and(str::is_empty);
417                if !empty_placeholder && crate::question::is_question_tool(&name) {
418                    let questions =
419                        crate::question::parse_tool_call_questions(&self.session_id, &name, &input);
420                    if !questions.is_empty() {
421                        let total = questions.len();
422                        let shared_answers = Arc::new(Mutex::new(Vec::new()));
423                        let mut q_map = self.questions.lock().unwrap_or_else(|e| e.into_inner());
424                        for q in questions {
425                            q_map.insert(
426                                q.id.clone(),
427                                PendingAcpQuestion::ToolCall {
428                                    total,
429                                    answers: Arc::clone(&shared_answers),
430                                },
431                            );
432                            self.emit(AgentEvent::Question(q));
433                        }
434                    }
435                }
436                self.emit(AgentEvent::ToolCall {
437                    name,
438                    input,
439                    ok: None,
440                    output: None,
441                });
442            }
443            "tool_call_update" => {
444                // ACP reports the same tool incrementally with pending/in_progress; only completed/failed
445                // is the final result. Previously "not completed" was treated as failure, causing successful
446                // shell calls to emit an extra `✗ failed` line.
447                let Some(ok) = tool_update_ok(update) else {
448                    return;
449                };
450                let name = tool_name(update);
451                let output = tool_result_text(update);
452                self.emit(AgentEvent::ToolCall {
453                    name,
454                    input: String::new(),
455                    ok: Some(ok),
456                    output,
457                });
458            }
459            _ => {}
460        }
461    }
462
463    /// Flushes remaining buffered lines (called before switching event types or tool calls).
464    fn flush_stream(&self) {
465        let chunk = self
466            .stream
467            .lock()
468            .unwrap_or_else(|e| e.into_inner())
469            .flush_chunk();
470        self.send_chunk(chunk);
471    }
472
473    /// Flushes buffered text after a stream pause *without* a trailing newline, so the
474    /// next chunk continues the same transcript line instead of splitting it mid-token.
475    fn idle_flush_stream(&self) {
476        let chunk = self
477            .stream
478            .lock()
479            .unwrap_or_else(|e| e.into_inner())
480            .idle_flush_chunk();
481        self.send_chunk(chunk);
482    }
483
484    fn send_chunk(&self, chunk: crate::stream::Chunk) {
485        if chunk.text.is_empty() {
486            return;
487        }
488        let ev = if chunk.append {
489            AgentEvent::OutputAppend(chunk.text)
490        } else {
491            AgentEvent::Output(chunk.text)
492        };
493        self.emit(ev);
494    }
495
496    fn on_permission(&self, msg: &Value) {
497        let jid = extract_request_id(msg);
498        let params = &msg["params"];
499        let options = params["options"].as_array().cloned().unwrap_or_default();
500
501        // Always forward to daemon: rule engine and session policy (auto/bypass auto-approval) are evaluated there.
502        let req = new_id("perm");
503        let title = params
504            .get("toolCall")
505            .and_then(|tc| tc.get("title"))
506            .and_then(|t| t.as_str())
507            .unwrap_or("permission")
508            .to_string();
509        let detail = params
510            .get("toolCall")
511            .and_then(|tc| tc.get("rawInput"))
512            .map_or_else(String::new, |v| v.to_string());
513        self.perms
514            .lock()
515            .unwrap_or_else(|e| e.into_inner())
516            .insert(req.clone(), (jid, options));
517        self.emit(AgentEvent::Permission(PermissionRequest {
518            req,
519            session: self.session_id.clone(),
520            title,
521            detail,
522        }));
523    }
524
525    fn resolve(&self, req: &str, decision: Decision) -> Result<()> {
526        let entry = self
527            .perms
528            .lock()
529            .unwrap_or_else(|e| e.into_inner())
530            .remove(req);
531        let Some((jid, options)) = entry else {
532            bail!("{}", tr!("未知的核准請求:{req}", req = req));
533        };
534        self.respond(&jid, decision_result(decision, &options));
535        Ok(())
536    }
537
538    fn on_elicitation(&self, msg: &Value) {
539        let jid = extract_request_id(msg);
540        let params = &msg["params"];
541        let list = crate::question::parse_acp_elicitations(&self.session_id, params);
542        if list.is_empty() {
543            self.respond_error(&jid, -32602, "invalid elicitation params");
544            return;
545        }
546        let total = list.len();
547        let shared_answers = Arc::new(Mutex::new(HashMap::new()));
548        let mut q_map = self.questions.lock().unwrap_or_else(|e| e.into_inner());
549        for (q, key) in list {
550            let option_values = q
551                .options
552                .iter()
553                .filter_map(|opt| opt.value.clone().map(|value| (opt.label.clone(), value)))
554                .collect();
555            q_map.insert(
556                q.id.clone(),
557                PendingAcpQuestion::Elicitation {
558                    rpc_id: jid.clone(),
559                    key,
560                    multi_select: q.multi_select,
561                    total,
562                    answers: Arc::clone(&shared_answers),
563                    option_values,
564                },
565            );
566            self.emit(AgentEvent::Question(q));
567        }
568    }
569
570    fn resolve_question(&self, id: &str, answers: &[String]) -> Result<()> {
571        let entry = self
572            .questions
573            .lock()
574            .unwrap_or_else(|e| e.into_inner())
575            .remove(id);
576        let Some(pending) = entry else {
577            bail!("{}", tr!("未知的問題請求:{id}", id = id));
578        };
579        match pending {
580            PendingAcpQuestion::Elicitation {
581                rpc_id,
582                key,
583                multi_select,
584                total,
585                answers: shared_answers,
586                option_values,
587            } => {
588                // An empty answer means the human skipped this field, which is normal for
589                // companion fields such as "Other". Keep it as an omitted field instead of
590                // declining the whole form; a real selection in another field still wins.
591                let submitted: Vec<String> = answers
592                    .iter()
593                    .map(|answer| {
594                        option_values
595                            .get(answer)
596                            .cloned()
597                            .unwrap_or_else(|| answer.clone())
598                    })
599                    .collect();
600                let mut map = shared_answers.lock().unwrap_or_else(|e| e.into_inner());
601                map.insert(key, (multi_select, submitted));
602                if map.len() < total {
603                    return Ok(());
604                }
605                let entries: Vec<(String, bool, Vec<String>)> = map
606                    .iter()
607                    .map(|(k, (multi, ans))| (k.clone(), *multi, ans.clone()))
608                    .collect();
609                drop(map);
610
611                let mut q_map = self.questions.lock().unwrap_or_else(|e| e.into_inner());
612                q_map.retain(|_, v| match v {
613                    PendingAcpQuestion::Elicitation { rpc_id: r, .. } => r != &rpc_id,
614                    _ => true,
615                });
616                drop(q_map);
617
618                self.respond(&rpc_id, elicitation_response(&entries));
619            }
620            PendingAcpQuestion::ToolCall {
621                total,
622                answers: shared_answers,
623            } => {
624                let mut list = shared_answers.lock().unwrap_or_else(|e| e.into_inner());
625                if answers.is_empty() {
626                    // Preserve one slot per skipped question so a grouped request still completes.
627                    list.push(String::new());
628                } else {
629                    list.extend(answers.iter().cloned());
630                }
631                if list.len() >= total {
632                    let ans_str = list.join("\n");
633                    self.emit(AgentEvent::Output(format!("↳ {ans_str}\n")));
634                }
635            }
636        }
637        Ok(())
638    }
639}
640
641/// Translates normalized [`Decision`] to ACP `outcome`.
642fn decision_result(decision: Decision, options: &[Value]) -> Value {
643    let wanted: &[&str] = match decision {
644        Decision::Allow => &["allow_once", "allow_always"],
645        Decision::AllowAlways => &["allow_always", "allow_once"],
646        Decision::Deny => &["reject_once", "reject_always"],
647    };
648    let chosen = options
649        .iter()
650        .find(|o| wanted.contains(&o["kind"].as_str().unwrap_or("")))
651        .or_else(|| options.first());
652
653    match (decision, chosen) {
654        (Decision::Deny, None) => json!({"outcome":{"outcome":"cancelled"}}),
655        (_, Some(o)) => json!({"outcome":{"outcome":"selected","optionId": o["optionId"]}}),
656        _ => json!({"outcome":{"outcome":"cancelled"}}),
657    }
658}
659
660fn tool_name(update: &Value) -> String {
661    update["title"]
662        .as_str()
663        .or_else(|| update["kind"].as_str())
664        .or_else(|| update["toolCallId"].as_str())
665        .unwrap_or("tool")
666        .to_string()
667}
668
669/// Status of `tool_call_update`: `Some(true)` succeeded, `Some(false)` failed, `None` progress only.
670fn tool_update_ok(update: &Value) -> Option<bool> {
671    match update["status"].as_str().unwrap_or("") {
672        "completed" => Some(true),
673        "failed" => Some(false),
674        _ => None,
675    }
676}
677
678/// Extracts plain text from ACP `content` (`ToolCallContent::Content`) to avoid showing JSON envelopes in transcripts.
679/// Falls back to `rawOutput` when no text content is available.
680fn tool_result_text(update: &Value) -> Option<String> {
681    let mut parts: Vec<&str> = Vec::new();
682    for item in update
683        .get("content")
684        .and_then(|c| c.as_array())
685        .into_iter()
686        .flatten()
687    {
688        if let Some(t) = item
689            .get("content")
690            .and_then(|c| c.get("text"))
691            .and_then(|t| t.as_str())
692            .or_else(|| item.get("text").and_then(|t| t.as_str()))
693            .filter(|t| !t.trim().is_empty())
694        {
695            parts.push(t);
696        }
697    }
698    let text = if parts.is_empty() {
699        match update.get("rawOutput") {
700            Some(Value::Null) | None => return None,
701            Some(v) => v.as_str().map_or_else(|| v.to_string(), str::to_string),
702        }
703    } else {
704        parts.join("\n")
705    };
706    Some(truncate_chars(&text, 4000))
707}
708
709/// Truncates excessively long tool output to prevent transcripts and event logs from ballooning.
710fn truncate_chars(s: &str, max: usize) -> String {
711    if s.chars().count() <= max {
712        return s.to_string();
713    }
714    let mut out: String = s.chars().take(max).collect();
715    out.push('…');
716    out
717}
718
719/// Whether error text indicates rate limiting / quota exhaustion (`RESOURCE_EXHAUSTED`, HTTP 429, `quota exceeded`, `rate limit`).
720fn is_rate_limit_error(text: &str) -> bool {
721    let lower = text.to_ascii_lowercase();
722    if lower.contains("resource_exhausted")
723        || lower.contains("quota exceeded")
724        || lower.contains("rate limit")
725        || lower.contains("rate_limit")
726    {
727        return true;
728    }
729    // Standalone `429` (surrounded by non-digits) to avoid matching `4290` etc.
730    let b = lower.as_bytes();
731    lower.match_indices("429").any(|(i, _)| {
732        i.checked_sub(1)
733            .and_then(|prev| b.get(prev))
734            .is_none_or(|c| !c.is_ascii_digit())
735            && b.get(i + 3).is_none_or(|c| !c.is_ascii_digit())
736    })
737}
738
739/// Rate limit error -> "quota reached" `Quota` (no percentage, only `reached` flag); returns `None` for other errors.
740fn rate_limit_quota(agent: &str, error_text: &str) -> Option<ertangle_core::Quota> {
741    is_rate_limit_error(error_text).then(|| ertangle_core::Quota {
742        agent: agent.to_string(),
743        windows: Vec::new(),
744        reached: true,
745        warning: false,
746        updated_ms: ertangle_core::now_millis(),
747    })
748}
749
750/// After a successful turn: if previously rate-limited, emits recovered (`reached=false`) quota and clears flag; otherwise `None`.
751fn recovered_quota(
752    agent: &str,
753    limited: &std::sync::atomic::AtomicBool,
754) -> Option<ertangle_core::Quota> {
755    limited
756        .swap(false, Ordering::SeqCst)
757        .then(|| ertangle_core::Quota {
758            agent: agent.to_string(),
759            windows: Vec::new(),
760            reached: false,
761            warning: false,
762            updated_ms: ertangle_core::now_millis(),
763        })
764}
765
766/// Safely extracts ID from a JSON-RPC message; returns safe fallback (`Value::Null`) if missing or null.
767pub(crate) fn extract_request_id(msg: &Value) -> Value {
768    match msg.get("id") {
769        Some(id) if !id.is_null() => id.clone(),
770        _ => Value::Null,
771    }
772}
773
774fn reader_loop(conn: Arc<Conn>, stdout: impl BufRead) {
775    for line in stdout.lines() {
776        let Ok(line) = line else { break };
777        if line.trim().is_empty() {
778            continue;
779        }
780        let Ok(msg): Result<Value, _> = serde_json::from_str(&line) else {
781            continue;
782        };
783
784        if let Some(method) = msg.get("method").and_then(|m| m.as_str()) {
785            match msg.get("id") {
786                Some(_) => match method {
787                    "session/request_permission" => conn.on_permission(&msg),
788                    "elicitation/create" => conn.on_elicitation(&msg),
789                    _ => {
790                        let id = extract_request_id(&msg);
791                        conn.respond_error(&id, -32601, "not supported");
792                    }
793                },
794                None if method == "session/update" => {
795                    *conn.last_update.lock().unwrap_or_else(|e| e.into_inner()) =
796                        std::time::Instant::now();
797                    if !conn.loading.load(Ordering::SeqCst) {
798                        conn.on_update(&msg);
799                    }
800                }
801                None => {}
802            }
803        } else if let Some(id) = msg.get("id").and_then(|v| v.as_i64()) {
804            if let Some(s) = conn
805                .pending
806                .lock()
807                .unwrap_or_else(|e| e.into_inner())
808                .remove(&id)
809            {
810                // 等待回應者若已逾時放棄則忽略傳送結果
811                let _ = s.send(msg);
812            }
813        }
814    }
815    conn.emit(AgentEvent::Exited(None));
816}
817
818struct AcpControl {
819    conn: Arc<Conn>,
820    child: Arc<Mutex<Child>>,
821    /// Most recently reported `configOptions` (wrapped as `{"configOptions": [...]}`), used to validate and find configId during runtime switches.
822    options: Mutex<Value>,
823}
824
825impl AgentControl for AcpControl {
826    fn send_input(&self, text: &str) -> Result<()> {
827        self.send_input_with(text, &[])
828    }
829
830    fn send_input_with(&self, text: &str, atts: &[ertangle_core::Attachment]) -> Result<()> {
831        let conn = self.conn.clone();
832        let text = text.to_string();
833        let atts = atts.to_vec();
834        std::thread::spawn(move || {
835            if let Err(e) = conn.prompt(&text, &atts) {
836                tracing::warn!("ACP prompt 失敗:{e}");
837                if ertangle_core::looks_like_limit(&e.to_string()) {
838                    conn.emit(AgentEvent::Limited(e.to_string()));
839                } else {
840                    // Otherwise the failure is only in the daemon log and the turn looks silently dropped.
841                    let note = tr!("ACP prompt 失敗:{err}", err = e);
842                    conn.emit(AgentEvent::Output(format!("⚠ {note}\n")));
843                    conn.emit(AgentEvent::Note(note));
844                }
845                conn.report_rate_limit(&e.to_string());
846            }
847            conn.refresh_quota_async();
848        });
849        Ok(())
850    }
851
852    /// `session/set_config_option`; response includes complete `configOptions`, also updating the cache.
853    fn set_config(&self, model: Option<&str>, effort: Option<&str>) -> Result<Option<String>> {
854        let sid = self
855            .conn
856            .acp_session
857            .lock()
858            .unwrap_or_else(|e| e.into_inner())
859            .clone();
860        let mut applied = None;
861        let mut jobs = Vec::new();
862        {
863            let opts = self.options.lock().unwrap_or_else(|e| e.into_inner());
864            if let Some(m) = model {
865                jobs.push(("model", pick_model_option(&opts, m)?));
866            }
867            if let Some(e) = effort {
868                jobs.push(("effort", pick_effort_option(&opts, e)?));
869            }
870        }
871        for (what, (config_id, value)) in jobs {
872            let r = self
873                .conn
874                .call(
875                    "session/set_config_option",
876                    json!({ "sessionId": sid, "configId": config_id, "value": value }),
877                    CALL_TIMEOUT,
878                )
879                .with_context(|| tr!("設定 {what} `{value}` 失敗", what = what, value = value))?;
880            if let Some(opts) = r.get("configOptions").filter(|co| co.is_array()) {
881                *self.options.lock().unwrap_or_else(|e| e.into_inner()) =
882                    json!({ "configOptions": opts });
883            }
884            if what == "model" {
885                applied = Some(value);
886            }
887        }
888        Ok(applied)
889    }
890
891    fn cancel(&self) -> Result<()> {
892        let sid = self
893            .conn
894            .acp_session
895            .lock()
896            .unwrap_or_else(|e| e.into_inner())
897            .clone();
898        if sid.is_empty() {
899            return Ok(());
900        }
901        self.conn.write(&json!({
902            "jsonrpc":"2.0","method":"session/cancel","params":{"sessionId":sid}
903        }))
904    }
905
906    fn pid(&self) -> Option<u32> {
907        Some(self.child.lock().unwrap_or_else(|e| e.into_inner()).id())
908    }
909
910    fn kill(&self) -> Result<()> {
911        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
912        // 終止處理程序群組或處理程序,忽略訊號發送錯誤
913        let _ = crate::signal_pgid(pid, "-KILL").or_else(|_| crate::signal_pid(pid, "-KILL"));
914        self.child
915            .lock()
916            .unwrap_or_else(|e| e.into_inner())
917            .kill()
918            .ok();
919        Ok(())
920    }
921
922    fn sleep(&self) -> Result<()> {
923        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
924        crate::signal_pgid(pid, "-STOP").or_else(|_| crate::signal_pid(pid, "-STOP"))
925    }
926
927    fn wake(&self) -> Result<()> {
928        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
929        crate::signal_pgid(pid, "-CONT").or_else(|_| crate::signal_pid(pid, "-CONT"))
930    }
931
932    fn resolve_permission(&self, req: &str, decision: Decision) -> Result<()> {
933        self.conn.resolve(req, decision)
934    }
935
936    fn resolve_question(&self, id: &str, answers: &[String]) -> Result<()> {
937        self.conn.resolve_question(id, answers)
938    }
939
940    fn transport(&self) -> &'static str {
941        "acp"
942    }
943}
944
945/// Takes the one-time collaboration prefix to prepend before the first prompt.
946fn take_effective_prompt(prepend_once: &Mutex<Option<String>>, text: &str) -> String {
947    match prepend_once
948        .lock()
949        .unwrap_or_else(|e| e.into_inner())
950        .take()
951    {
952        Some(prefix) if !prefix.trim().is_empty() => {
953            format!("{}\n\n{}", prefix.trim_end(), text)
954        }
955        _ => text.to_string(),
956    }
957}
958
959/// ACP prompt blocks: text (including inlined text files); adds image blocks if agent supports images, otherwise describes images as a text line.
960fn prompt_blocks(text: &str, atts: &[ertangle_core::Attachment], image_ok: bool) -> Value {
961    let mut blocks =
962        vec![json!({ "type": "text", "text": ertangle_core::compose_text(text, atts, !image_ok) })];
963    if image_ok {
964        for a in atts.iter().filter(|a| a.is_image()) {
965            if let Some(data) = &a.data {
966                blocks.push(json!({ "type": "image", "data": data, "mimeType": a.mime }));
967            }
968        }
969    }
970    Value::Array(blocks)
971}
972
973/// Finds model option from `session/new` response `configOptions` and validates `wanted`.
974/// Returns `(configId, value)`; returns a clear error if the agent reported no model options or the value is not in the list.
975fn pick_model_option(new: &Value, wanted: &str) -> Result<(String, String)> {
976    let opts = new["configOptions"].as_array().cloned().unwrap_or_default();
977    let opt = opts
978        .iter()
979        .find(|o| o["category"] == "model" || o["id"] == "model")
980        .ok_or_else(|| {
981            anyhow!(tr!(
982                "此 agent 沒有回報可選的 model (configOptions 無 model 項)"
983            ))
984        })?;
985    let id = opt["id"].as_str().unwrap_or("model").to_string();
986    // Options may be flat [{value,name}] or grouped [{options:[...]}]
987    let mut values: Vec<String> = Vec::new();
988    for o in opt["options"].as_array().into_iter().flatten() {
989        if let Some(v) = o["value"].as_str() {
990            values.push(v.to_string());
991        }
992        for g in o["options"].as_array().into_iter().flatten() {
993            if let Some(v) = g["value"].as_str() {
994                values.push(v.to_string());
995            }
996        }
997    }
998    if !values.is_empty() && !values.iter().any(|v| v == wanted) {
999        bail!(
1000            "{}",
1001            tr!(
1002                "未知的 model `{wanted}`;可用:{list}",
1003                wanted = wanted,
1004                list = values.join(", ")
1005            )
1006        );
1007    }
1008    Ok((id, wanted.to_string()))
1009}
1010
1011/// Finds reasoning effort option from `session/new` `configOptions` (id or category containing effort/reasoning/thought).
1012fn pick_effort_option(new: &Value, wanted: &str) -> Result<(String, String)> {
1013    let opts = new["configOptions"].as_array().cloned().unwrap_or_default();
1014    let is_effort = |s: &str| {
1015        let s = s.to_ascii_lowercase();
1016        s.contains("effort") || s.contains("reasoning") || s.contains("thought")
1017    };
1018    let opt = opts
1019        .iter()
1020        .find(|o| {
1021            is_effort(o["id"].as_str().unwrap_or(""))
1022                || is_effort(o["category"].as_str().unwrap_or(""))
1023        })
1024        .ok_or_else(|| {
1025            anyhow!(tr!(
1026                "此 agent 沒有回報可設定的 effort (configOptions 無相關項)"
1027            ))
1028        })?;
1029    let id = opt["id"].as_str().unwrap_or("effort").to_string();
1030    let values: Vec<String> = opt["options"]
1031        .as_array()
1032        .into_iter()
1033        .flatten()
1034        .filter_map(|o| o["value"].as_str().map(str::to_string))
1035        .collect();
1036    if !values.is_empty() && !values.iter().any(|v| v == wanted) {
1037        bail!(
1038            "{}",
1039            tr!(
1040                "effort `{wanted}` 不在可用清單:{list}",
1041                wanted = wanted,
1042                list = values.join(", ")
1043            )
1044        );
1045    }
1046    Ok((id, wanted.to_string()))
1047}
1048
1049pub fn start(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
1050    let (default_prog, args) = spec
1051        .kind
1052        .acp_command()
1053        .with_context(|| tr!("此 agent 不支援原生結構化協定"))?;
1054    let prog = match spec.bin.as_deref() {
1055        Some(b) => crate::which(b).with_context(|| tr!("找不到指定的執行檔 `{b}`", b = b))?,
1056        None => crate::which(default_prog)
1057            .with_context(|| tr!("找不到 `{prog}`", prog = default_prog))?,
1058    };
1059
1060    let mut cmd = Command::new(&prog);
1061    cmd.args(args)
1062        .args(&spec.args)
1063        .current_dir(&spec.cwd)
1064        .stdin(Stdio::piped())
1065        .stdout(Stdio::piped())
1066        .stderr(Stdio::piped());
1067    for k in crate::env_removals(&spec.kind) {
1068        cmd.env_remove(k);
1069    }
1070    for (k, v) in &spec.env {
1071        cmd.env(k, v);
1072    }
1073    #[cfg(unix)]
1074    {
1075        use std::os::unix::process::CommandExt;
1076        cmd.process_group(0);
1077    }
1078    let mut child = cmd
1079        .spawn()
1080        .with_context(|| tr!("無法啟動 `{prog} acp`", prog = prog.display()))?;
1081
1082    let stdin = child.stdin.take().with_context(|| tr!("取得 stdin 失敗"))?;
1083    let stderr_tail = child.stderr.take().map(crate::stderr::StderrTail::spawn);
1084    let stdout = child
1085        .stdout
1086        .take()
1087        .with_context(|| tr!("取得 stdout 失敗"))?;
1088
1089    let quota_prog = if spec.kind == ertangle_core::AgentKind::Antigravity {
1090        Some((prog.clone(), spec.env.clone()))
1091    } else {
1092        None
1093    };
1094
1095    let (stream_poke, stream_rx) = mpsc::channel();
1096    let conn = Arc::new(Conn {
1097        agent: spec.kind.id().to_string(),
1098        limited: std::sync::atomic::AtomicBool::new(false),
1099        quota_prog,
1100        quota_refreshing: std::sync::atomic::AtomicBool::new(false),
1101        session_id: spec.id.clone(),
1102        acp_session: Mutex::new(String::new()),
1103        stdin: Mutex::new(stdin),
1104        next_id: AtomicI64::new(1),
1105        pending: Mutex::new(HashMap::new()),
1106        perms: Mutex::new(HashMap::new()),
1107        questions: Mutex::new(HashMap::new()),
1108        stream: Mutex::new(StreamBuf::default()),
1109        stream_poke,
1110        prepend_once: Mutex::new(spec.system_append.clone().filter(|s| !s.trim().is_empty())),
1111        image_ok: std::sync::atomic::AtomicBool::new(false),
1112        loading: std::sync::atomic::AtomicBool::new(false),
1113        last_update: Mutex::new(std::time::Instant::now()),
1114        turns: Mutex::new(TurnTracker::default()),
1115        tx: tx.clone(),
1116    });
1117
1118    {
1119        let weak = Arc::downgrade(&conn);
1120        std::thread::spawn(move || {
1121            // Exits once the connection is dropped (session ended).
1122            loop {
1123                std::thread::sleep(STALL_POLL);
1124                let Some(c) = weak.upgrade() else { return };
1125                c.check_stall(Instant::now());
1126            }
1127        });
1128    }
1129
1130    {
1131        let weak = Arc::downgrade(&conn);
1132        std::thread::spawn(move || {
1133            // Flush trailing partial lines after 250ms of stream silence so internal
1134            // background-task turns without `conn.prompt()` don't leak into the next prompt.
1135            while stream_rx.recv().is_ok() {
1136                loop {
1137                    match stream_rx.recv_timeout(Duration::from_millis(250)) {
1138                        Ok(()) => continue,
1139                        Err(mpsc::RecvTimeoutError::Timeout) => {
1140                            if let Some(c) = weak.upgrade() {
1141                                c.idle_flush_stream();
1142                            }
1143                            break;
1144                        }
1145                        Err(mpsc::RecvTimeoutError::Disconnected) => return,
1146                    }
1147                }
1148            }
1149        });
1150    }
1151
1152    {
1153        let conn = conn.clone();
1154        std::thread::spawn(move || reader_loop(conn, BufReader::new(stdout)));
1155    }
1156
1157    let child = Arc::new(Mutex::new(child));
1158    {
1159        let child = child.clone();
1160        let tx = tx.clone();
1161        std::thread::spawn(move || {
1162            // Poll with try_wait (rather than blocking wait) to avoid holding the lock indefinitely, which would deadlock `kill()`.
1163            let code = loop {
1164                let status = {
1165                    let mut c = child.lock().unwrap_or_else(|e| e.into_inner());
1166                    c.try_wait()
1167                };
1168                match status {
1169                    Ok(Some(s)) => break s.code(),
1170                    Ok(None) => std::thread::sleep(Duration::from_millis(100)),
1171                    Err(_) => break None,
1172                }
1173            };
1174            if let Some(t) = &stderr_tail {
1175                t.report_exit(code, &tx);
1176            }
1177            // 接收端若已關閉則忽略退出事件
1178            let _ = tx.send(AgentEvent::Exited(code));
1179        });
1180    }
1181
1182    // Handshake.
1183    let init = conn.call(
1184        "initialize",
1185        json!({
1186            "protocolVersion": 1,
1187            "clientCapabilities": {
1188                "fs": { "readTextFile": false, "writeTextFile": false },
1189                "elicitation": { "form": {} }
1190            }
1191        }),
1192        CALL_TIMEOUT,
1193    )?;
1194    tracing::debug!("ACP initialize: {init}");
1195    conn.image_ok.store(
1196        init.get("agentCapabilities")
1197            .and_then(|ac| ac.get("promptCapabilities"))
1198            .and_then(|pc| pc.get("image"))
1199            .and_then(|v| v.as_bool())
1200            .unwrap_or(false),
1201        Ordering::SeqCst,
1202    );
1203
1204    let mcp_servers = match &spec.mcp_exe {
1205        Some(exe) => {
1206            let mut args = vec!["mcp".to_string(), "--session".to_string(), spec.id.clone()];
1207            if let Some((_, sock)) = spec.env.iter().find(|(k, _)| k == "ERTANGLE_SOCKET") {
1208                args.push("--socket".to_string());
1209                args.push(sock.clone());
1210            }
1211            json!([{
1212                "name": "ertangle",
1213                "command": exe.to_string_lossy(),
1214                "args": args,
1215                "env": []
1216            }])
1217        }
1218        None => json!([]),
1219    };
1220    // Only agents declaring `loadSession` can be reconnected later.
1221    let can_load = init
1222        .get("agentCapabilities")
1223        .and_then(|ac| ac.get("loadSession"))
1224        .and_then(|v| v.as_bool())
1225        .unwrap_or(false);
1226    let (sid, new) = match &spec.resume {
1227        Some(id) => {
1228            if !can_load {
1229                bail!(
1230                    "{}",
1231                    tr!(
1232                        "{kind} 沒有宣告 loadSession,無法接續對話",
1233                        kind = spec.kind
1234                    )
1235                );
1236            }
1237            conn.loading.store(true, Ordering::SeqCst);
1238            let loaded = conn.call(
1239                "session/load",
1240                json!({ "sessionId": id, "cwd": spec.cwd.to_string_lossy(), "mcpServers": mcp_servers }),
1241                LOAD_TIMEOUT,
1242            );
1243            // Some ACP agents (e.g. agy) stream `session/load` replay updates after returning the response.
1244            // Keep discarding until the replay goes quiet; otherwise it lands after the initial prompt
1245            // and buries the user's message under the old conversation.
1246            *conn.last_update.lock().unwrap_or_else(|e| e.into_inner()) = std::time::Instant::now();
1247            wait_until_quiet(
1248                || *conn.last_update.lock().unwrap_or_else(|e| e.into_inner()),
1249                REPLAY_QUIET,
1250                REPLAY_MAX_WAIT,
1251            );
1252            conn.loading.store(false, Ordering::SeqCst);
1253            // 等待重播結束後刷新緩衝區,若無資料則忽略
1254            let _ = conn
1255                .stream
1256                .lock()
1257                .unwrap_or_else(|e| e.into_inner())
1258                .flush();
1259            (id.clone(), loaded?)
1260        }
1261        None => {
1262            let new = conn.call(
1263                "session/new",
1264                json!({ "cwd": spec.cwd.to_string_lossy(), "mcpServers": mcp_servers }),
1265                CALL_TIMEOUT,
1266            )?;
1267            let sid = new
1268                .get("sessionId")
1269                .and_then(|v| v.as_str())
1270                .with_context(|| tr!("`session/new` 未回傳 sessionId"))?
1271                .to_string();
1272            (sid, new)
1273        }
1274    };
1275    *conn.acp_session.lock().unwrap_or_else(|e| e.into_inner()) = sid.clone();
1276    if can_load {
1277        // 接收端若已關閉則忽略事件傳送
1278        let _ = tx.send(AgentEvent::NativeId(sid.clone()));
1279    }
1280    // When resuming, model/effort already exist in agent conversation; do not reset if response lacks configOptions.
1281    let has_options =
1282        spec.resume.is_none() || new.get("configOptions").is_some_and(|co| co.is_array());
1283    if let Some(wanted) = spec.model.as_ref().filter(|_| has_options) {
1284        let (config_id, value) = pick_model_option(&new, wanted)?;
1285        conn.call(
1286            "session/set_config_option",
1287            json!({ "sessionId": sid, "configId": config_id, "value": value }),
1288            CALL_TIMEOUT,
1289        )
1290        .with_context(|| tr!("設定 model `{value}` 失敗", value = value))?;
1291        // 接收端若已關閉則忽略事件傳送
1292        let _ = tx.send(AgentEvent::Model(value));
1293    }
1294    if let Some(e) = spec.effort.as_ref().filter(|_| has_options) {
1295        let (config_id, value) = pick_effort_option(&new, e)?;
1296        conn.call(
1297            "session/set_config_option",
1298            json!({ "sessionId": sid, "configId": config_id, "value": value }),
1299            CALL_TIMEOUT,
1300        )
1301        .with_context(|| tr!("設定 effort `{value}` 失敗", value = value))?;
1302    }
1303    let has_initial_prompt = spec
1304        .initial_prompt
1305        .as_deref()
1306        .is_some_and(|p| !p.trim().is_empty());
1307    // 接收端若已關閉則忽略事件傳送
1308    let _ = tx.send(AgentEvent::Status(if has_initial_prompt {
1309        SessionStatus::Busy
1310    } else {
1311        SessionStatus::Idle
1312    }));
1313    conn.refresh_quota_async();
1314
1315    let control = AcpControl {
1316        conn,
1317        child,
1318        options: Mutex::new(
1319            json!({ "configOptions": new.get("configOptions").cloned().unwrap_or(Value::Null) }),
1320        ),
1321    };
1322
1323    if let Some(p) = &spec.initial_prompt {
1324        control.send_input_with(p, &spec.initial_attachments)?;
1325    }
1326
1327    Ok(Box::new(control))
1328}
1329
1330/// Blocks until `last_activity()` is at least `quiet` old, or `max` has elapsed in total.
1331fn wait_until_quiet(
1332    last_activity: impl Fn() -> std::time::Instant,
1333    quiet: Duration,
1334    max: Duration,
1335) {
1336    let start = std::time::Instant::now();
1337    loop {
1338        let idle = last_activity().elapsed();
1339        let waited = start.elapsed();
1340        if idle >= quiet || waited >= max {
1341            return;
1342        }
1343        std::thread::sleep((quiet - idle).min(max - waited));
1344    }
1345}
1346
1347#[cfg(test)]
1348mod turn_tracker_tests {
1349    use super::*;
1350
1351    const T: Duration = Duration::from_secs(180);
1352
1353    #[test]
1354    fn idle_only_after_last_concurrent_turn_ends() {
1355        let mut t = TurnTracker::default();
1356        let now = Instant::now();
1357        t.begin(now);
1358        t.begin(now);
1359        assert_eq!(
1360            t.end(),
1361            None,
1362            "second turn finishing early must not report Idle"
1363        );
1364        assert_eq!(t.end(), Some(false));
1365    }
1366
1367    #[test]
1368    fn end_without_begin_does_not_underflow() {
1369        let mut t = TurnTracker::default();
1370        assert_eq!(t.end(), Some(false));
1371    }
1372
1373    #[test]
1374    fn no_stall_when_no_turn_running() {
1375        let mut t = TurnTracker::default();
1376        let now = Instant::now();
1377        assert_eq!(t.stalled(now + T * 2, now, T), None);
1378    }
1379
1380    #[test]
1381    fn warns_once_per_quiet_period_and_rearms_after_activity() {
1382        let mut t = TurnTracker::default();
1383        let start = Instant::now();
1384        t.begin(start);
1385        assert_eq!(t.stalled(start + T / 2, start, T), None);
1386        assert_eq!(t.stalled(start + T, start, T), Some(T));
1387        assert_eq!(t.stalled(start + T * 2, start, T), None, "already warned");
1388        let activity = start + T * 3;
1389        assert_eq!(t.stalled(activity + T, activity, T), Some(T));
1390        assert_eq!(t.end(), Some(true), "warning must be cleared on Idle");
1391    }
1392
1393    #[test]
1394    fn quiet_period_counts_from_turn_start_not_stale_update() {
1395        let mut t = TurnTracker::default();
1396        let old_update = Instant::now();
1397        let start = old_update + T * 5;
1398        t.begin(start);
1399        assert_eq!(t.stalled(start + T / 2, old_update, T), None);
1400    }
1401}
1402
1403#[cfg(test)]
1404mod replay_wait_tests {
1405    use super::*;
1406    use std::time::Instant;
1407
1408    #[test]
1409    fn returns_once_activity_goes_quiet() {
1410        let start = Instant::now();
1411        // Activity keeps arriving for the first 150ms, then stops.
1412        let last = || {
1413            let now = Instant::now();
1414            if now.duration_since(start) < Duration::from_millis(150) {
1415                now
1416            } else {
1417                start + Duration::from_millis(150)
1418            }
1419        };
1420        wait_until_quiet(last, Duration::from_millis(100), Duration::from_secs(5));
1421        let took = start.elapsed();
1422        assert!(
1423            took >= Duration::from_millis(250),
1424            "returned too early: {took:?}"
1425        );
1426        assert!(took < Duration::from_secs(2), "waited too long: {took:?}");
1427    }
1428
1429    #[test]
1430    fn gives_up_after_max_wait_when_activity_never_stops() {
1431        let start = Instant::now();
1432        wait_until_quiet(
1433            Instant::now,
1434            Duration::from_millis(100),
1435            Duration::from_millis(200),
1436        );
1437        let took = start.elapsed();
1438        assert!(
1439            took >= Duration::from_millis(200),
1440            "returned too early: {took:?}"
1441        );
1442        assert!(took < Duration::from_secs(2), "waited too long: {took:?}");
1443    }
1444
1445    #[test]
1446    fn returns_immediately_when_already_quiet() {
1447        let past = Instant::now() - Duration::from_secs(1);
1448        let start = Instant::now();
1449        wait_until_quiet(|| past, Duration::from_millis(100), Duration::from_secs(5));
1450        assert!(start.elapsed() < Duration::from_millis(50));
1451    }
1452}
1453
1454#[cfg(test)]
1455mod model_tests {
1456    use super::*;
1457
1458    #[test]
1459    fn elicitation_content_uses_scalar_for_single_select() {
1460        let entries = vec![
1461            ("strategy".to_string(), false, vec!["balanced".to_string()]),
1462            (
1463                "tags".to_string(),
1464                true,
1465                vec!["api".to_string(), "ui".to_string()],
1466            ),
1467        ];
1468        assert_eq!(
1469            elicitation_accept_content(&entries),
1470            json!({ "strategy": "balanced", "tags": ["api", "ui"] })
1471        );
1472        assert_eq!(
1473            elicitation_accept_content(&[("custom".to_string(), false, Vec::new())]),
1474            json!({ "custom": [] })
1475        );
1476    }
1477
1478    #[test]
1479    fn elicitation_response_keeps_selection_when_other_field_is_skipped() {
1480        let entries = vec![
1481            ("A1".to_string(), false, vec!["Postgres".to_string()]),
1482            ("A2".to_string(), false, Vec::new()),
1483        ];
1484        assert_eq!(
1485            elicitation_response(&entries),
1486            json!({ "action": "accept", "content": { "A1": "Postgres" } })
1487        );
1488        assert_eq!(
1489            elicitation_response(&[("A2".to_string(), false, Vec::new())]),
1490            json!({ "action": "decline" })
1491        );
1492    }
1493
1494    #[test]
1495    fn extracts_request_id_with_safe_fallback() {
1496        assert_eq!(extract_request_id(&json!({"id": 123})), json!(123));
1497        assert_eq!(extract_request_id(&json!({"id": "req-1"})), json!("req-1"));
1498        assert_eq!(extract_request_id(&json!({"id": null})), Value::Null);
1499        assert_eq!(
1500            extract_request_id(&json!({"method": "session/update"})),
1501            Value::Null
1502        );
1503        assert_eq!(extract_request_id(&json!(42)), Value::Null);
1504        assert_eq!(extract_request_id(&json!([])), Value::Null);
1505    }
1506
1507    #[test]
1508    fn picks_model_option_and_validates() {
1509        let new = json!({"sessionId":"x","configOptions":[
1510            {"id":"mode","category":"mode","options":[{"value":"a"}]},
1511            {"id":"model","category":"model","type":"select","options":[
1512                {"value":"p/m1","name":"M1"},{"value":"p/m2","name":"M2"}]}]});
1513        assert_eq!(pick_model_option(&new, "p/m2").unwrap().1, "p/m2");
1514        let e = pick_model_option(&new, "zzz").unwrap_err().to_string();
1515        assert!(e.contains("p/m1") && e.contains("zzz"));
1516        assert!(pick_model_option(&json!({"sessionId":"x"}), "a").is_err());
1517    }
1518
1519    #[test]
1520    fn prepend_once_applies_only_to_first_prompt() {
1521        let p = Mutex::new(Some("[ertangle 協作說明]\n規則\n".to_string()));
1522        let first = take_effective_prompt(&p, "做任務 A");
1523        assert!(first.starts_with("[ertangle 協作說明]\n規則\n\n做任務 A"));
1524        let second = take_effective_prompt(&p, "做任務 B");
1525        assert_eq!(second, "做任務 B");
1526    }
1527
1528    #[test]
1529    fn tool_updates_only_report_final_states() {
1530        assert_eq!(tool_update_ok(&json!({"status":"pending"})), None);
1531        assert_eq!(tool_update_ok(&json!({"status":"in_progress"})), None);
1532        assert_eq!(tool_update_ok(&json!({})), None);
1533        assert_eq!(tool_update_ok(&json!({"status":"completed"})), Some(true));
1534        assert_eq!(tool_update_ok(&json!({"status":"failed"})), Some(false));
1535    }
1536
1537    #[test]
1538    fn tool_result_text_unwraps_acp_content() {
1539        let u = json!({"content":[{"type":"content","content":{"type":"text","text":"a\nb"}}]});
1540        assert_eq!(tool_result_text(&u).as_deref(), Some("a\nb"));
1541
1542        let u = json!({"content":[
1543            {"type":"content","content":{"type":"text","text":"x"}},
1544            {"type":"content","content":{"type":"text","text":"y"}}]});
1545        assert_eq!(tool_result_text(&u).as_deref(), Some("x\ny"));
1546
1547        assert_eq!(tool_result_text(&json!({})), None);
1548        // Diff content has no plain text: do not print raw JSON.
1549        assert_eq!(
1550            tool_result_text(&json!({"content":[{"type":"diff","path":"a.rs"}]})),
1551            None
1552        );
1553        // Fall back to rawOutput when content is absent.
1554        assert_eq!(
1555            tool_result_text(&json!({"rawOutput":{"exit":0}})).as_deref(),
1556            Some("{\"exit\":0}")
1557        );
1558    }
1559
1560    #[test]
1561    fn long_tool_output_is_truncated() {
1562        let s = "x".repeat(10);
1563        assert_eq!(truncate_chars(&s, 4), "xxxx…");
1564        assert_eq!(truncate_chars("abc", 4), "abc");
1565    }
1566}
1567
1568const QUOTA_QUERY_TIMEOUT: Duration = Duration::from_secs(15);
1569
1570/// Executes `agy --output-format json -p /quota` to obtain raw JSON; returns `None` on failure or timeout.
1571fn query_agy_quota(prog: &std::path::Path, env: &[(String, String)]) -> Option<String> {
1572    let mut cmd = Command::new(prog);
1573    cmd.args(["--output-format", "json", "-p", "/quota"])
1574        .stdin(Stdio::null())
1575        .stdout(Stdio::piped())
1576        .stderr(Stdio::null());
1577    for k in crate::env_removals(&ertangle_core::AgentKind::Antigravity) {
1578        cmd.env_remove(k);
1579    }
1580    for (k, v) in env {
1581        cmd.env(k, v);
1582    }
1583    let mut child = cmd.spawn().ok()?;
1584    let deadline = std::time::Instant::now() + QUOTA_QUERY_TIMEOUT;
1585    let status = loop {
1586        match child.try_wait() {
1587            Ok(Some(s)) => break s,
1588            Ok(None) if std::time::Instant::now() < deadline => {
1589                std::thread::sleep(Duration::from_millis(50));
1590            }
1591            _ => {
1592                // 查詢額度逾時強制終止子處理程序並回收,忽略錯誤
1593                let _ = child.kill();
1594                let _ = child.wait();
1595                return None;
1596            }
1597        }
1598    };
1599    if !status.success() {
1600        return None;
1601    }
1602    let mut out = String::new();
1603    if let Some(mut so) = child.stdout.take() {
1604        use std::io::Read;
1605        so.read_to_string(&mut out).ok()?;
1606    }
1607    Some(out)
1608}
1609
1610/// Parses output of `agy --output-format json -p /quota` into `Quota`.
1611pub(crate) fn parse_agy_quota_json(raw: &str, reached: bool) -> Option<ertangle_core::Quota> {
1612    let v: Value = serde_json::from_str(raw.trim()).ok()?;
1613    let groups = v
1614        .get("command")
1615        .and_then(|c| c.get("data"))
1616        .and_then(|d| d.get("groups"))
1617        .and_then(|g| g.as_array())?;
1618    let mut windows = Vec::new();
1619    for g in groups {
1620        let group_name = g["name"].as_str().unwrap_or("");
1621        let Some(buckets) = g["buckets"].as_array() else {
1622            continue;
1623        };
1624        for b in buckets {
1625            let Some(remaining) = b["remaining_fraction"].as_f64() else {
1626                continue;
1627            };
1628            let id = b["id"].as_str().unwrap_or("");
1629            let win_raw = b["window"].as_str().unwrap_or("");
1630            let name = agy_window_name(group_name, id, win_raw);
1631            let used_percent = ((1.0 - remaining) * 100.0).clamp(0.0, 100.0) as f32;
1632            let resets_at_ms = b["reset_time"].as_str().and_then(parse_rfc3339_utc_ms);
1633            windows.push(ertangle_core::QuotaWindow {
1634                name,
1635                used_percent,
1636                resets_at_ms,
1637            });
1638        }
1639    }
1640    if windows.is_empty() {
1641        return None;
1642    }
1643    windows.sort_by_key(|w| {
1644        let rank = match w.name.as_str() {
1645            "5h" => 0,
1646            "7d" => 1,
1647            n if n.starts_with("argon") => 2,
1648            "3p-5h" => 3,
1649            "3p-7d" => 4,
1650            _ => 5,
1651        };
1652        (rank, w.name.clone())
1653    });
1654    let primary_exhausted = windows
1655        .iter()
1656        .any(|w| matches!(w.name.as_str(), "5h" | "7d") && w.used_percent >= 100.0);
1657    Some(ertangle_core::Quota {
1658        agent: "antigravity".into(),
1659        windows,
1660        reached: reached || primary_exhausted,
1661        warning: false,
1662        updated_ms: ertangle_core::now_millis(),
1663    })
1664}
1665
1666fn agy_window_name(group_name: &str, id: &str, window: &str) -> String {
1667    if id == "gemini-5h" || (group_name == "Gemini Models" && window == "5h") {
1668        return "5h".into();
1669    }
1670    if id == "gemini-weekly" || (group_name == "Gemini Models" && window == "weekly") {
1671        return "7d".into();
1672    }
1673    if id.contains("argon") || group_name.contains("Argon") {
1674        return match window {
1675            "5h" => "argon-5h".into(),
1676            "weekly" => "argon-7d".into(),
1677            other if !other.is_empty() => format!("argon-{other}"),
1678            _ => "argon".into(),
1679        };
1680    }
1681    if id.starts_with("3p-") || group_name.contains("Claude") {
1682        return match window {
1683            "5h" => "3p-5h".into(),
1684            "weekly" => "3p-7d".into(),
1685            _ => id.into(),
1686        };
1687    }
1688    match window {
1689        "weekly" => "7d".into(),
1690        other if !other.is_empty() => other.into(),
1691        _ => id.into(),
1692    }
1693}
1694
1695/// Parses UTC RFC 3339 timestamp string (`YYYY-MM-DDTHH:MM:SSZ` or with fractional seconds) to epoch milliseconds.
1696pub(crate) fn parse_rfc3339_utc_ms(s: &str) -> Option<u64> {
1697    let s = s.strip_suffix('Z')?;
1698    let (date, time) = s.split_once('T')?;
1699    let mut dp = date.split('-');
1700    let y: i64 = dp.next()?.parse().ok()?;
1701    let m: i64 = dp.next()?.parse().ok()?;
1702    let d: i64 = dp.next()?.parse().ok()?;
1703    if dp.next().is_some() || !(1..=12).contains(&m) || !(1..=31).contains(&d) {
1704        return None;
1705    }
1706    let hms = time.split('.').next()?;
1707    let mut tp = hms.split(':');
1708    let hh: i64 = tp.next()?.parse().ok()?;
1709    let mm: i64 = tp.next()?.parse().ok()?;
1710    let ss: i64 = tp.next()?.parse().ok()?;
1711    if tp.next().is_some()
1712        || !(0..=23).contains(&hh)
1713        || !(0..=59).contains(&mm)
1714        || !(0..=60).contains(&ss)
1715    {
1716        return None;
1717    }
1718    // Howard Hinnant's civil-from-days inverse: convert to days since Unix epoch.
1719    let y_adj = y - if m <= 2 { 1 } else { 0 };
1720    let era = y_adj.div_euclid(400);
1721    let yoe = y_adj.rem_euclid(400);
1722    let doy = (153 * (m + if m > 2 { -3 } else { 9 }) + 2) / 5 + d - 1;
1723    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
1724    let days = era * 146097 + doe - 719468;
1725    let secs = days
1726        .checked_mul(86_400)?
1727        .checked_add(hh.checked_mul(3_600)?)?
1728        .checked_add(mm.checked_mul(60)?)?
1729        .checked_add(ss)?;
1730    u64::try_from(secs).ok()?.checked_mul(1_000)
1731}
1732
1733#[cfg(test)]
1734mod rate_limit_tests {
1735    use super::*;
1736
1737    #[test]
1738    fn detects_rate_limit_errors() {
1739        let samples = [
1740            r#"`session/prompt` 失敗:{"code":-32000,"message":"RESOURCE_EXHAUSTED: Quota exceeded for metric"}"#,
1741            r#"{"code":429,"message":"Too Many Requests"}"#,
1742            r#"{"message":"You have hit the rate limit"}"#,
1743            r#"{"sessionUpdate":"error","error":{"message":"HTTP 429"}}"#,
1744        ];
1745        for s in samples {
1746            let q = rate_limit_quota("antigravity", s).expect(s);
1747            assert!(q.reached);
1748            assert_eq!(q.agent, "antigravity");
1749            assert!(q.windows.is_empty());
1750        }
1751    }
1752
1753    #[test]
1754    fn recovery_clears_limit_once() {
1755        let flag = std::sync::atomic::AtomicBool::new(false);
1756        assert!(recovered_quota("antigravity", &flag).is_none());
1757        flag.store(true, Ordering::SeqCst);
1758        let q = recovered_quota("antigravity", &flag).expect("reset");
1759        assert!(!q.reached && !q.warning && q.windows.is_empty());
1760        assert_eq!(q.agent, "antigravity");
1761        assert!(recovered_quota("antigravity", &flag).is_none());
1762    }
1763
1764    #[test]
1765    fn ignores_other_errors() {
1766        for s in [
1767            r#"{"code":-32603,"message":"internal error"}"#,
1768            r#"{"message":"tokens used: 14290"}"#,
1769            r#"{"message":"invalid params"}"#,
1770        ] {
1771            assert!(rate_limit_quota("antigravity", s).is_none(), "{s}");
1772        }
1773    }
1774
1775    #[test]
1776    fn parses_rfc3339_utc_ms() {
1777        assert_eq!(parse_rfc3339_utc_ms("1970-01-01T00:00:00Z"), Some(0));
1778        assert_eq!(
1779            parse_rfc3339_utc_ms("2026-11-19T15:43:56Z"),
1780            Some(1_795_103_036_000)
1781        );
1782        assert_eq!(
1783            parse_rfc3339_utc_ms("2026-11-19T15:43:56.123Z"),
1784            Some(1_795_103_036_000)
1785        );
1786        assert!(parse_rfc3339_utc_ms("2026-11-19T15:43:56+08:00").is_none());
1787    }
1788
1789    #[test]
1790    fn parses_agy_quota_json_sample() {
1791        let sample = r#"{
1792            "conversation_id": "",
1793            "status": "SUCCESS",
1794            "command": {
1795                "name": "usage",
1796                "data": {
1797                    "groups": [
1798                        {
1799                            "name": "Gemini Models",
1800                            "buckets": [
1801                                {"id": "gemini-weekly", "window": "weekly", "remaining_fraction": 0.39, "reset_time": "2026-11-25T13:49:39Z"},
1802                                {"id": "gemini-5h", "window": "5h", "remaining_fraction": 0.93, "reset_time": "2026-11-19T15:43:56Z"}
1803                            ]
1804                        },
1805                        {
1806                            "name": "Claude and GPT models",
1807                            "buckets": [
1808                                {"id": "3p-weekly", "window": "weekly", "remaining_fraction": 0.10, "reset_time": "2026-11-26T10:58:54Z"},
1809                                {"id": "3p-5h", "window": "5h", "remaining_fraction": 1, "reset_time": "2026-11-19T15:58:54Z"}
1810                            ]
1811                        },
1812                        {
1813                            "name": "Gemini 4 Argon",
1814                            "buckets": [
1815                                {"id": "gemini-argon-wtu-weekly", "window": "weekly", "remaining_fraction": 0.78, "reset_time": "2026-11-25T13:41:45Z"}
1816                            ]
1817                        }
1818                    ]
1819                }
1820            }
1821        }"#;
1822        let q = parse_agy_quota_json(sample, false).expect("valid agy quota");
1823        assert_eq!(q.agent, "antigravity");
1824        assert!(!q.reached);
1825        assert_eq!(q.windows.len(), 5);
1826        assert_eq!(q.windows[0].name, "5h");
1827        assert!((q.windows[0].used_percent - 7.0).abs() < 0.01);
1828        assert_eq!(q.windows[1].name, "7d");
1829        assert!((q.windows[1].used_percent - 61.0).abs() < 0.01);
1830        assert_eq!(q.windows[2].name, "argon-7d");
1831        assert_eq!(q.windows[3].name, "3p-5h");
1832        assert_eq!(q.windows[4].name, "3p-7d");
1833        assert_eq!(q.windows[0].resets_at_ms, Some(1_795_103_036_000));
1834        assert_eq!(q.max_used(), 61.0);
1835        assert_eq!(q.max_used_live(0), 61.0);
1836        assert!(!q.reached);
1837    }
1838
1839    #[test]
1840    fn marks_reached_when_primary_window_exhausted() {
1841        let sample = r#"{"command":{"name":"usage","data":{"groups":[{"name":"Gemini Models","buckets":[{"id":"gemini-5h","window":"5h","remaining_fraction":0.0}]}]}}}"#;
1842        let q = parse_agy_quota_json(sample, false).expect("exhausted");
1843        assert!(q.reached);
1844        assert!((q.windows[0].used_percent - 100.0).abs() < 0.01);
1845        assert!(parse_agy_quota_json("not json", false).is_none());
1846    }
1847}