Skip to main content

ertangle_adapter/
claude.rs

1//! Native adapter for Claude Code (`--input-format stream-json --output-format stream-json`).
2//!
3//! This is bidirectional NDJSON: we write user messages to stdin, and Claude emits events on stdout.
4//! Since Claude Code does not provide native ACP, this is its only structured interface with zero extra dependencies.
5//!
6//! Observed wire shape (claude 2.1.x):
7//!
8//! ```text
9//! → {"type":"user","message":{"role":"user","content":[{"type":"text","text":"..."}]}}
10//! ← {"type":"system","subtype":"init","session_id":...,"model":...,"tools":[...]}
11//! ← {"type":"stream_event","event":{"type":"content_block_delta","delta":{"type":"text_delta","text":"..."}}}
12//! ← {"type":"assistant","message":{"content":[{"type":"text","text":...},{"type":"tool_use","name":...,"input":...}]}}
13//! ← {"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":...,"content":...,"is_error":false}]}}
14//! ← {"type":"result","subtype":"success","total_cost_usd":...,"usage":{...},"is_error":false}
15//! ```
16
17use crate::stream::StreamBuf;
18use crate::{AgentControl, AgentEvent, SessionSpec};
19use anyhow::{bail, Context, Result};
20use ertangle_core::{Cost, Decision, SessionStatus};
21use serde_json::{json, Value};
22use std::io::{BufRead, BufReader, Write};
23use std::process::{Child, ChildStdin, Command, Stdio};
24use std::sync::atomic::{AtomicBool, Ordering};
25use std::sync::mpsc::Sender;
26use std::sync::{Arc, Mutex};
27use std::time::Duration;
28use tr::tr;
29
30/// Reads the running Claude event stream.
31struct Conn {
32    stdin: Mutex<ChildStdin>,
33    stream: Mutex<StreamBuf>,
34    /// Whether this message has already streamed via deltas (avoids duplicate output with the full assistant message).
35    saw_delta: AtomicBool,
36    /// Set by `cancel()`: the next `error_during_execution` result is the user's interrupt, not a failure.
37    interrupted: AtomicBool,
38    tx: Sender<AgentEvent>,
39}
40
41impl Conn {
42    fn emit(&self, ev: AgentEvent) {
43        // Write failure means the receiver channel is closed; nothing to do.
44        let _ = self.tx.send(ev);
45    }
46
47    fn send_raw(&self, v: &Value) -> Result<()> {
48        let mut line = serde_json::to_string(v)?;
49        line.push('\n');
50        let mut w = self.stdin.lock().unwrap_or_else(|e| e.into_inner());
51        w.write_all(line.as_bytes())?;
52        w.flush()?;
53        Ok(())
54    }
55
56    fn flush_stream(&self) {
57        let text = self
58            .stream
59            .lock()
60            .unwrap_or_else(|e| e.into_inner())
61            .flush();
62        if !text.is_empty() {
63            self.emit(AgentEvent::Output(text));
64        }
65    }
66
67    /// Processes a single stdout line.
68    fn on_line(&self, line: &str) {
69        let Ok(msg) = serde_json::from_str::<Value>(line) else {
70            return;
71        };
72        match msg.get("type").and_then(|v| v.as_str()).unwrap_or("") {
73            "system" => self.on_system(&msg),
74            "stream_event" => self.on_stream_event(&msg),
75            "assistant" => self.on_assistant(&msg),
76            "user" => self.on_tool_results(&msg),
77            "result" => self.on_result(&msg),
78            "rate_limit_event" => {
79                if let Some(q) = parse_rate_limit_event(&msg) {
80                    self.emit(AgentEvent::Quota(q));
81                }
82            }
83            // hook_started / hook_response / rate_limit_event / system.status…
84            _ => {}
85        }
86    }
87
88    fn on_system(&self, msg: &Value) {
89        if msg["subtype"].as_str() == Some("init") {
90            if let Some(model) = msg["model"].as_str() {
91                self.emit(AgentEvent::Model(model.to_string()));
92            }
93            if let Some(cmds) = msg["slash_commands"].as_array() {
94                let names: Vec<String> = cmds
95                    .iter()
96                    .filter_map(|c| c.as_str().map(str::to_string))
97                    .collect();
98                if !names.is_empty() {
99                    self.emit(AgentEvent::Commands(names));
100                }
101            }
102            // Send every time: after resuming the ID may change; the latest takes precedence.
103            if let Some(id) = msg["session_id"].as_str().filter(|s| !s.is_empty()) {
104                self.emit(AgentEvent::NativeId(id.to_string()));
105            }
106            // Status is set to Idle by the daemon upon startup completion and restored to Idle by `result` at turn end;
107            // do not emit Idle here, otherwise the UI would appear idle while the initial prompt is still being processed.
108        }
109    }
110
111    /// Word-by-word streaming (requires `--include-partial-messages`).
112    fn on_stream_event(&self, msg: &Value) {
113        let ev = &msg["event"];
114        match ev["type"].as_str().unwrap_or("") {
115            "message_start" => {
116                self.saw_delta.store(false, Ordering::SeqCst);
117            }
118            "content_block_delta" => {
119                let delta = &ev["delta"];
120                match delta["type"].as_str().unwrap_or("") {
121                    "text_delta" => {
122                        if let Some(t) = delta["text"].as_str() {
123                            self.saw_delta.store(true, Ordering::SeqCst);
124                            let out = self
125                                .stream
126                                .lock()
127                                .unwrap_or_else(|e| e.into_inner())
128                                .push("msg", t);
129                            if !out.is_empty() {
130                                self.emit(AgentEvent::Output(out));
131                            }
132                        }
133                    }
134                    "thinking_delta" => {
135                        if let Some(t) = delta["thinking"].as_str() {
136                            let out = self
137                                .stream
138                                .lock()
139                                .unwrap_or_else(|e| e.into_inner())
140                                .push("think", t);
141                            if !out.is_empty() {
142                                self.emit(AgentEvent::Output(out));
143                            }
144                        }
145                    }
146                    _ => {}
147                }
148            }
149            // Finish text output when a tool call starts so the order is correct.
150            "content_block_start"
151                if ev
152                    .get("content_block")
153                    .and_then(|b| b.get("type"))
154                    .and_then(|t| t.as_str())
155                    == Some("tool_use") =>
156            {
157                self.flush_stream();
158            }
159            _ => {}
160        }
161    }
162
163    /// Full assistant message: attaches tool calls and text (when partial messages are disabled).
164    fn on_assistant(&self, msg: &Value) {
165        let content = msg
166            .get("message")
167            .and_then(|m| m.get("content"))
168            .and_then(|c| c.as_array())
169            .cloned()
170            .unwrap_or_default();
171        for block in &content {
172            match block["type"].as_str().unwrap_or("") {
173                "text" => {
174                    // Do not output again if already streamed via delta.
175                    if self.saw_delta.load(Ordering::SeqCst) {
176                        self.flush_stream();
177                    } else {
178                        let text = block["text"].as_str().unwrap_or("");
179                        if !text.is_empty() {
180                            self.emit(AgentEvent::Output(format!("{text}\n")));
181                        }
182                    }
183                }
184                "tool_use" => {
185                    self.flush_stream();
186                    let name = block["name"].as_str().unwrap_or("tool").to_string();
187                    let input = block["input"].to_string();
188                    self.emit(AgentEvent::ToolCall {
189                        name,
190                        input,
191                        ok: None,
192                        output: None,
193                    });
194                }
195                "thinking" => {}
196                _ => {}
197            }
198        }
199        // Context usage = input tokens for this assistant message (including cache); window size is only known at `result`.
200        let u = msg.get("message").and_then(|m| m.get("usage"));
201        if let Some(u) = u {
202            if !u.is_null() {
203                let used = u
204                    .get("input_tokens")
205                    .and_then(|v| v.as_u64())
206                    .unwrap_or(0)
207                    .saturating_add(
208                        u.get("cache_creation_input_tokens")
209                            .and_then(|v| v.as_u64())
210                            .unwrap_or(0),
211                    )
212                    .saturating_add(
213                        u.get("cache_read_input_tokens")
214                            .and_then(|v| v.as_u64())
215                            .unwrap_or(0),
216                    );
217                if used > 0 {
218                    self.emit(AgentEvent::Context { used, window: None });
219                }
220            }
221        }
222        // Do not emit per-message usage here: it only has tokens for a single message, which would overwrite
223        // cumulative totals with smaller numbers causing costs and tokens to jump backward mid-turn. Cumulative values rely on `result`.
224    }
225
226    /// Tool result (Claude reports this via a `user` message).
227    fn on_tool_results(&self, msg: &Value) {
228        let content = msg
229            .get("message")
230            .and_then(|m| m.get("content"))
231            .and_then(|c| c.as_array())
232            .cloned()
233            .unwrap_or_default();
234        for block in &content {
235            if block["type"].as_str() != Some("tool_result") {
236                continue;
237            }
238            let ok = !block["is_error"].as_bool().unwrap_or(false);
239            let output = match &block["content"] {
240                Value::String(s) => s.clone(),
241                // MCP tool returns [{"type":"text","text":...}]: extract text, do not show JSON envelope.
242                Value::Array(parts) if parts.iter().all(|p| p["text"].is_string()) => parts
243                    .iter()
244                    .filter_map(|p| p["text"].as_str())
245                    .collect::<Vec<_>>()
246                    .join("\n"),
247                other => other.to_string(),
248            };
249            self.emit(AgentEvent::ToolCall {
250                name: String::new(),
251                input: String::new(),
252                ok: Some(ok),
253                output: Some(truncate(&output, 4000)),
254            });
255        }
256    }
257
258    fn on_result(&self, msg: &Value) {
259        self.flush_stream();
260        if let Some(window) = msg["modelUsage"]
261            .as_object()
262            .and_then(|m| m.values().filter_map(|v| v["contextWindow"].as_u64()).max())
263        {
264            // Reuse usage from the latest assistant message; here only fill in the window size.
265            self.emit(AgentEvent::Context {
266                used: 0,
267                window: Some(window),
268            });
269        }
270        if let Some(cost) = result_cost(msg) {
271            self.emit(AgentEvent::Cost(cost));
272        }
273        let was_interrupted = self.interrupted.swap(false, Ordering::SeqCst);
274        if is_interrupt_result(msg, was_interrupted) {
275            // A user interrupt makes Claude report an errored result; the session itself is still healthy.
276            self.emit(AgentEvent::Status(SessionStatus::Idle));
277        } else if msg["is_error"].as_bool().unwrap_or(false) {
278            let detail = msg["result"].as_str().unwrap_or("").to_string();
279            if ertangle_core::looks_like_limit(&detail) {
280                self.emit(AgentEvent::Limited(detail));
281            } else if !detail.trim().is_empty() {
282                let note = tr!("claude 錯誤:{detail}", detail = detail.trim());
283                self.emit(AgentEvent::Output(format!("⚠ {note}\n")));
284                self.emit(AgentEvent::Note(note));
285            }
286            self.emit(AgentEvent::Status(SessionStatus::Failed));
287        } else {
288            self.emit(AgentEvent::Status(SessionStatus::Idle));
289        }
290    }
291}
292
293/// Whether `msg` is the errored `result` Claude emits after an interrupt we requested.
294fn is_interrupt_result(msg: &Value, interrupted: bool) -> bool {
295    interrupted
296        && msg["is_error"].as_bool().unwrap_or(false)
297        && msg["subtype"].as_str() == Some("error_during_execution")
298}
299
300/// Parses `rate_limit_event`: each window in `unifiedWindows` has `utilization` (0..1) and `resetsAt` (seconds).
301pub(crate) fn parse_rate_limit_event(msg: &Value) -> Option<ertangle_core::Quota> {
302    let info = &msg["rate_limit_info"];
303    let mut windows: Vec<ertangle_core::QuotaWindow> = Vec::new();
304    // `allowed_warning` (approaching limit warning) is still usable; only non-`allowed*` statuses like `rejected` count as exhausted.
305    let blocked = |v: &Value| v.as_str().is_some_and(|s| !s.starts_with("allowed"));
306    let mut reached = blocked(&info["status"]);
307    let warns = |v: &Value| v.as_str() == Some("allowed_warning");
308    let mut warning = warns(&info["status"]);
309    if let Some(map) = info["unifiedWindows"].as_object() {
310        for (key, w) in map {
311            let name = match key.as_str() {
312                "five_hour" => "5h".to_string(),
313                "seven_day" => "7d".to_string(),
314                other => other.to_string(),
315            };
316            let used = w["utilization"].as_f64()? as f32 * 100.0;
317            if blocked(&w["status"]) {
318                reached = true;
319            }
320            warning |= warns(&w["status"]);
321            windows.push(ertangle_core::QuotaWindow {
322                name,
323                used_percent: used,
324                resets_at_ms: w["resetsAt"].as_u64().map(|s| s.saturating_mul(1000)),
325            });
326        }
327    }
328    if windows.is_empty() {
329        return None;
330    }
331    windows.sort_by(|a, b| a.name.cmp(&b.name));
332    Some(ertangle_core::Quota {
333        agent: "claude".into(),
334        windows,
335        reached,
336        warning,
337        updated_ms: ertangle_core::now_millis(),
338    })
339}
340
341/// Estimates cost from Anthropic's usage block (Claude only provides totals in `result`).
342fn result_cost(msg: &Value) -> Option<Cost> {
343    let usd = msg["total_cost_usd"].as_f64()?;
344    let usage = &msg["usage"];
345    Some(Cost {
346        usd,
347        input_tokens: usage["input_tokens"]
348            .as_u64()
349            .unwrap_or(0)
350            .saturating_add(usage["cache_read_input_tokens"].as_u64().unwrap_or(0)),
351        output_tokens: usage["output_tokens"].as_u64().unwrap_or(0),
352    })
353}
354
355fn truncate(s: &str, max: usize) -> String {
356    if s.chars().count() <= max {
357        return s.to_string();
358    }
359    let mut out: String = s.chars().take(max).collect();
360    out.push('…');
361    out
362}
363
364// ---------------------------------------------------------------------------
365// Control handle
366// ---------------------------------------------------------------------------
367
368/// Control message for switching models.
369fn set_model_request(model: &str) -> Value {
370    json!({
371        "type": "control_request",
372        "request_id": format!("ertangle-model-{}", std::process::id()),
373        "request": { "subtype": "set_model", "model": model }
374    })
375}
376
377struct ClaudeControl {
378    conn: Arc<Conn>,
379    child: Arc<Mutex<Child>>,
380}
381
382impl AgentControl for ClaudeControl {
383    fn send_input(&self, text: &str) -> Result<()> {
384        self.send_input_with(text, &[])
385    }
386
387    fn send_input_with(&self, text: &str, atts: &[ertangle_core::Attachment]) -> Result<()> {
388        self.conn.emit(AgentEvent::Status(SessionStatus::Busy));
389        self.conn.send_raw(&json!({
390            "type": "user",
391            "message": { "role": "user", "content": user_content(text, atts) }
392        }))
393    }
394
395    /// Sends an interrupt control message (best-effort; Claude has no public cancellation API).
396    fn cancel(&self) -> Result<()> {
397        self.conn.flush_stream();
398        self.conn.interrupted.store(true, Ordering::SeqCst);
399        self.conn.send_raw(&json!({
400            "type": "control_request",
401            "request_id": format!("ertangle-cancel-{}", std::process::id()),
402            "request": { "subtype": "interrupt" }
403        }))
404    }
405
406    fn pid(&self) -> Option<u32> {
407        Some(self.child.lock().unwrap_or_else(|e| e.into_inner()).id())
408    }
409
410    fn kill(&self) -> Result<()> {
411        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
412        // Terminate the process group or process, ignoring signal send errors.
413        let _ = crate::signal_pgid(pid, "-KILL").or_else(|_| crate::signal_pid(pid, "-KILL"));
414        self.child
415            .lock()
416            .unwrap_or_else(|e| e.into_inner())
417            .kill()
418            .ok();
419        Ok(())
420    }
421
422    fn sleep(&self) -> Result<()> {
423        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
424        crate::signal_pgid(pid, "-STOP").or_else(|_| crate::signal_pid(pid, "-STOP"))
425    }
426
427    fn wake(&self) -> Result<()> {
428        let pid = self.child.lock().unwrap_or_else(|e| e.into_inner()).id();
429        crate::signal_pgid(pid, "-CONT").or_else(|_| crate::signal_pid(pid, "-CONT"))
430    }
431
432    /// Claude's per-item permissions are handled by the daemon via `--permission-prompt-tool` (MCP `ertangle_approve`).
433    fn resolve_permission(&self, _req: &str, _decision: Decision) -> Result<()> {
434        bail!(
435            "{}",
436            tr!("claude 逐項核准已由 MCP (ertangle_approve) 轉發,此請求無效或已逾時")
437        )
438    }
439
440    fn transport(&self) -> &'static str {
441        "stream-json"
442    }
443
444    /// `control_request` for `set_model` (verified working) and `apply_flag_settings` (effortLevel).
445    fn set_config(&self, model: Option<&str>, effort: Option<&str>) -> Result<Option<String>> {
446        if let Some(e) = effort {
447            crate::check_effort(e)?;
448        }
449        if let Some(m) = model {
450            self.conn.send_raw(&set_model_request(m))?;
451        }
452        if let Some(e) = effort {
453            self.conn.send_raw(&json!({
454                "type": "control_request",
455                "request_id": format!("ertangle-effort-{}", std::process::id()),
456                "request": { "subtype": "apply_flag_settings", "settings": { "effortLevel": e } }
457            }))?;
458        }
459        Ok(model.map(str::to_string))
460    }
461}
462
463// ---------------------------------------------------------------------------
464// Startup
465// ---------------------------------------------------------------------------
466
467/// Claude's user content: text (including inlined text files) plus base64 image blocks.
468fn user_content(text: &str, atts: &[ertangle_core::Attachment]) -> Value {
469    let mut blocks =
470        vec![json!({ "type": "text", "text": ertangle_core::compose_text(text, atts, false) })];
471    for a in atts.iter().filter(|a| a.is_image()) {
472        if let Some(data) = &a.data {
473            blocks.push(json!({
474                "type": "image",
475                "source": { "type": "base64", "media_type": a.mime, "data": data }
476            }));
477        }
478    }
479    Value::Array(blocks)
480}
481
482/// Command-line arguments related to permissions and system prompt (read-only, allowed/disallowed tools, fixed ertangle MCP tools, appended system prompt).
483pub fn permission_args(spec: &SessionSpec) -> Vec<String> {
484    let mut out: Vec<String> = Vec::new();
485    if let Some(e) = &spec.effort {
486        out.extend(["--effort".to_string(), e.clone()]);
487    }
488    if let Some(s) = spec.system_append.as_deref().filter(|s| !s.is_empty()) {
489        out.extend(["--append-system-prompt".to_string(), s.to_string()]);
490    }
491    if spec.read_only {
492        out.extend(["--permission-mode".into(), "plan".into()]);
493    } else {
494        out.extend(spec.permission.claude_flags().into_iter().map(String::from));
495    }
496    // When not bypass, tool calls requiring approval are deferred to ertangle (rule engine / user).
497    if spec.mcp_exe.is_some() && spec.permission != ertangle_core::PermissionPolicy::Bypass {
498        out.extend([
499            "--permission-prompt-tool".into(),
500            "mcp__ertangle__ertangle_approve".into(),
501            "--permission-prompts".into(),
502            "host".into(),
503        ]);
504    }
505    let mut allowed = spec.allowed_tools.clone();
506    if spec.mcp_exe.is_some() && spec.permission.auto_approves() {
507        allowed.push("mcp__ertangle__*".into());
508    }
509    if !allowed.is_empty() {
510        out.push(format!("--allowedTools={}", allowed.join(",")));
511    }
512    if !spec.disallowed_tools.is_empty() {
513        out.push(format!(
514            "--disallowedTools={}",
515            spec.disallowed_tools.join(",")
516        ));
517    }
518    out
519}
520
521/// Fixed stream-json arguments plus model and resume (`--resume <id>`: reconnects to original conversation; verified ID does not change).
522fn base_args(spec: &SessionSpec) -> Vec<String> {
523    let mut out: Vec<String> = [
524        "-p",
525        "--input-format",
526        "stream-json",
527        "--output-format",
528        "stream-json",
529        "--verbose",
530        "--include-partial-messages",
531    ]
532    .into_iter()
533    .map(String::from)
534    .collect();
535    if let Some(m) = &spec.model {
536        out.extend(["--model".to_string(), m.clone()]);
537    }
538    if let Some(id) = &spec.resume {
539        out.extend(["--resume".to_string(), id.clone()]);
540    }
541    out
542}
543
544pub fn start(spec: SessionSpec, tx: Sender<AgentEvent>) -> Result<Box<dyn AgentControl>> {
545    let prog = match spec.bin.as_deref() {
546        Some(b) => crate::which(b).with_context(|| tr!("找不到指定的執行檔 `{b}`", b = b))?,
547        None => crate::agent_bin("claude", "ERTANGLE_CLAUDE_BIN")
548            .with_context(|| tr!("找不到 `{prog}`", prog = "claude"))?,
549    };
550    let mut cmd = Command::new(prog);
551    cmd.args(base_args(&spec));
552    cmd.args(permission_args(&spec));
553    if let Some(exe) = &spec.mcp_exe {
554        let mut args = vec!["mcp".to_string(), "--session".to_string(), spec.id.clone()];
555        if let Some((_, sock)) = spec.env.iter().find(|(k, _)| k == "ERTANGLE_SOCKET") {
556            args.push("--socket".to_string());
557            args.push(sock.clone());
558        }
559        let mcp_cfg = json!({
560            "mcpServers": {
561                "ertangle": {
562                    "command": exe.to_string_lossy(),
563                    "args": args
564                }
565            }
566        });
567        cmd.arg(format!("--mcp-config={mcp_cfg}"));
568    }
569    cmd.args(&spec.args);
570    cmd.current_dir(&spec.cwd)
571        .env_remove("CLAUDECODE")
572        .stdin(Stdio::piped())
573        .stdout(Stdio::piped())
574        .stderr(Stdio::piped());
575    for (k, v) in &spec.env {
576        cmd.env(k, v);
577    }
578    #[cfg(unix)]
579    {
580        use std::os::unix::process::CommandExt;
581        cmd.process_group(0);
582    }
583
584    let mut child = cmd.spawn().with_context(|| tr!("無法啟動 `claude`"))?;
585    let stdin = child
586        .stdin
587        .take()
588        .with_context(|| tr!("取得 claude stdin 失敗"))?;
589    let stderr_tail = child.stderr.take().map(crate::stderr::StderrTail::spawn);
590    let stdout = child
591        .stdout
592        .take()
593        .with_context(|| tr!("取得 claude stdout 失敗"))?;
594
595    let conn = Arc::new(Conn {
596        stdin: Mutex::new(stdin),
597        stream: Mutex::new(StreamBuf::default()),
598        interrupted: AtomicBool::new(false),
599        saw_delta: AtomicBool::new(false),
600        tx: tx.clone(),
601    });
602
603    {
604        let conn = conn.clone();
605        std::thread::spawn(move || {
606            let reader = BufReader::new(stdout);
607            for line in reader.lines() {
608                match line {
609                    Ok(l) => conn.on_line(&l),
610                    Err(_) => break,
611                }
612            }
613        });
614    }
615
616    let child = Arc::new(Mutex::new(child));
617    {
618        let child = child.clone();
619        let tx = tx.clone();
620        std::thread::spawn(move || {
621            // Poll with try_wait: do not hold lock during blocking wait, otherwise kill() will deadlock.
622            let code = loop {
623                let status = {
624                    let mut c = child.lock().unwrap_or_else(|e| e.into_inner());
625                    c.try_wait()
626                };
627                match status {
628                    Ok(Some(s)) => break s.code(),
629                    Ok(None) => std::thread::sleep(Duration::from_millis(100)),
630                    Err(_) => break None,
631                }
632            };
633            if let Some(t) = &stderr_tail {
634                t.report_exit(code, &tx);
635            }
636            // Ignore exit event if the receiver is already closed.
637            let _ = tx.send(AgentEvent::Exited(code));
638        });
639    }
640
641    let control = ClaudeControl { conn, child };
642    if let Some(p) = &spec.initial_prompt {
643        control.send_input_with(p, &spec.initial_attachments)?;
644    }
645    Ok(Box::new(control))
646}
647
648#[cfg(test)]
649mod tests {
650    use super::*;
651
652    #[test]
653    fn parses_result_cost() {
654        let msg = json!({
655            "type":"result","subtype":"success","is_error":false,
656            "total_cost_usd":0.5,
657            "usage":{"input_tokens":10,"cache_read_input_tokens":5,"output_tokens":20}
658        });
659        let c = result_cost(&msg).unwrap();
660        assert_eq!(c.input_tokens, 15);
661        assert_eq!(c.output_tokens, 20);
662        assert!((c.usd - 0.5).abs() < 1e-9);
663    }
664
665    #[test]
666    fn interrupt_result_is_not_a_failure() {
667        let err = json!({"type":"result","subtype":"error_during_execution","is_error":true});
668        assert!(is_interrupt_result(&err, true));
669        assert!(!is_interrupt_result(&err, false));
670        let ok = json!({"type":"result","subtype":"success","is_error":false});
671        assert!(!is_interrupt_result(&ok, true));
672        let other = json!({"type":"result","subtype":"error_max_turns","is_error":true});
673        assert!(!is_interrupt_result(&other, true));
674    }
675
676    fn spec_for_args() -> SessionSpec {
677        SessionSpec {
678            id: "s".into(),
679            kind: ertangle_core::AgentKind::ClaudeCode,
680            cwd: std::env::temp_dir(),
681            transport: ertangle_protocol::Transport::Structured,
682            bin: None,
683            args: vec![],
684            model: None,
685            effort: None,
686            allowed_tools: vec!["Read".into(), "Grep".into()],
687            disallowed_tools: vec!["Bash".into()],
688            read_only: false,
689            sandbox: None,
690            env: vec![],
691            permission: ertangle_core::PermissionPolicy::Auto,
692            mcp_exe: Some("/bin/ertangle".into()),
693            system_append: None,
694            initial_prompt: None,
695            initial_attachments: vec![],
696            resume: None,
697            cols: 80,
698            rows: 24,
699        }
700    }
701
702    #[test]
703    fn permission_args_merge_allowed_tools_with_mcp() {
704        let a = permission_args(&spec_for_args());
705        assert!(
706            a.contains(&"--allowedTools=Read,Grep,mcp__ertangle__*".to_string()),
707            "{a:?}"
708        );
709        assert!(a.contains(&"--disallowedTools=Bash".to_string()));
710        let mut s = spec_for_args();
711        s.read_only = true;
712        let a = permission_args(&s);
713        assert!(a.windows(2).any(|w| w == ["--permission-mode", "plan"]));
714    }
715
716    #[test]
717    fn user_content_adds_image_block_and_embeds_text_files() {
718        let atts = vec![
719            ertangle_core::Attachment {
720                name: "p.png".into(),
721                mime: "image/png".into(),
722                data: Some("QUJD".into()),
723                ..Default::default()
724            },
725            ertangle_core::Attachment {
726                name: "n.txt".into(),
727                mime: "text/plain".into(),
728                text: Some("hi".into()),
729                ..Default::default()
730            },
731        ];
732        let c = user_content("看", &atts);
733        let arr = c.as_array().unwrap();
734        assert_eq!(arr.len(), 2);
735        assert!(arr[0]["text"].as_str().unwrap().contains("hi"));
736        assert_eq!(arr[1]["type"], "image");
737        assert_eq!(arr[1]["source"]["media_type"], "image/png");
738        assert_eq!(arr[1]["source"]["data"], "QUJD");
739    }
740
741    #[test]
742    fn parses_real_rate_limit_event() {
743        let msg: Value = serde_json::from_str(
744            r#"{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1794543000,"rateLimitType":"five_hour","unifiedWindows":{"five_hour":{"utilization":0.39,"resetsAt":1794543000,"status":"allowed"},"seven_day":{"utilization":0.22,"resetsAt":1795042800,"status":"allowed"}}}}"#,
745        )
746        .unwrap();
747        let q = parse_rate_limit_event(&msg).unwrap();
748        assert_eq!(q.agent, "claude");
749        assert_eq!(q.windows.len(), 2);
750        let h5 = q.windows.iter().find(|w| w.name == "5h").unwrap();
751        assert!((h5.used_percent - 39.0).abs() < 0.01);
752        assert_eq!(h5.resets_at_ms, Some(1794543000 * 1000));
753        assert!(!q.reached);
754        let blocked = serde_json::json!({"rate_limit_info":{"status":"rejected","unifiedWindows":{"five_hour":{"utilization":1.0,"resetsAt":1,"status":"rejected"}}}});
755        assert!(parse_rate_limit_event(&blocked).unwrap().reached);
756        let warning = serde_json::json!({"rate_limit_info":{"status":"allowed_warning","unifiedWindows":{"seven_day":{"utilization":0.76,"resetsAt":1,"status":"allowed_warning"}}}});
757        let wq = parse_rate_limit_event(&warning).unwrap();
758        assert!(!wq.reached && wq.warning);
759        assert!(!q.warning);
760    }
761
762    #[test]
763    fn resume_flag_added_only_when_resuming() {
764        let mut s = spec_for_args();
765        assert!(!base_args(&s).iter().any(|a| a == "--resume"));
766        s.resume = Some("abc-123".into());
767        let a = base_args(&s);
768        assert!(a.windows(2).any(|w| w == ["--resume", "abc-123"]), "{a:?}");
769    }
770
771    #[test]
772    fn effort_flag_added() {
773        let mut s = spec_for_args();
774        s.effort = Some("high".into());
775        let a = permission_args(&s);
776        assert!(a.windows(2).any(|w| w == ["--effort", "high"]), "{a:?}");
777    }
778
779    #[test]
780    fn system_append_flag_added_only_when_present() {
781        let s = spec_for_args();
782        let a = permission_args(&s);
783        assert!(!a.iter().any(|x| x == "--append-system-prompt"), "{a:?}");
784
785        let mut s2 = spec_for_args();
786        s2.system_append = Some("collab text".into());
787        let a2 = permission_args(&s2);
788        assert!(
789            a2.windows(2)
790                .any(|w| w == ["--append-system-prompt", "collab text"]),
791            "{a2:?}"
792        );
793    }
794
795    #[test]
796    fn prompt_tool_flag_added_unless_bypass() {
797        let a = permission_args(&spec_for_args());
798        assert!(a.windows(2).any(|w| w
799            == [
800                "--permission-prompt-tool",
801                "mcp__ertangle__ertangle_approve"
802            ]));
803        assert!(a.windows(2).any(|w| w == ["--permission-prompts", "host"]));
804        let mut s = spec_for_args();
805        s.permission = ertangle_core::PermissionPolicy::Bypass;
806        assert!(!permission_args(&s)
807            .iter()
808            .any(|x| x.contains("permission-prompt-tool")));
809        assert!(!permission_args(&s)
810            .iter()
811            .any(|x| x.contains("permission-prompts")));
812    }
813
814    #[test]
815    fn truncates_long_tool_output() {
816        let s = "x".repeat(10);
817        assert_eq!(truncate(&s, 4), "xxxx…");
818        assert_eq!(truncate("abc", 4), "abc");
819    }
820
821    #[test]
822    fn set_model_request_shape() {
823        let v = set_model_request("opus");
824        assert_eq!(v["type"], "control_request");
825        assert_eq!(v["request"]["subtype"], "set_model");
826        assert_eq!(v["request"]["model"], "opus");
827    }
828}