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-file "{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 = 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            format!(
444                "--restricted --strict-mcp-config --tools '{}' \\\n  ",
445                kinds.join(",")
446            )
447        } else {
448            String::new()
449        };
450
451        format!(
452            r#"{timeout_cmd} {binary} -p --verbose {model_flag}{effort_flag} \
453  --permission-mode {permission_mode} \
454  --output-format stream-json \
455  {restrict_flag}{tool_flag} \
456  --append-system-prompt-file "{sys_file}" \
457  < "{msg_file}""#,
458            timeout_cmd = timeout_cmd,
459            binary = self.binary,
460            model_flag = model_flag,
461            permission_mode = permission_mode,
462            tool_flag = tool_flag,
463            sys_file = sys_file,
464            msg_file = msg_file,
465        )
466    }
467
468    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError> {
469        let trimmed = raw.trim();
470        if trimmed.is_empty() {
471            return Err(AgentError::InvalidResponse { raw: String::new() });
472        }
473
474        // For NDJSON (--output-format stream-json): find the best result line and its
475        // token count. For single-line JSON (--output-format json), returns None.
476        if let Some((result_line, tokens)) = find_ndjson_result_line(trimmed) {
477            let result = Self::parse_envelope(result_line)?;
478            // If the envelope parse preserved meaningful tokens, use those.
479            // Otherwise, fall back to the tokens from find_ndjson_result_line
480            // (which selected the best result line by token count — issue #1387).
481            let input_tokens = result.input_tokens.or(tokens.map(|(i, _)| i));
482            let output_tokens = result.output_tokens.or(tokens.map(|(_, o)| o));
483            if input_tokens != result.input_tokens || output_tokens != result.output_tokens {
484                return Ok(ParsedResponse {
485                    input_tokens,
486                    output_tokens,
487                    ..result
488                });
489            }
490            return Ok(result);
491        }
492
493        // Fallback: treat the whole string as the envelope (e.g. pretty-printed JSON)
494        Self::parse_envelope(trimmed)
495    }
496
497    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError {
498        // For claude-protocol agents the real error string lives in the `result`
499        // field of the NDJSON result line (when is_error=true). Prepend it to the
500        // combined text so the classifier sees it before the raw metadata tail.
501        let error_result: Option<String> = (|| {
502            let trimmed = stdout.trim();
503            let (line, _) = find_ndjson_result_line(trimmed)?;
504            let val: serde_json::Value = serde_json::from_str(line).ok()?;
505            let obj = val.as_object()?;
506            if obj.get("is_error").and_then(serde_json::Value::as_bool) != Some(true) {
507                return None;
508            }
509            Some(envelope_error_text(obj)).filter(|t| !t.is_empty())
510        })();
511
512        // Also check for system-level error events (e.g., session limit mid-stream).
513        // These appear as `type:system` NDJSON events with an error object, not as
514        // `type:result` lines with `is_error:true`. This catches errors like session
515        // limits, credential issues, and API errors that interrupt the agent mid-run.
516        //
517        // Example:
518        //   {"type":"system","subtype":"error","error":{"type":"session_limit","message":"..."}}
519        let system_error: Option<String> = (|| {
520            let trimmed = stdout.trim();
521            for line in trimmed.lines() {
522                let line = line.trim();
523                if line.is_empty() {
524                    continue;
525                }
526                if let Ok(val) = serde_json::from_str::<serde_json::Value>(line)
527                    && let Some(obj) = val.as_object()
528                    && obj.get("type").and_then(|t| t.as_str()) == Some("system")
529                    && let Some(error) = obj.get("error")
530                    && let Some(msg) = error.get("message").and_then(|m| m.as_str())
531                {
532                    return Some(msg.to_string());
533                }
534            }
535            None
536        })();
537
538        // A kill signal (SIGTERM or SIGKILL) with no result envelope and no error event
539        // is an interrupted run, not a provider failure, so skip the text scan
540        let has_result_line = find_ndjson_result_line(stdout.trim()).is_some();
541        if matches!(exit_code, 143 | 137)
542            && !has_result_line
543            && error_result.is_none()
544            && system_error.is_none()
545        {
546            return AgentError::Interrupted {
547                message: format!("agent killed by signal (exit {exit_code})"),
548            };
549        }
550
551        let combined = match (&error_result, &system_error) {
552            (Some(r), Some(s)) => format!("{s}\n{r}\n{stdout}\n{stderr}"),
553            (Some(r), None) => format!("{r}\n{stdout}\n{stderr}"),
554            (None, Some(s)) => format!("{s}\n{stdout}\n{stderr}"),
555            (None, None) => format!("{stdout}\n{stderr}"),
556        };
557        // Envelope billing text is prepended into the same 3000-byte head as hook
558        // UUIDs, so classify the envelope before the combined scan
559        if let Some(message) = &error_result
560            && let Some(e) = super::patterns::detect_auth_error(message)
561        {
562            return e;
563        }
564        let classified = super::patterns::classify_from_text(exit_code, &combined);
565
566        // `classify_from_text`'s generic catch-all truncates to the last 300
567        // bytes of the combined text, which can cut a perfectly well-formed
568        // `error_result` line off mid-field-name (e.g. `is_error` becomes
569        // `i_error`) once enough NDJSON precedes it (issue #3577). When we
570        // already extracted a clean, complete error message from the result
571        // envelope but none of the specific pattern detectors matched it,
572        // prefer that clean message over the byte-truncated fallback.
573        if let (AgentError::Unknown { .. }, Some(message)) = (&classified, &error_result)
574            && !message.is_empty()
575        {
576            return AgentError::AgentFailed {
577                message: message.clone(),
578            };
579        }
580        classified
581    }
582
583    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command> {
584        let mut cmd = Command::new(&self.binary);
585        cmd.env_remove("CLAUDECODE"); // allow nested invocation
586        cmd.arg("--output-format")
587            .arg("stream-json")
588            .arg("--verbose")
589            .arg("--print");
590        if let Some(m) = model.map(str::trim).filter(|m| !m.is_empty()) {
591            cmd.arg("--model").arg(m);
592        }
593        cmd.arg(prompt);
594        Ok(cmd)
595    }
596}
597
598/// Known Claude Code native tool names.
599/// These are passed as-is to `--allowedTools`.
600const CLAUDE_NATIVE_TOOLS: &[&str] = &[
601    "Edit",
602    "Write",
603    "Read",
604    "Bash",
605    "Grep",
606    "Glob",
607    "WebFetch",
608    "WebSearch",
609    "Task",
610    "Skill",
611    "NotebookEdit",
612    "EnterPlanMode",
613    "ExitPlanMode",
614    "EnterWorktree",
615    "AskUserQuestion",
616    "TodoWrite",
617    "TodoRead",
618];
619
620/// Translate a unified allowed_tools list into Claude `--allowedTools` patterns.
621///
622/// - Items matching known Claude tool names pass through as-is
623/// - Edit/Write are scoped to `allowed_edit_paths` when set
624/// - Other items are treated as CLI commands and become `Bash(<cmd> *)` patterns
625fn translate_allowed_tools(allowed: &[String], allowed_edit_paths: &[PathBuf]) -> Vec<String> {
626    let mut tools = Vec::new();
627    for item in allowed {
628        if (item == "Edit" || item == "Write") && !allowed_edit_paths.is_empty() {
629            // Scope Edit/Write to allowed paths only
630            for path in allowed_edit_paths {
631                tools.push(format!("{}({}/*)", item, path.display()));
632            }
633        } else if CLAUDE_NATIVE_TOOLS.contains(&item.as_str()) || item.starts_with("Bash(") {
634            tools.push(item.clone());
635        } else {
636            // CLI command → Bash(<cmd> *) pattern
637            tools.push(format!("Bash({item} *)"));
638        }
639    }
640    tools
641}
642
643/// Find the best NDJSON result line and its token usage.
644///
645/// Returns `(line, tokens)` where `tokens` is `Some((input, output))` or `None`
646/// if no usage data was found.
647///
648/// Selection priority:
649/// 1. JSON result fields (object/array or string that parses as JSON) — always preferred
650/// 2. Among plain-text results: the one with the most total tokens (preferring actual
651///    work over outer-session confirmation summaries)
652/// 3. Error results (is_error=true) — included even with no tokens, so the caller can
653///    classify them properly
654///
655/// This skips outer-session plain-text summaries in favor of inner task results
656/// with meaningful token counts (issue #1387).
657pub(crate) fn find_ndjson_result_line(text: &str) -> Option<(&str, Option<(u64, u64)>)> {
658    let lines: Vec<_> = text.lines().filter(|l| !l.trim().is_empty()).collect();
659
660    // Pass 1: find a result line with a JSON result field.
661    // JSON results are always preferred (inner task delegate output).
662    for line in lines.iter().rev() {
663        if let Ok(val) = serde_json::from_str::<serde_json::Value>(line)
664            && let Some(obj) = val.as_object()
665            && obj.get("type").and_then(|t| t.as_str()) == Some("result")
666            && let Some(result) = obj.get("result")
667        {
668            let is_json_result = match result {
669                serde_json::Value::Object(_) | serde_json::Value::Array(_) => true,
670                serde_json::Value::String(s) => {
671                    serde_json::from_str::<serde_json::Value>(s).is_ok()
672                }
673                _ => false,
674            };
675            if is_json_result {
676                let tokens = extract_result_tokens(obj);
677                return Some((line, tokens));
678            }
679        }
680    }
681
682    // Pass 2: no JSON result found — choose the plain-text result with the most tokens.
683    // This handles outer-session confirmation summaries (e.g. "Already retrieved the result")
684    // vs. actual work summaries: prefer the one with more tokens.
685    // Error results (is_error=true) are included even with zero tokens, so the caller
686    // can classify them properly.
687    let mut best_line: Option<&str> = None;
688    let mut best_total = 0u64;
689
690    for line in &lines {
691        if let Ok(val) = serde_json::from_str::<serde_json::Value>(line)
692            && let Some(obj) = val.as_object()
693            && obj.get("type").and_then(|t| t.as_str()) == Some("result")
694        {
695            let tokens = extract_result_tokens(obj);
696            let total = tokens.map_or(0, |(i, o)| i.saturating_add(o));
697            if total >= best_total {
698                best_total = total;
699                best_line = Some(*line);
700            }
701        }
702    }
703
704    best_line.map(|line| (line, extract_result_tokens_from_line(line)))
705}
706
707/// Extract input/output token counts from a parsed result envelope object.
708fn extract_result_tokens(obj: &serde_json::Map<String, serde_json::Value>) -> Option<(u64, u64)> {
709    // Try top-level `usage` first.
710    if let Some(usage) = obj.get("usage").and_then(|v| v.as_object()) {
711        let input = usage
712            .get("input_tokens")
713            .and_then(serde_json::Value::as_u64);
714        let output = usage
715            .get("output_tokens")
716            .and_then(serde_json::Value::as_u64);
717        if let (Some(i), Some(o)) = (input, output) {
718            return Some((i, o));
719        }
720    }
721    // Try modelUsage (aggregated across models).
722    if let Some(model_usage) = obj.get("modelUsage").and_then(|v| v.as_object()) {
723        let mut total_input = 0u64;
724        let mut total_output = 0u64;
725        let mut found = false;
726        for (_model_name, model_stats) in model_usage {
727            if let Some(stats) = model_stats.as_object() {
728                if let Some(i) = stats
729                    .get("inputTokens")
730                    .or_else(|| stats.get("input_tokens"))
731                    .and_then(serde_json::Value::as_u64)
732                {
733                    total_input += i;
734                    found = true;
735                }
736                if let Some(o) = stats
737                    .get("outputTokens")
738                    .or_else(|| stats.get("output_tokens"))
739                    .and_then(serde_json::Value::as_u64)
740                {
741                    total_output += o;
742                    found = true;
743                }
744            }
745        }
746        if found {
747            return Some((total_input, total_output));
748        }
749    }
750    None
751}
752
753/// Extract token counts from a raw NDJSON result line string.
754fn extract_result_tokens_from_line(line: &str) -> Option<(u64, u64)> {
755    let val = serde_json::from_str::<serde_json::Value>(line).ok()?;
756    let obj = val.as_object()?;
757    extract_result_tokens(obj)
758}
759
760/// The run cost the envelope reports. Claude Code names it `total_cost_usd`, older builds used
761/// `costUSD` or `cost_usd`.
762fn envelope_cost(envelope: &serde_json::Map<String, serde_json::Value>) -> Option<f64> {
763    envelope
764        .get("total_cost_usd")
765        .or_else(|| envelope.get("costUSD"))
766        .or_else(|| envelope.get("cost_usd"))
767        .and_then(serde_json::Value::as_f64)
768}
769
770/// Extract input/output tokens from the Claude envelope's usage objects.
771fn extract_usage(
772    envelope: &serde_json::Map<String, serde_json::Value>,
773) -> (Option<u64>, Option<u64>) {
774    // Try top-level `usage` first
775    if let Some(usage) = envelope.get("usage").and_then(|v| v.as_object()) {
776        let input = usage
777            .get("input_tokens")
778            .and_then(serde_json::Value::as_u64);
779        let output = usage
780            .get("output_tokens")
781            .and_then(serde_json::Value::as_u64);
782        if input.is_some() || output.is_some() {
783            return (input, output);
784        }
785    }
786
787    // Try modelUsage (aggregated across models)
788    if let Some(model_usage) = envelope.get("modelUsage").and_then(|v| v.as_object()) {
789        let mut total_input = 0u64;
790        let mut total_output = 0u64;
791        let mut found = false;
792
793        for (_model_name, model_stats) in model_usage {
794            if let Some(stats) = model_stats.as_object() {
795                if let Some(i) = stats
796                    .get("inputTokens")
797                    .or_else(|| stats.get("input_tokens"))
798                    .and_then(serde_json::Value::as_u64)
799                {
800                    total_input += i;
801                    found = true;
802                }
803                if let Some(o) = stats
804                    .get("outputTokens")
805                    .or_else(|| stats.get("output_tokens"))
806                    .and_then(serde_json::Value::as_u64)
807                {
808                    total_output += o;
809                    found = true;
810                }
811            }
812        }
813
814        if found {
815            return (Some(total_input), Some(total_output));
816        }
817    }
818
819    (None, None)
820}
821
822const SHOW_CURSOR: &str = "\x1b[?25h";
823const HIDE_CURSOR: &str = "\x1b[?25l";
824
825/// Drop `script` tty junk: show-cursor (`ESC[?25h`) and `^D`/backspace redraw lines
826pub fn strip_tty_control_lines(raw: &str) -> String {
827    raw.lines()
828        .filter(|line| !is_tty_control_line(line))
829        .map(strip_trailing_cursor)
830        .collect::<Vec<_>>()
831        .join("\n")
832}
833
834fn strip_trailing_cursor(line: &str) -> &str {
835    let mut s = line.trim_end();
836    loop {
837        if let Some(next) = s
838            .strip_suffix(SHOW_CURSOR)
839            .or_else(|| s.strip_suffix(HIDE_CURSOR))
840        {
841            s = next.trim_end();
842            continue;
843        }
844        return s;
845    }
846}
847
848fn is_tty_control_line(line: &str) -> bool {
849    let trimmed = strip_trailing_cursor(line).trim();
850    if trimmed.is_empty() {
851        return !line.trim().is_empty();
852    }
853    trimmed.chars().all(|c| matches!(c, '^' | 'D' | '\u{0008}'))
854}
855
856/// Type of the last content block on the last assistant NDJSON message
857fn last_assistant_content_type(ndjson: &str) -> Option<String> {
858    let mut last = None;
859    for line in ndjson.lines() {
860        let line = line.trim();
861        if line.is_empty() {
862            continue;
863        }
864        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
865            continue;
866        };
867        if val.get("type").and_then(|v| v.as_str()) != Some("assistant") {
868            continue;
869        }
870        let Some(content) = val
871            .get("message")
872            .and_then(|m| m.get("content"))
873            .and_then(|c| c.as_array())
874        else {
875            continue;
876        };
877        if let Some(item) = content.last()
878            && let Some(t) = item.get("type").and_then(|v| v.as_str())
879        {
880            last = Some(t.to_string());
881        }
882    }
883    last
884}
885
886/// True when the stream has no result envelope and ended on a thinking block
887/// or a tool call, so the model never produced a finished review decision
888pub fn review_session_exited_mid_thought(ndjson: &str) -> bool {
889    if find_ndjson_result_line(ndjson).is_some() {
890        return false;
891    }
892    matches!(
893        last_assistant_content_type(ndjson).as_deref(),
894        Some("thinking" | "redacted_thinking" | "tool_use")
895    )
896}
897
898/// Extract a structured `AgentResult` from Claude/Kimi/MiniMax NDJSON output.
899///
900/// Finds the last `"type":"result"` line whose `result` field contains valid JSON.
901/// This skips outer-session plain-text summaries (issue #1387) and finds the
902/// actual task-delegate result with structured JSON.
903///
904/// Extracts:
905/// - `result` text (the inner content)
906/// - `is_error` flag
907/// - token usage from `usage` or `modelUsage`
908/// - `duration_ms`
909///
910/// If no JSON result line exists (common with MiniMax), falls back to
911/// extracting the last assistant text message from the stream.
912///
913/// Returns `None` only if the input contains no recognizable NDJSON events.
914pub fn find_claude_result(ndjson: &str) -> Option<super::AgentResult> {
915    let stripped = strip_tty_control_lines(ndjson);
916    let trimmed = stripped.trim();
917    if trimmed.is_empty() {
918        return None;
919    }
920
921    // Try to find the result envelope first
922    if let Some((result_line, _tokens)) = find_ndjson_result_line(trimmed)
923        && let Ok(parsed) = serde_json::from_str::<serde_json::Value>(result_line)
924        && let Some(envelope) = parsed.as_object()
925    {
926        let is_error = envelope
927            .get("is_error")
928            .and_then(serde_json::Value::as_bool)
929            .unwrap_or(false);
930
931        let result_text = if is_error {
932            // Error envelopes put the real message in errors[] (billing,
933            // rate limits) with `result` empty — don't lose it (issue #3713)
934            envelope_error_text(envelope)
935        } else {
936            envelope
937                .get("result")
938                .and_then(|v| v.as_str())
939                .unwrap_or("")
940                .to_string()
941        };
942
943        let (input_tokens, output_tokens) = extract_usage(envelope);
944        let duration_ms = envelope
945            .get("duration_ms")
946            .and_then(serde_json::Value::as_u64);
947
948        let cost_usd = envelope_cost(envelope);
949
950        return Some(super::AgentResult {
951            is_error,
952            result_text,
953            input_tokens,
954            output_tokens,
955            cost_usd,
956            duration_ms,
957            truncated_by_length: false,
958        });
959    }
960
961    // Fallback for MiniMax/Kimi: extract last assistant text message
962    let mut last_text = None;
963    let mut input_tokens = None;
964    let mut output_tokens = None;
965
966    for line in trimmed.lines() {
967        let line = line.trim();
968        if line.is_empty() {
969            continue;
970        }
971        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
972            continue;
973        };
974        if val.get("type").and_then(|v| v.as_str()) != Some("assistant") {
975            continue;
976        }
977        // Extract text from content array
978        if let Some(content) = val
979            .get("message")
980            .and_then(|m| m.get("content"))
981            .and_then(|c| c.as_array())
982        {
983            for item in content {
984                if item.get("type").and_then(|v| v.as_str()) == Some("text")
985                    && let Some(text) = item.get("text").and_then(|v| v.as_str())
986                {
987                    let t = text.trim();
988                    if !t.is_empty() {
989                        last_text = Some(t.to_string());
990                    }
991                }
992            }
993        }
994        // Extract usage (take max, as Claude reports cumulative)
995        if let Some(usage) = val.get("message").and_then(|m| m.get("usage")) {
996            if let Some(inp) = usage
997                .get("input_tokens")
998                .and_then(serde_json::Value::as_u64)
999            {
1000                input_tokens = Some(input_tokens.unwrap_or(0u64).max(inp));
1001            }
1002            if let Some(out) = usage
1003                .get("output_tokens")
1004                .and_then(serde_json::Value::as_u64)
1005            {
1006                output_tokens = Some(output_tokens.unwrap_or(0u64).max(out));
1007            }
1008        }
1009    }
1010
1011    last_text.map(|text| super::AgentResult {
1012        is_error: false,
1013        result_text: text,
1014        input_tokens,
1015        output_tokens,
1016        cost_usd: None,
1017        duration_ms: None,
1018        truncated_by_length: false,
1019    })
1020}
1021
1022/// Keep a vendor label printable: letters, digits, `_` and `-`, at most 32 characters
1023fn sanitize_window_label(raw: &str) -> String {
1024    raw.chars()
1025        .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))
1026        .take(32)
1027        .collect()
1028}
1029
1030/// Every window of every `rate_limit_event`, oldest first. The event status belongs to the headline
1031/// window, the other `unifiedWindows` entries use their own status or `unknown`
1032pub fn rate_limit_windows(ndjson: &str) -> Vec<RateLimitWindow> {
1033    let mut windows = Vec::new();
1034    for line in ndjson
1035        .lines()
1036        .filter(|line| line.contains("rate_limit_event"))
1037    {
1038        let Ok(val) = serde_json::from_str::<serde_json::Value>(line.trim()) else {
1039            continue;
1040        };
1041        if val.get("type").and_then(|v| v.as_str()) != Some("rate_limit_event") {
1042            continue;
1043        }
1044        let Some(info) = val.get("rate_limit_info") else {
1045            continue;
1046        };
1047        let Some(status) = info.get("status").and_then(|v| v.as_str()) else {
1048            continue;
1049        };
1050        let unified = info.get("unifiedWindows").and_then(|v| v.as_object());
1051        let headline_raw = info
1052            .get("rateLimitType")
1053            .and_then(|v| v.as_str())
1054            .unwrap_or("unknown");
1055        let headline = unified.and_then(|map| map.get(headline_raw));
1056        windows.push(RateLimitWindow {
1057            status: sanitize_window_label(status),
1058            window_type: sanitize_window_label(headline_raw),
1059            utilization: headline
1060                .and_then(|w| w.get("utilization"))
1061                .or_else(|| info.get("utilization"))
1062                .and_then(serde_json::Value::as_f64),
1063            resets_at: info
1064                .get("resetsAt")
1065                .or_else(|| headline.and_then(|w| w.get("resetsAt")))
1066                .and_then(serde_json::Value::as_i64),
1067        });
1068        for (name, w) in unified.into_iter().flatten() {
1069            if name == headline_raw {
1070                continue;
1071            }
1072            windows.push(RateLimitWindow {
1073                status: sanitize_window_label(
1074                    w.get("status")
1075                        .and_then(|v| v.as_str())
1076                        .unwrap_or("unknown"),
1077                ),
1078                window_type: sanitize_window_label(name),
1079                utilization: w.get("utilization").and_then(serde_json::Value::as_f64),
1080                resets_at: w.get("resetsAt").and_then(serde_json::Value::as_i64),
1081            });
1082        }
1083    }
1084    windows
1085}
1086
1087/// Concatenate text content from all `type:assistant` NDJSON messages in
1088/// the stream.  Used as a fallback when the `type:result` envelope text
1089/// does not contain valid AgentResponse JSON but an earlier assistant turn
1090/// might have emitted it.
1091pub fn collect_assistant_messages_text(ndjson: &str) -> String {
1092    let mut parts: Vec<String> = Vec::new();
1093    for line in ndjson.trim().lines() {
1094        let line = line.trim();
1095        if line.is_empty() {
1096            continue;
1097        }
1098        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
1099            continue;
1100        };
1101        if val.get("type").and_then(|v| v.as_str()) != Some("assistant") {
1102            continue;
1103        }
1104        if let Some(content) = val
1105            .get("message")
1106            .and_then(|m| m.get("content"))
1107            .and_then(|c| c.as_array())
1108        {
1109            for item in content {
1110                if item.get("type").and_then(|v| v.as_str()) == Some("text")
1111                    && let Some(text) = item.get("text").and_then(|v| v.as_str())
1112                {
1113                    let t = text.trim();
1114                    if !t.is_empty() {
1115                        parts.push(t.to_string());
1116                    }
1117                }
1118            }
1119        }
1120    }
1121    parts.join("\n")
1122}
1123
1124/// Claude `stream-json`: calls and text are blocks in `assistant` messages, results in `user` ones
1125pub(crate) fn stream_events(v: &serde_json::Value) -> Vec<StreamEvent> {
1126    let blocks = || v["message"]["content"].as_array().into_iter().flatten();
1127    match json_str(v, "/type") {
1128        "system" if json_str(v, "/subtype") == "init" => vec![StreamEvent::Started {
1129            model: json_str(v, "/model").to_string(),
1130        }],
1131        "assistant" => blocks()
1132            .filter_map(|b| match json_str(b, "/type") {
1133                "text" => Some(StreamEvent::Text(json_str(b, "/text").to_string())),
1134                "thinking" => Some(StreamEvent::Thinking(json_str(b, "/thinking").to_string())),
1135                "tool_use" => Some(StreamEvent::ToolCall {
1136                    id: json_str(b, "/id").to_string(),
1137                    name: json_str(b, "/name").to_string(),
1138                    input: b["input"].clone(),
1139                }),
1140                _ => None,
1141            })
1142            .collect(),
1143        "user" => blocks()
1144            .filter(|b| json_str(b, "/type") == "tool_result")
1145            .map(|b| StreamEvent::ToolResult {
1146                id: json_str(b, "/tool_use_id").to_string(),
1147                name: String::new(),
1148                output: match &b["content"] {
1149                    serde_json::Value::String(s) => s.clone(),
1150                    serde_json::Value::Array(parts) => parts
1151                        .iter()
1152                        .filter_map(|p| p["text"].as_str())
1153                        .collect::<Vec<_>>()
1154                        .join("\n"),
1155                    _ => String::new(),
1156                },
1157                is_error: b["is_error"].as_bool() == Some(true),
1158            })
1159            .collect(),
1160        "error" => vec![StreamEvent::Error(json_error_message(v))],
1161        "result" => {
1162            let failed = v["is_error"].as_bool() == Some(true)
1163                || json_str(v, "/subtype").starts_with("error");
1164            if failed {
1165                return vec![StreamEvent::Error(json_str(v, "/result").to_string())];
1166            }
1167
1168            let turns = v["num_turns"].as_u64().unwrap_or(0);
1169            let secs = v["duration_ms"].as_u64().unwrap_or(0) / 1000;
1170            let time = if secs >= 60 {
1171                format!("{}m {}s", secs / 60, secs % 60)
1172            } else {
1173                format!("{secs}s")
1174            };
1175            vec![StreamEvent::Done(format!("{turns} turns · {time}"))]
1176        }
1177        _ => vec![],
1178    }
1179}
1180
1181#[cfg(test)]
1182mod tests;
1183
1184#[cfg(test)]
1185mod stream_tests;