Skip to main content

orch/engine/agents/claude/
mod.rs

1//! Claude-compatible agent runner.
2//!
3//! Handles Claude, Kimi, and MiniMax agents. All three use the same
4//! `claude` binary (or a shell wrapper that sets `ANTHROPIC_BASE_URL`).
5//!
6//! ## CLI invocation
7//!
8//! ```bash
9//! claude -p --model {model} \
10//!   --permission-mode bypassPermissions \
11//!   --output-format stream-json \
12//!   --disallowedTools '...' \
13//!   --append-system-prompt "{sys_file}" \
14//!   < "{msg_file}"
15//! ```
16//!
17//! ## Output format (`--output-format stream-json`)
18//!
19//! NDJSON event stream; the final event is always `"type": "result"`:
20//! ```jsonl
21//! {"type":"system","subtype":"init",...}
22//! {"type":"assistant","message":{...}}
23//! {"type":"tool_use","tool":{...}}
24//! {"type":"tool_result","result":{...}}
25//! {"type":"result","subtype":"success","is_error":false,"duration_ms":2006,"result":"...","usage":{"input_tokens":10,"output_tokens":78},"modelUsage":{...}}
26//! ```
27//!
28//! Backward compatible with `--output-format json` (single JSON blob) — the
29//! parser finds the last `"type":"result"` line whether it is NDJSON or a
30//! pretty-printed single object.
31//!
32//! ## Kimi/MiniMax wrappers
33//!
34//! Both are shell scripts that `exec` the claude binary with custom env:
35//! ```bash
36//! exec env ANTHROPIC_BASE_URL=... ANTHROPIC_API_KEY=... claude "$@"
37//! ```
38//!
39//! ## Known error patterns
40//!
41//! - `is_error: true` with various message strings
42//! - "credit balance too low" — billing/auth
43//! - "overloaded" — capacity / rate limit (HTTP 529)
44//! - "rate limit" / "429" — standard rate limiting
45//! - "context_length_exceeded" — context overflow
46
47use std::path::PathBuf;
48
49use tokio::process::Command;
50
51use super::SandboxLevel;
52use super::{
53    AgentError, AgentRunner, ParsedResponse, PermissionRules, StreamEvent, json_error_message,
54    json_str,
55};
56use crate::cooldown::RateLimitWindow;
57use crate::engine::agents::opencode;
58use crate::engine::agents::parser;
59
60/// Runner for Claude-compatible agents (Claude, Kimi, MiniMax).
61#[derive(Debug)]
62pub struct ClaudeRunner {
63    /// The agent binary name (claude, kimi, minimax, or custom).
64    binary: String,
65}
66
67impl ClaudeRunner {
68    pub fn new(agent_name: &str) -> Self {
69        Self {
70            binary: agent_name.to_string(),
71        }
72    }
73
74    /// Parse the Claude `--output-format json` envelope.
75    ///
76    /// Extracts `result`, `usage`, and `is_error`.
77    fn parse_envelope(raw: &str) -> Result<ParsedResponse, AgentError> {
78        let parsed_json: serde_json::Value = serde_json::from_str(raw).map_err(|_| {
79            // Not valid JSON at all — try as raw text
80            AgentError::InvalidResponse {
81                raw: raw.to_string(),
82            }
83        })?;
84
85        let envelope = parsed_json
86            .as_object()
87            .ok_or_else(|| AgentError::InvalidResponse {
88                raw: raw.to_string(),
89            })?;
90
91        // Check if this is a Claude envelope (has "type" field)
92        let is_envelope = envelope.get("type").and_then(|v| v.as_str()) == Some("result");
93
94        if !is_envelope {
95            // Not a Claude envelope — try direct parsing via generic parser
96            return Self::parse_direct(raw);
97        }
98
99        // Check is_error flag
100        let is_error = envelope
101            .get("is_error")
102            .and_then(serde_json::Value::as_bool)
103            .unwrap_or(false);
104
105        // Extract the result text
106        let error_text = if is_error {
107            envelope_error_text(envelope)
108        } else {
109            String::new()
110        };
111        let result_text = if is_error {
112            error_text.as_str()
113        } else {
114            envelope
115                .get("result")
116                .and_then(|v| v.as_str())
117                .unwrap_or("")
118        };
119
120        if is_error {
121            // Classify the error from the result text.
122            // Check stale session first — it requires a targeted recovery action
123            // (reset UUID + retry) that is distinct from generic agent failures.
124            if let Some(e) = super::patterns::detect_stale_session(result_text) {
125                return Err(e);
126            }
127            // Check thinking block conflict before auth — it's a specific 400
128            // that must not be counted as a model failure.
129            if let Some(e) = super::patterns::detect_thinking_block_conflict(result_text) {
130                return Err(e);
131            }
132            // Check auth before rate_limit — billing errors (credit balance)
133            // are auth issues, not transient rate limits.
134            // Use result_text only (not combined with raw JSON) so the error
135            // message stays clean — the raw NDJSON stats blob must not leak
136            // into the logged reason string.
137            if let Some(e) = super::patterns::detect_auth_error(result_text) {
138                return Err(e);
139            }
140            if let Some(e) = super::patterns::detect_rate_limit(result_text) {
141                return Err(e);
142            }
143            if let Some(e) = super::patterns::detect_context_overflow(result_text) {
144                return Err(e);
145            }
146            return Err(AgentError::AgentFailed {
147                message: result_text.to_string(),
148            });
149        }
150
151        // Extract token usage from top-level `usage` object
152        let (input_tokens, output_tokens) = extract_usage(envelope);
153
154        // Extract duration
155        let duration_ms = envelope
156            .get("duration_ms")
157            .and_then(serde_json::Value::as_u64);
158
159        // Parse the inner result text into AgentResponse.
160        // Do NOT check for rate limits here — result_text is agent work product
161        // (summary, code descriptions) when is_error=false. Rate-limit keywords
162        // in work product cause false positives (see issue #1292).
163        let response = match parser::parse(result_text) {
164            Ok(r) => r,
165            Err(_) => {
166                // Structured parse failed — try plain-text synthesis.
167                // Preserve already-extracted tokens rather than discarding them (issue #1387).
168                super::synthesize_response_from_text(result_text).ok_or_else(|| {
169                    AgentError::InvalidResponse {
170                        raw: result_text.to_string(),
171                    }
172                })?
173            }
174        };
175
176        Ok(ParsedResponse {
177            response,
178            input_tokens,
179            output_tokens,
180            cost_usd: envelope_cost(envelope),
181            duration_ms,
182        })
183    }
184
185    /// Parse raw text directly (non-envelope response).
186    fn parse_direct(raw: &str) -> Result<ParsedResponse, AgentError> {
187        let response = parser::parse(raw).map_err(|_| AgentError::InvalidResponse {
188            raw: raw.to_string(),
189        })?;
190
191        Ok(ParsedResponse {
192            response,
193            input_tokens: None,
194            output_tokens: None,
195            cost_usd: None,
196            duration_ms: None,
197        })
198    }
199}
200
201/// Error text of an `is_error` envelope: `result`, else the joined `errors[]`, else `subtype`.
202/// Some agents (e.g. billing failures) put the message only in `errors[]`
203fn envelope_error_text(obj: &serde_json::Map<String, serde_json::Value>) -> String {
204    let result = obj.get("result").and_then(|v| v.as_str()).unwrap_or("");
205    if !result.is_empty() {
206        return result.to_string();
207    }
208    let errors = obj
209        .get("errors")
210        .and_then(|v| v.as_array())
211        .map(|a| {
212            a.iter()
213                .filter_map(|e| e.as_str())
214                .collect::<Vec<_>>()
215                .join("\n")
216        })
217        .unwrap_or_default();
218    if !errors.is_empty() {
219        return errors;
220    }
221    obj.get("subtype")
222        .and_then(|v| v.as_str())
223        .unwrap_or("")
224        .to_string()
225}
226
227/// Helper: extract error from a JSON object if it is a `type:result` envelope
228/// with `is_error=true`. Uses pattern detection for proper error classification
229/// (auth, rate limit, context overflow) rather than always returning AgentFailed.
230fn extract_error_from_envelope(
231    obj: &serde_json::Map<String, serde_json::Value>,
232    _raw: &str,
233) -> Option<AgentError> {
234    if obj.get("type").and_then(|v| v.as_str()) == Some("result")
235        && obj
236            .get("is_error")
237            .and_then(serde_json::Value::as_bool)
238            .unwrap_or(false)
239    {
240        let result_text = envelope_error_text(obj);
241        let result_text = result_text.as_str();
242        // Use result_text only (not combined with raw JSON) so the error
243        // message stays clean — the raw NDJSON stats blob must not leak
244        // into the logged reason string.
245        if let Some(e) = super::patterns::detect_thinking_block_conflict(result_text) {
246            return Some(e);
247        }
248        if let Some(e) = super::patterns::detect_auth_error(result_text) {
249            return Some(e);
250        }
251        if let Some(e) = super::patterns::detect_rate_limit(result_text) {
252            return Some(e);
253        }
254        if let Some(e) = super::patterns::detect_context_overflow(result_text) {
255            return Some(e);
256        }
257        return Some(AgentError::AgentFailed {
258            message: result_text.to_string(),
259        });
260    }
261    None
262}
263
264/// Helper: scan NDJSON lines in `text` for a `type:result` envelope with
265/// `is_error=true` and extract the error message. Returns `None` if no error
266/// envelope is found.
267fn detect_error_envelope(text: &str) -> Option<AgentError> {
268    for line in text.lines().filter(|l| !l.trim().is_empty()) {
269        if let Ok(val) = serde_json::from_str::<serde_json::Value>(line)
270            && let Some(obj) = val.as_object()
271            && let Some(err) = extract_error_from_envelope(obj, line)
272        {
273            return Some(err);
274        }
275    }
276    None
277}
278
279pub(crate) fn extract_stream_json_result_text(raw: &str) -> Result<String, AgentError> {
280    let trimmed = raw.trim();
281    if trimmed.is_empty() {
282        return Err(AgentError::InvalidResponse { raw: String::new() });
283    }
284
285    // Prefer the final result envelope whose result field is valid JSON.
286    // This skips outer-session plain-text summaries (issue #1387).
287    let envelope_line_opt = find_ndjson_result_line(trimmed).map(|(line, _)| line);
288
289    if let Some(line) = envelope_line_opt {
290        // Parse the found result line.
291        if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(line)
292            && let Some(obj) = parsed.as_object()
293        {
294            // Check is_error FIRST.
295            if let Some(err) = extract_error_from_envelope(obj, line) {
296                return Err(err);
297            }
298            // Extract result text from the JSON object.
299            if let Some(result) = obj.get("result") {
300                if let Some(text) = result.as_str() {
301                    return Ok(text.to_string());
302                }
303                if result.is_object() || result.is_array() {
304                    return Ok(result.to_string());
305                }
306            }
307        }
308        // Not an error, but result field is not extractable: fall through to fallback.
309    }
310
311    // No JSON result line found (or it wasn't an error). Try opencode-style
312    // text extraction which scans NDJSON for text/result events.
313    if let Some(fallback) = opencode::extract_router_text(trimmed) {
314        return Ok(fallback);
315    }
316
317    // No opencode-style text found. Try parsing the whole trimmed string as a
318    // single JSON object (handles `--output-format json` plain output).
319    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(trimmed)
320        && let Some(obj) = parsed.as_object()
321    {
322        // Check for error envelope in the single-line JSON.
323        if let Some(err) = extract_error_from_envelope(obj, trimmed) {
324            return Err(err);
325        }
326        // Extract result text from the JSON object.
327        if let Some(result) = obj.get("result") {
328            if let Some(text) = result.as_str() {
329                return Ok(text.to_string());
330            }
331            if result.is_object() || result.is_array() {
332                return Ok(result.to_string());
333            }
334        }
335        return Ok(trimmed.to_string());
336    }
337
338    // Not valid JSON at all. Before returning raw text, scan for error envelopes
339    // (handles the case where find_ndjson_result_line skipped error-only output).
340    if let Some(err) = detect_error_envelope(trimmed) {
341        return Err(err);
342    }
343
344    Ok(trimmed.to_string())
345}
346
347impl AgentRunner for ClaudeRunner {
348    #[cfg(test)]
349    fn name(&self) -> &str {
350        &self.binary
351    }
352
353    fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent> {
354        stream_events(event)
355    }
356
357    fn router_transcript(&self) -> super::RouterTranscript {
358        super::RouterTranscript::Messages
359    }
360
361    fn extract_text(&self, raw: &str) -> Result<String, super::AgentError> {
362        // Empty input: return empty string (not an error), matching historical behavior.
363        if raw.trim().is_empty() {
364            return Ok(String::new());
365        }
366        extract_stream_json_result_text(raw)
367    }
368
369    fn build_command(
370        &self,
371        model: Option<&str>,
372        timeout_cmd: &str,
373        sys_file: &str,
374        msg_file: &str,
375        permissions: &PermissionRules,
376    ) -> String {
377        self.build_command_with_effort(model, None, timeout_cmd, sys_file, msg_file, permissions)
378    }
379
380    fn build_command_with_effort(
381        &self,
382        model: Option<&str>,
383        effort: Option<&str>,
384        timeout_cmd: &str,
385        sys_file: &str,
386        msg_file: &str,
387        permissions: &PermissionRules,
388    ) -> String {
389        let effort_flag = effort
390            .map(|e| format!(" --effort {}", super::shell_single_quote(e)))
391            .unwrap_or_default();
392        let model_flag = model
393            .map(str::trim)
394            .filter(|m| !m.is_empty())
395            .map(|m| format!("--model {}", super::shell_single_quote(m)))
396            .unwrap_or_default();
397
398        // Claude permission mode: autonomous → bypassPermissions, supervised → acceptEdits
399        // dontAsk refuses every tool not on --allowedTools instead of asking, so a read-only
400        // chat runs its allowlist and nothing else
401        let permission_mode = if permissions.sandbox == SandboxLevel::ReadOnly {
402            "dontAsk"
403        } else if permissions.autonomous {
404            "bypassPermissions"
405        } else {
406            "acceptEdits"
407        };
408
409        // Build tool restriction flags.
410        // If allowed_tools is set (whitelist), use --allowedTools and ignore disallowed_tools.
411        // Otherwise fall back to --disallowedTools (deny list).
412        let tool_flag = if !permissions.allowed_tools.is_empty() {
413            let tools = translate_allowed_tools(
414                &permissions.allowed_tools,
415                &permissions.allowed_edit_paths,
416            );
417            format!("--allowedTools '{}'", tools.join(","))
418        } else if !permissions.disallowed_tools.is_empty() {
419            format!(
420                "--disallowedTools '{}'",
421                permissions.disallowed_tools.join(",")
422            )
423        } else {
424            String::new()
425        };
426
427        // A read-only chat ignores the operator's own settings files, whose allow rules would widen
428        // its allowlist, loads no MCP server, and has only the tool kinds its allowlist names
429        let (restrict_flag, prompt_flag) = if permissions.sandbox == SandboxLevel::ReadOnly {
430            let mut kinds: Vec<&str> = permissions
431                .allowed_tools
432                .iter()
433                .filter(|t| CLAUDE_NATIVE_TOOLS.contains(&t.as_str()))
434                .map(String::as_str)
435                .collect();
436            if permissions
437                .allowed_tools
438                .iter()
439                .any(|t| t.starts_with("Bash("))
440            {
441                kinds.push("Bash");
442            }
443            (
444                format!(
445                    "--restricted --strict-mcp-config --tools '{}' \\\n  ",
446                    kinds.join(",")
447                ),
448                "--append-system-prompt-file",
449            )
450        } else {
451            (String::new(), "--append-system-prompt")
452        };
453
454        format!(
455            r#"{timeout_cmd} {binary} -p --verbose {model_flag}{effort_flag} \
456  --permission-mode {permission_mode} \
457  --output-format stream-json \
458  {restrict_flag}{tool_flag} \
459  {prompt_flag} "{sys_file}" \
460  < "{msg_file}""#,
461            timeout_cmd = timeout_cmd,
462            binary = self.binary,
463            model_flag = model_flag,
464            permission_mode = permission_mode,
465            tool_flag = tool_flag,
466            sys_file = sys_file,
467            msg_file = msg_file,
468        )
469    }
470
471    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError> {
472        let trimmed = raw.trim();
473        if trimmed.is_empty() {
474            return Err(AgentError::InvalidResponse { raw: String::new() });
475        }
476
477        // For NDJSON (--output-format stream-json): find the best result line and its
478        // token count. For single-line JSON (--output-format json), returns None.
479        if let Some((result_line, tokens)) = find_ndjson_result_line(trimmed) {
480            let result = Self::parse_envelope(result_line)?;
481            // If the envelope parse preserved meaningful tokens, use those.
482            // Otherwise, fall back to the tokens from find_ndjson_result_line
483            // (which selected the best result line by token count — issue #1387).
484            let input_tokens = result.input_tokens.or(tokens.map(|(i, _)| i));
485            let output_tokens = result.output_tokens.or(tokens.map(|(_, o)| o));
486            if input_tokens != result.input_tokens || output_tokens != result.output_tokens {
487                return Ok(ParsedResponse {
488                    input_tokens,
489                    output_tokens,
490                    ..result
491                });
492            }
493            return Ok(result);
494        }
495
496        // Fallback: treat the whole string as the envelope (e.g. pretty-printed JSON)
497        Self::parse_envelope(trimmed)
498    }
499
500    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError {
501        // For claude-protocol agents the real error string lives in the `result`
502        // field of the NDJSON result line (when is_error=true). Prepend it to the
503        // combined text so the classifier sees it before the raw metadata tail.
504        let error_result: Option<String> = (|| {
505            let trimmed = stdout.trim();
506            let (line, _) = find_ndjson_result_line(trimmed)?;
507            let val: serde_json::Value = serde_json::from_str(line).ok()?;
508            let obj = val.as_object()?;
509            if obj.get("is_error").and_then(serde_json::Value::as_bool) != Some(true) {
510                return None;
511            }
512            Some(envelope_error_text(obj)).filter(|t| !t.is_empty())
513        })();
514
515        // Also check for system-level error events (e.g., session limit mid-stream).
516        // These appear as `type:system` NDJSON events with an error object, not as
517        // `type:result` lines with `is_error:true`. This catches errors like session
518        // limits, credential issues, and API errors that interrupt the agent mid-run.
519        //
520        // Example:
521        //   {"type":"system","subtype":"error","error":{"type":"session_limit","message":"..."}}
522        let system_error: Option<String> = (|| {
523            let trimmed = stdout.trim();
524            for line in trimmed.lines() {
525                let line = line.trim();
526                if line.is_empty() {
527                    continue;
528                }
529                if let Ok(val) = serde_json::from_str::<serde_json::Value>(line)
530                    && let Some(obj) = val.as_object()
531                    && obj.get("type").and_then(|t| t.as_str()) == Some("system")
532                    && let Some(error) = obj.get("error")
533                    && let Some(msg) = error.get("message").and_then(|m| m.as_str())
534                {
535                    return Some(msg.to_string());
536                }
537            }
538            None
539        })();
540
541        // A kill signal (SIGTERM or SIGKILL) with no result envelope and no error event
542        // is an interrupted run, not a provider failure, so skip the text scan
543        let has_result_line = find_ndjson_result_line(stdout.trim()).is_some();
544        if matches!(exit_code, 143 | 137)
545            && !has_result_line
546            && error_result.is_none()
547            && system_error.is_none()
548        {
549            return AgentError::Interrupted {
550                message: format!("agent killed by signal (exit {exit_code})"),
551            };
552        }
553
554        let combined = match (&error_result, &system_error) {
555            (Some(r), Some(s)) => format!("{s}\n{r}\n{stdout}\n{stderr}"),
556            (Some(r), None) => format!("{r}\n{stdout}\n{stderr}"),
557            (None, Some(s)) => format!("{s}\n{stdout}\n{stderr}"),
558            (None, None) => format!("{stdout}\n{stderr}"),
559        };
560        // Envelope billing text is prepended into the same 3000-byte head as hook
561        // UUIDs, so classify the envelope before the combined scan
562        if let Some(message) = &error_result
563            && let Some(e) = super::patterns::detect_auth_error(message)
564        {
565            return e;
566        }
567        let classified = super::patterns::classify_from_text(exit_code, &combined);
568
569        // `classify_from_text`'s generic catch-all truncates to the last 300
570        // bytes of the combined text, which can cut a perfectly well-formed
571        // `error_result` line off mid-field-name (e.g. `is_error` becomes
572        // `i_error`) once enough NDJSON precedes it (issue #3577). When we
573        // already extracted a clean, complete error message from the result
574        // envelope but none of the specific pattern detectors matched it,
575        // prefer that clean message over the byte-truncated fallback.
576        if let (AgentError::Unknown { .. }, Some(message)) = (&classified, &error_result)
577            && !message.is_empty()
578        {
579            return AgentError::AgentFailed {
580                message: message.clone(),
581            };
582        }
583        classified
584    }
585
586    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command> {
587        let mut cmd = Command::new(&self.binary);
588        cmd.env_remove("CLAUDECODE"); // allow nested invocation
589        cmd.arg("--output-format")
590            .arg("stream-json")
591            .arg("--verbose")
592            .arg("--print");
593        if let Some(m) = model.map(str::trim).filter(|m| !m.is_empty()) {
594            cmd.arg("--model").arg(m);
595        }
596        cmd.arg(prompt);
597        Ok(cmd)
598    }
599}
600
601/// Known Claude Code native tool names.
602/// These are passed as-is to `--allowedTools`.
603const CLAUDE_NATIVE_TOOLS: &[&str] = &[
604    "Edit",
605    "Write",
606    "Read",
607    "Bash",
608    "Grep",
609    "Glob",
610    "WebFetch",
611    "WebSearch",
612    "Task",
613    "Skill",
614    "NotebookEdit",
615    "EnterPlanMode",
616    "ExitPlanMode",
617    "EnterWorktree",
618    "AskUserQuestion",
619    "TodoWrite",
620    "TodoRead",
621];
622
623/// Translate a unified allowed_tools list into Claude `--allowedTools` patterns.
624///
625/// - Items matching known Claude tool names pass through as-is
626/// - Edit/Write are scoped to `allowed_edit_paths` when set
627/// - Other items are treated as CLI commands and become `Bash(<cmd> *)` patterns
628fn translate_allowed_tools(allowed: &[String], allowed_edit_paths: &[PathBuf]) -> Vec<String> {
629    let mut tools = Vec::new();
630    for item in allowed {
631        if (item == "Edit" || item == "Write") && !allowed_edit_paths.is_empty() {
632            // Scope Edit/Write to allowed paths only
633            for path in allowed_edit_paths {
634                tools.push(format!("{}({}/*)", item, path.display()));
635            }
636        } else if CLAUDE_NATIVE_TOOLS.contains(&item.as_str()) || item.starts_with("Bash(") {
637            tools.push(item.clone());
638        } else {
639            // CLI command → Bash(<cmd> *) pattern
640            tools.push(format!("Bash({item} *)"));
641        }
642    }
643    tools
644}
645
646/// Find the best NDJSON result line and its token usage.
647///
648/// Returns `(line, tokens)` where `tokens` is `Some((input, output))` or `None`
649/// if no usage data was found.
650///
651/// Selection priority:
652/// 1. JSON result fields (object/array or string that parses as JSON) — always preferred
653/// 2. Among plain-text results: the one with the most total tokens (preferring actual
654///    work over outer-session confirmation summaries)
655/// 3. Error results (is_error=true) — included even with no tokens, so the caller can
656///    classify them properly
657///
658/// This skips outer-session plain-text summaries in favor of inner task results
659/// with meaningful token counts (issue #1387).
660pub(crate) fn find_ndjson_result_line(text: &str) -> Option<(&str, Option<(u64, u64)>)> {
661    let lines: Vec<_> = text.lines().filter(|l| !l.trim().is_empty()).collect();
662
663    // Pass 1: find a result line with a JSON result field.
664    // JSON results are always preferred (inner task delegate output).
665    for line in lines.iter().rev() {
666        if let Ok(val) = serde_json::from_str::<serde_json::Value>(line)
667            && let Some(obj) = val.as_object()
668            && obj.get("type").and_then(|t| t.as_str()) == Some("result")
669            && let Some(result) = obj.get("result")
670        {
671            let is_json_result = match result {
672                serde_json::Value::Object(_) | serde_json::Value::Array(_) => true,
673                serde_json::Value::String(s) => {
674                    serde_json::from_str::<serde_json::Value>(s).is_ok()
675                }
676                _ => false,
677            };
678            if is_json_result {
679                let tokens = extract_result_tokens(obj);
680                return Some((line, tokens));
681            }
682        }
683    }
684
685    // Pass 2: no JSON result found — choose the plain-text result with the most tokens.
686    // This handles outer-session confirmation summaries (e.g. "Already retrieved the result")
687    // vs. actual work summaries: prefer the one with more tokens.
688    // Error results (is_error=true) are included even with zero tokens, so the caller
689    // can classify them properly.
690    let mut best_line: Option<&str> = None;
691    let mut best_total = 0u64;
692
693    for line in &lines {
694        if let Ok(val) = serde_json::from_str::<serde_json::Value>(line)
695            && let Some(obj) = val.as_object()
696            && obj.get("type").and_then(|t| t.as_str()) == Some("result")
697        {
698            let tokens = extract_result_tokens(obj);
699            let total = tokens.map_or(0, |(i, o)| i.saturating_add(o));
700            if total >= best_total {
701                best_total = total;
702                best_line = Some(*line);
703            }
704        }
705    }
706
707    best_line.map(|line| (line, extract_result_tokens_from_line(line)))
708}
709
710/// Extract input/output token counts from a parsed result envelope object.
711fn extract_result_tokens(obj: &serde_json::Map<String, serde_json::Value>) -> Option<(u64, u64)> {
712    // Try top-level `usage` first.
713    if let Some(usage) = obj.get("usage").and_then(|v| v.as_object()) {
714        let input = usage
715            .get("input_tokens")
716            .and_then(serde_json::Value::as_u64);
717        let output = usage
718            .get("output_tokens")
719            .and_then(serde_json::Value::as_u64);
720        if let (Some(i), Some(o)) = (input, output) {
721            return Some((i, o));
722        }
723    }
724    // Try modelUsage (aggregated across models).
725    if let Some(model_usage) = obj.get("modelUsage").and_then(|v| v.as_object()) {
726        let mut total_input = 0u64;
727        let mut total_output = 0u64;
728        let mut found = false;
729        for (_model_name, model_stats) in model_usage {
730            if let Some(stats) = model_stats.as_object() {
731                if let Some(i) = stats
732                    .get("inputTokens")
733                    .or_else(|| stats.get("input_tokens"))
734                    .and_then(serde_json::Value::as_u64)
735                {
736                    total_input += i;
737                    found = true;
738                }
739                if let Some(o) = stats
740                    .get("outputTokens")
741                    .or_else(|| stats.get("output_tokens"))
742                    .and_then(serde_json::Value::as_u64)
743                {
744                    total_output += o;
745                    found = true;
746                }
747            }
748        }
749        if found {
750            return Some((total_input, total_output));
751        }
752    }
753    None
754}
755
756/// Extract token counts from a raw NDJSON result line string.
757fn extract_result_tokens_from_line(line: &str) -> Option<(u64, u64)> {
758    let val = serde_json::from_str::<serde_json::Value>(line).ok()?;
759    let obj = val.as_object()?;
760    extract_result_tokens(obj)
761}
762
763/// The run cost the envelope reports. Claude Code names it `total_cost_usd`, older builds used
764/// `costUSD` or `cost_usd`.
765fn envelope_cost(envelope: &serde_json::Map<String, serde_json::Value>) -> Option<f64> {
766    envelope
767        .get("total_cost_usd")
768        .or_else(|| envelope.get("costUSD"))
769        .or_else(|| envelope.get("cost_usd"))
770        .and_then(serde_json::Value::as_f64)
771}
772
773/// Extract input/output tokens from the Claude envelope's usage objects.
774fn extract_usage(
775    envelope: &serde_json::Map<String, serde_json::Value>,
776) -> (Option<u64>, Option<u64>) {
777    // Try top-level `usage` first
778    if let Some(usage) = envelope.get("usage").and_then(|v| v.as_object()) {
779        let input = usage
780            .get("input_tokens")
781            .and_then(serde_json::Value::as_u64);
782        let output = usage
783            .get("output_tokens")
784            .and_then(serde_json::Value::as_u64);
785        if input.is_some() || output.is_some() {
786            return (input, output);
787        }
788    }
789
790    // Try modelUsage (aggregated across models)
791    if let Some(model_usage) = envelope.get("modelUsage").and_then(|v| v.as_object()) {
792        let mut total_input = 0u64;
793        let mut total_output = 0u64;
794        let mut found = false;
795
796        for (_model_name, model_stats) in model_usage {
797            if let Some(stats) = model_stats.as_object() {
798                if let Some(i) = stats
799                    .get("inputTokens")
800                    .or_else(|| stats.get("input_tokens"))
801                    .and_then(serde_json::Value::as_u64)
802                {
803                    total_input += i;
804                    found = true;
805                }
806                if let Some(o) = stats
807                    .get("outputTokens")
808                    .or_else(|| stats.get("output_tokens"))
809                    .and_then(serde_json::Value::as_u64)
810                {
811                    total_output += o;
812                    found = true;
813                }
814            }
815        }
816
817        if found {
818            return (Some(total_input), Some(total_output));
819        }
820    }
821
822    (None, None)
823}
824
825const SHOW_CURSOR: &str = "\x1b[?25h";
826const HIDE_CURSOR: &str = "\x1b[?25l";
827
828/// Drop `script` tty junk: show-cursor (`ESC[?25h`) and `^D`/backspace redraw lines
829pub fn strip_tty_control_lines(raw: &str) -> String {
830    raw.lines()
831        .filter(|line| !is_tty_control_line(line))
832        .map(strip_trailing_cursor)
833        .collect::<Vec<_>>()
834        .join("\n")
835}
836
837fn strip_trailing_cursor(line: &str) -> &str {
838    let mut s = line.trim_end();
839    loop {
840        if let Some(next) = s
841            .strip_suffix(SHOW_CURSOR)
842            .or_else(|| s.strip_suffix(HIDE_CURSOR))
843        {
844            s = next.trim_end();
845            continue;
846        }
847        return s;
848    }
849}
850
851fn is_tty_control_line(line: &str) -> bool {
852    let trimmed = strip_trailing_cursor(line).trim();
853    if trimmed.is_empty() {
854        return !line.trim().is_empty();
855    }
856    trimmed.chars().all(|c| matches!(c, '^' | 'D' | '\u{0008}'))
857}
858
859/// Type of the last content block on the last assistant NDJSON message
860fn last_assistant_content_type(ndjson: &str) -> Option<String> {
861    let mut last = None;
862    for line in ndjson.lines() {
863        let line = line.trim();
864        if line.is_empty() {
865            continue;
866        }
867        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
868            continue;
869        };
870        if val.get("type").and_then(|v| v.as_str()) != Some("assistant") {
871            continue;
872        }
873        let Some(content) = val
874            .get("message")
875            .and_then(|m| m.get("content"))
876            .and_then(|c| c.as_array())
877        else {
878            continue;
879        };
880        if let Some(item) = content.last()
881            && let Some(t) = item.get("type").and_then(|v| v.as_str())
882        {
883            last = Some(t.to_string());
884        }
885    }
886    last
887}
888
889/// True when the stream has no result envelope and ended on a thinking block
890/// or a tool call, so the model never produced a finished review decision
891pub fn review_session_exited_mid_thought(ndjson: &str) -> bool {
892    if find_ndjson_result_line(ndjson).is_some() {
893        return false;
894    }
895    matches!(
896        last_assistant_content_type(ndjson).as_deref(),
897        Some("thinking" | "redacted_thinking" | "tool_use")
898    )
899}
900
901/// Extract a structured `AgentResult` from Claude/Kimi/MiniMax NDJSON output.
902///
903/// Finds the last `"type":"result"` line whose `result` field contains valid JSON.
904/// This skips outer-session plain-text summaries (issue #1387) and finds the
905/// actual task-delegate result with structured JSON.
906///
907/// Extracts:
908/// - `result` text (the inner content)
909/// - `is_error` flag
910/// - token usage from `usage` or `modelUsage`
911/// - `duration_ms`
912///
913/// If no JSON result line exists (common with MiniMax), falls back to
914/// extracting the last assistant text message from the stream.
915///
916/// Returns `None` only if the input contains no recognizable NDJSON events.
917pub fn find_claude_result(ndjson: &str) -> Option<super::AgentResult> {
918    let stripped = strip_tty_control_lines(ndjson);
919    let trimmed = stripped.trim();
920    if trimmed.is_empty() {
921        return None;
922    }
923
924    // Try to find the result envelope first
925    if let Some((result_line, _tokens)) = find_ndjson_result_line(trimmed)
926        && let Ok(parsed) = serde_json::from_str::<serde_json::Value>(result_line)
927        && let Some(envelope) = parsed.as_object()
928    {
929        let is_error = envelope
930            .get("is_error")
931            .and_then(serde_json::Value::as_bool)
932            .unwrap_or(false);
933
934        let result_text = if is_error {
935            // Error envelopes put the real message in errors[] (billing,
936            // rate limits) with `result` empty — don't lose it (issue #3713)
937            envelope_error_text(envelope)
938        } else {
939            envelope
940                .get("result")
941                .and_then(|v| v.as_str())
942                .unwrap_or("")
943                .to_string()
944        };
945
946        let (input_tokens, output_tokens) = extract_usage(envelope);
947        let duration_ms = envelope
948            .get("duration_ms")
949            .and_then(serde_json::Value::as_u64);
950
951        let cost_usd = envelope_cost(envelope);
952
953        return Some(super::AgentResult {
954            is_error,
955            result_text,
956            input_tokens,
957            output_tokens,
958            cost_usd,
959            duration_ms,
960            truncated_by_length: false,
961        });
962    }
963
964    // Fallback for MiniMax/Kimi: extract last assistant text message
965    let mut last_text = None;
966    let mut input_tokens = None;
967    let mut output_tokens = None;
968
969    for line in trimmed.lines() {
970        let line = line.trim();
971        if line.is_empty() {
972            continue;
973        }
974        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
975            continue;
976        };
977        if val.get("type").and_then(|v| v.as_str()) != Some("assistant") {
978            continue;
979        }
980        // Extract text from content array
981        if let Some(content) = val
982            .get("message")
983            .and_then(|m| m.get("content"))
984            .and_then(|c| c.as_array())
985        {
986            for item in content {
987                if item.get("type").and_then(|v| v.as_str()) == Some("text")
988                    && let Some(text) = item.get("text").and_then(|v| v.as_str())
989                {
990                    let t = text.trim();
991                    if !t.is_empty() {
992                        last_text = Some(t.to_string());
993                    }
994                }
995            }
996        }
997        // Extract usage (take max, as Claude reports cumulative)
998        if let Some(usage) = val.get("message").and_then(|m| m.get("usage")) {
999            if let Some(inp) = usage
1000                .get("input_tokens")
1001                .and_then(serde_json::Value::as_u64)
1002            {
1003                input_tokens = Some(input_tokens.unwrap_or(0u64).max(inp));
1004            }
1005            if let Some(out) = usage
1006                .get("output_tokens")
1007                .and_then(serde_json::Value::as_u64)
1008            {
1009                output_tokens = Some(output_tokens.unwrap_or(0u64).max(out));
1010            }
1011        }
1012    }
1013
1014    last_text.map(|text| super::AgentResult {
1015        is_error: false,
1016        result_text: text,
1017        input_tokens,
1018        output_tokens,
1019        cost_usd: None,
1020        duration_ms: None,
1021        truncated_by_length: false,
1022    })
1023}
1024
1025/// Keep a vendor label printable: letters, digits, `_` and `-`, at most 32 characters
1026fn sanitize_window_label(raw: &str) -> String {
1027    raw.chars()
1028        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))
1029        .take(32)
1030        .collect()
1031}
1032
1033/// Every window of every `rate_limit_event`, oldest first. The event status belongs to the headline
1034/// window, the other `unifiedWindows` entries use their own status or `unknown`
1035pub fn rate_limit_windows(ndjson: &str) -> Vec<RateLimitWindow> {
1036    let mut windows = Vec::new();
1037    for line in ndjson
1038        .lines()
1039        .filter(|line| line.contains("rate_limit_event"))
1040    {
1041        let Ok(val) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1042            continue;
1043        };
1044        if val.get("type").and_then(|v| v.as_str()) != Some("rate_limit_event") {
1045            continue;
1046        }
1047        let Some(info) = val.get("rate_limit_info") else {
1048            continue;
1049        };
1050        let Some(status) = info.get("status").and_then(|v| v.as_str()) else {
1051            continue;
1052        };
1053        let unified = info.get("unifiedWindows").and_then(|v| v.as_object());
1054        let headline_raw = info
1055            .get("rateLimitType")
1056            .and_then(|v| v.as_str())
1057            .unwrap_or("unknown");
1058        let headline = unified.and_then(|map| map.get(headline_raw));
1059        windows.push(RateLimitWindow {
1060            status: sanitize_window_label(status),
1061            window_type: sanitize_window_label(headline_raw),
1062            utilization: headline
1063                .and_then(|w| w.get("utilization"))
1064                .or_else(|| info.get("utilization"))
1065                .and_then(serde_json::Value::as_f64),
1066            resets_at: info
1067                .get("resetsAt")
1068                .or_else(|| headline.and_then(|w| w.get("resetsAt")))
1069                .and_then(serde_json::Value::as_i64),
1070        });
1071        for (name, w) in unified.into_iter().flatten() {
1072            if name == headline_raw {
1073                continue;
1074            }
1075            windows.push(RateLimitWindow {
1076                status: sanitize_window_label(
1077                    w.get("status")
1078                        .and_then(|v| v.as_str())
1079                        .unwrap_or("unknown"),
1080                ),
1081                window_type: sanitize_window_label(name),
1082                utilization: w.get("utilization").and_then(serde_json::Value::as_f64),
1083                resets_at: w.get("resetsAt").and_then(serde_json::Value::as_i64),
1084            });
1085        }
1086    }
1087    windows
1088}
1089
1090/// Concatenate text content from all `type:assistant` NDJSON messages in
1091/// the stream.  Used as a fallback when the `type:result` envelope text
1092/// does not contain valid AgentResponse JSON but an earlier assistant turn
1093/// might have emitted it.
1094pub fn collect_assistant_messages_text(ndjson: &str) -> String {
1095    let mut parts: Vec<String> = Vec::new();
1096    for line in ndjson.trim().lines() {
1097        let line = line.trim();
1098        if line.is_empty() {
1099            continue;
1100        }
1101        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
1102            continue;
1103        };
1104        if val.get("type").and_then(|v| v.as_str()) != Some("assistant") {
1105            continue;
1106        }
1107        if let Some(content) = val
1108            .get("message")
1109            .and_then(|m| m.get("content"))
1110            .and_then(|c| c.as_array())
1111        {
1112            for item in content {
1113                if item.get("type").and_then(|v| v.as_str()) == Some("text")
1114                    && let Some(text) = item.get("text").and_then(|v| v.as_str())
1115                {
1116                    let t = text.trim();
1117                    if !t.is_empty() {
1118                        parts.push(t.to_string());
1119                    }
1120                }
1121            }
1122        }
1123    }
1124    parts.join("\n")
1125}
1126
1127/// Claude `stream-json`: calls and text are blocks in `assistant` messages, results in `user` ones
1128pub(crate) fn stream_events(v: &serde_json::Value) -> Vec<StreamEvent> {
1129    let blocks = || v["message"]["content"].as_array().into_iter().flatten();
1130    match json_str(v, "/type") {
1131        "system" if json_str(v, "/subtype") == "init" => vec![StreamEvent::Started {
1132            model: json_str(v, "/model").to_string(),
1133        }],
1134        "assistant" => blocks()
1135            .filter_map(|b| match json_str(b, "/type") {
1136                "text" => Some(StreamEvent::Text(json_str(b, "/text").to_string())),
1137                "thinking" => Some(StreamEvent::Thinking(json_str(b, "/thinking").to_string())),
1138                "tool_use" => Some(StreamEvent::ToolCall {
1139                    id: json_str(b, "/id").to_string(),
1140                    name: json_str(b, "/name").to_string(),
1141                    input: b["input"].clone(),
1142                }),
1143                _ => None,
1144            })
1145            .collect(),
1146        "user" => blocks()
1147            .filter(|b| json_str(b, "/type") == "tool_result")
1148            .map(|b| StreamEvent::ToolResult {
1149                id: json_str(b, "/tool_use_id").to_string(),
1150                name: String::new(),
1151                output: match &b["content"] {
1152                    serde_json::Value::String(s) => s.clone(),
1153                    serde_json::Value::Array(parts) => parts
1154                        .iter()
1155                        .filter_map(|p| p["text"].as_str())
1156                        .collect::<Vec<_>>()
1157                        .join("\n"),
1158                    _ => String::new(),
1159                },
1160                is_error: b["is_error"].as_bool() == Some(true),
1161            })
1162            .collect(),
1163        "error" => vec![StreamEvent::Error(json_error_message(v))],
1164        "result" => {
1165            let failed = v["is_error"].as_bool() == Some(true)
1166                || json_str(v, "/subtype").starts_with("error");
1167            if failed {
1168                return vec![StreamEvent::Error(json_str(v, "/result").to_string())];
1169            }
1170
1171            let turns = v["num_turns"].as_u64().unwrap_or(0);
1172            let secs = v["duration_ms"].as_u64().unwrap_or(0) / 1000;
1173            let time = if secs >= 60 {
1174                format!("{}m {}s", secs / 60, secs % 60)
1175            } else {
1176                format!("{secs}s")
1177            };
1178            vec![StreamEvent::Done(format!("{turns} turns · {time}"))]
1179        }
1180        _ => vec![],
1181    }
1182}
1183
1184#[cfg(test)]
1185mod tests;
1186
1187#[cfg(test)]
1188mod stream_tests;