Skip to main content

orch/engine/runner/agents/
mod.rs

1//! Per-agent runner trait, error types, and agent registry.
2//!
3//! Each agent (Claude, Codex, OpenCode, Grok) has a different CLI invocation,
4//! output format, and error pattern. This module defines a common trait
5//! so the runner can delegate parsing and error classification to the
6//! correct implementation.
7
8#[macro_use]
9mod delegate;
10
11#[cfg(test)]
12pub(crate) mod fixture;
13/// Shared error pattern detection utilities used by multiple agent runners.
14pub(crate) mod patterns;
15
16pub mod claude;
17pub mod codex;
18pub mod grok;
19pub mod kimi;
20pub mod minimax;
21pub mod opencode;
22
23use crate::config;
24use crate::parser::AgentResponse;
25use std::collections::BTreeSet;
26use std::error;
27use std::fmt;
28use std::fmt::Display;
29use std::fmt::Formatter;
30use std::path::PathBuf;
31use std::time::Duration;
32use tokio::process::Command;
33
34/// Unified permission rules that each agent translates into its native flags.
35///
36/// Instead of hardcoding `--permission-mode bypassPermissions` for Claude and
37/// `--sandbox workspace-write` for Codex, we define a single set of rules and
38/// let each `AgentRunner` format them for its CLI.
39#[derive(Debug, Clone)]
40pub struct PermissionRules {
41    /// Whether the agent runs fully autonomous (no user prompts).
42    pub autonomous: bool,
43    /// Sandbox level for filesystem access.
44    pub sandbox: SandboxLevel,
45    /// Tool patterns to disallow (e.g., `["Bash(rm *)", "Bash(rm -*)"]`).
46    pub disallowed_tools: Vec<String>,
47    /// Tools to allow (whitelist). Overrides `disallowed_tools` when non-empty.
48    ///
49    /// Items are either agent-native tool names (e.g., "Edit", "Write", "Bash")
50    /// or CLI command names (e.g., "git", "npm") which get translated to
51    /// agent-specific patterns (e.g., `Bash(git*)` for Claude).
52    pub allowed_tools: Vec<String>,
53    /// Paths where the agent is allowed to edit files (worktree path).
54    /// When set, Edit/Write tools are scoped to these paths only.
55    /// Set dynamically per invocation (not from config).
56    pub allowed_edit_paths: Vec<PathBuf>,
57    /// Restrict to orchestration-only operations — denies Read, Glob, Grep,
58    /// and Bash commands for browsing/reading files (ls, cat, find, etc.).
59    /// Agents translate this into their native permission model.
60    pub deny_read_only: bool,
61    /// Additional directories that must be writable (e.g. the git common dir
62    /// when running inside a worktree whose `.git` metadata lives outside the
63    /// sandbox root). Codex translates these into `--add-dir` flags; other
64    /// agents ignore the field.
65    pub extra_writable_dirs: Vec<PathBuf>,
66}
67
68/// Sandbox level — how much filesystem access the agent gets.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum SandboxLevel {
71    /// Agent can only write within the workspace/worktree.
72    WorkspaceWrite,
73    /// Agent has full filesystem access (dangerous).
74    FullAccess,
75    /// No sandboxing (orch manages isolation externally).
76    None,
77    /// The OS sandbox runs the agent, so the agent's own sandbox is off
78    Os,
79    /// Reads only, and runs `allowed_tools` and nothing else, refused without a prompt. For a chat
80    /// whose context holds text anyone can write
81    ReadOnly,
82}
83
84impl Default for PermissionRules {
85    fn default() -> Self {
86        Self {
87            autonomous: true,
88            sandbox: SandboxLevel::WorkspaceWrite,
89            disallowed_tools: vec![
90                "Bash(rm *)".to_string(),
91                "Bash(rm -*)".to_string(),
92                "Bash(git push*)".to_string(),
93            ],
94            allowed_tools: vec![],
95            allowed_edit_paths: vec![],
96            deny_read_only: false,
97            extra_writable_dirs: vec![],
98        }
99    }
100}
101
102impl PermissionRules {
103    /// Load permission rules from config, falling back to defaults.
104    pub fn from_config() -> Self {
105        let mut rules = Self::default();
106
107        if let Ok(mode) = config::get("workflow.permissions.mode") {
108            rules.autonomous = mode != "supervised";
109        }
110
111        if let Ok(sandbox) = config::get("workflow.permissions.sandbox") {
112            rules.sandbox = match sandbox.as_str() {
113                "full-access" | "danger-full-access" => SandboxLevel::FullAccess,
114                "none" => SandboxLevel::None,
115                _ => SandboxLevel::WorkspaceWrite,
116            };
117        }
118
119        if let Ok(tools) = config::get("workflow.disallowed_tools") {
120            let parsed: Vec<String> = tools
121                .split(',')
122                .map(|s| s.trim().to_string())
123                .filter(|s| !s.is_empty())
124                .collect();
125            if !parsed.is_empty() {
126                rules.disallowed_tools = parsed;
127            }
128        }
129
130        if let Ok(tools) = config::get_list("workflow.allowed_tools") {
131            rules.allowed_tools = tools;
132        }
133
134        rules
135    }
136
137    /// Restriction preset for control sessions: denies Read, Glob, Grep, and
138    /// Bash commands that read files or list directories (ls, cat, find, etc.).
139    ///
140    /// The agent remains autonomous but is prevented from browsing or reading
141    /// arbitrary files on the host machine. Translation into agent-native flags
142    /// is handled by each `AgentRunner::build_command()` implementation.
143    /// A chat that may read and run `allowed`, and is refused everything else
144    pub fn read_only(allowed: Vec<String>) -> Self {
145        Self {
146            autonomous: false,
147            sandbox: SandboxLevel::ReadOnly,
148            disallowed_tools: vec![],
149            allowed_tools: allowed,
150            allowed_edit_paths: vec![],
151            deny_read_only: false,
152            extra_writable_dirs: vec![],
153        }
154    }
155
156    pub fn deny_read_only() -> Self {
157        Self {
158            autonomous: true,
159            sandbox: SandboxLevel::WorkspaceWrite,
160            disallowed_tools: vec![
161                "Bash(rm *)".to_string(),
162                "Bash(rm -*)".to_string(),
163                "Bash(git push*)".to_string(),
164                "Bash(ls *)".to_string(),
165                "Bash(ls)".to_string(),
166                "Bash(find *)".to_string(),
167                "Bash(cat *)".to_string(),
168                "Bash(head *)".to_string(),
169                "Bash(tail *)".to_string(),
170                "Bash(fzf *)".to_string(),
171                "Bash(less *)".to_string(),
172                "Bash(more *)".to_string(),
173                "Read".to_string(),
174                "Glob".to_string(),
175                "Grep".to_string(),
176            ],
177            allowed_tools: vec![],
178            allowed_edit_paths: vec![],
179            deny_read_only: true,
180            extra_writable_dirs: vec![],
181        }
182    }
183}
184
185/// Structured result from per-agent NDJSON extraction.
186///
187/// Each agent emits a different NDJSON format. The per-agent `find_result`
188/// functions parse agent-specific envelopes and return a unified `AgentResult`
189/// so callers (review pipeline, response handler) don't need format knowledge.
190#[derive(Debug, Clone)]
191pub struct AgentResult {
192    /// Whether the agent reported an error (e.g. `is_error: true` in Claude).
193    pub is_error: bool,
194    /// The extracted result text (inner content, stripped of envelope).
195    pub result_text: String,
196    /// Input tokens consumed (if reported by the agent).
197    pub input_tokens: Option<u64>,
198    /// Output tokens consumed (if reported by the agent).
199    pub output_tokens: Option<u64>,
200    /// Total cost in USD (if reported by the agent).
201    pub cost_usd: Option<f64>,
202    /// Wall-clock duration in milliseconds (if reported by the agent).
203    pub duration_ms: Option<u64>,
204    /// True when the provider cut the response short by exceeding its
205    /// output/reasoning token budget (e.g. opencode's `step_finish` event
206    /// reporting `reason: "length"`), as opposed to producing malformed
207    /// output. Callers use this to distinguish a token-budget fluke from a
208    /// genuinely format-incapable model.
209    pub truncated_by_length: bool,
210}
211
212/// Concatenate text from all assistant-turn messages in the agent's NDJSON
213/// output stream.  Used as an intermediate fallback when the `type:result`
214/// envelope text is not valid AgentResponse JSON but an earlier assistant
215/// message in the conversation might contain it.
216pub fn collect_assistant_messages_text(_agent: &str, ndjson: &str) -> String {
217    claude::collect_assistant_messages_text(ndjson)
218}
219
220/// Dispatch to the appropriate per-agent result extractor.
221///
222/// Returns `None` if no structured result could be found in the output
223/// (e.g. plain text, empty output, or unrecognized format).
224pub fn find_agent_result(agent: &str, ndjson: &str) -> Option<AgentResult> {
225    match agent {
226        "grok" => grok::find_grok_result(ndjson),
227        "opencode" => opencode::find_opencode_result(ndjson),
228        "codex" => codex::find_codex_result(ndjson),
229        // claude, kimi, minimax and unknown agents all emit the claude format
230        _ => claude::find_claude_result(ndjson),
231    }
232}
233
234/// Parsed response from an agent, including metadata extracted from the
235/// agent-specific output envelope.
236#[derive(Debug, Clone)]
237pub struct ParsedResponse {
238    /// Normalized task response (status, summary, accomplished, etc.)
239    pub response: AgentResponse,
240    /// Input tokens consumed (if reported by the agent).
241    pub input_tokens: Option<u64>,
242    /// Output tokens consumed (if reported by the agent).
243    pub output_tokens: Option<u64>,
244    /// Cost in USD of this run, as the agent reported it.
245    pub cost_usd: Option<f64>,
246    /// Wall-clock duration in milliseconds (if reported by the agent).
247    pub duration_ms: Option<u64>,
248}
249
250/// Agent-specific error with enough detail for autonomous recovery.
251#[derive(Debug, Clone)]
252pub enum AgentError {
253    /// Rate/usage limit — reroute to different agent, cooldown current.
254    RateLimit { message: String },
255    /// Auth/billing/API key error — switch agent entirely.
256    Auth { message: String },
257    /// Requested model not available — try different model, then switch agent.
258    ModelUnavailable { message: String, model: String },
259    /// Context window exceeded — truncate and retry, then switch agent.
260    ContextOverflow { message: String },
261    /// Agent hit the task time limit. Retry without cooling the model
262    Timeout { elapsed: Duration },
263    /// Process exited with no result envelope, usually a kill rather than a model fault
264    Interrupted { message: String },
265    /// Required tool/binary missing from the environment.
266    MissingTool { tool: String },
267    /// Sandbox or filesystem permission denied.
268    PermissionDenied { message: String },
269    /// Agent is waiting for interactive input (e.g., 1Password, SSH).
270    WaitingForInput { message: String },
271    /// The agent's session ID is no longer valid (session expired or was cleared).
272    ///
273    /// Returned when Claude reports "No conversation found with session ID: <uuid>".
274    /// The caller should reset the stored UUID and retry with a fresh `--session-id`.
275    StaleSession { session_id: String },
276    /// Agent returned unparseable output.
277    InvalidResponse { raw: String },
278    /// Agent self-reported a failure in its response.
279    AgentFailed { message: String },
280    /// Transient network connectivity error — retry same agent, no failover.
281    NetworkError { message: String },
282    /// Thinking blocks cannot be modified (Claude extended-thinking + tool-use 400).
283    ///
284    /// Transient API incompatibility inside the Claude CLI's multi-turn tool-use
285    /// loop — the Anthropic API rejects the request when thinking blocks are altered
286    /// between turns. Not a model capacity problem: does NOT increment failure counts
287    /// or apply cooldowns. The task is rerouted to a different agent.
288    ThinkingBlockConflict { message: String },
289    /// Unclassified error.
290    Unknown { exit_code: i32, message: String },
291}
292
293impl Display for AgentError {
294    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
295        match self {
296            Self::RateLimit { message, .. } => write!(f, "rate limit: {message}"),
297            Self::Auth { message } => write!(f, "auth error: {message}"),
298            Self::ModelUnavailable { message, model } => {
299                write!(f, "model unavailable ({model}): {message}")
300            }
301            Self::ContextOverflow { message, .. } => write!(f, "context overflow: {message}"),
302            Self::Timeout { elapsed } => write!(f, "timeout after {}s", elapsed.as_secs()),
303            Self::Interrupted { message } => write!(f, "interrupted: {message}"),
304            Self::MissingTool { tool } => write!(f, "missing tool: {tool}"),
305            Self::PermissionDenied { message } => write!(f, "permission denied: {message}"),
306            Self::WaitingForInput { message } => write!(f, "waiting for input: {message}"),
307            Self::StaleSession { session_id } => {
308                write!(f, "stale session (session expired): {session_id}")
309            }
310            Self::InvalidResponse { raw } => {
311                let end = truncate_at_char_boundary(raw, 200);
312                write!(f, "invalid response: {}", &raw[..end])
313            }
314            Self::AgentFailed { message } => write!(f, "agent failed: {message}"),
315            Self::NetworkError { message } => write!(f, "network error: {message}"),
316            Self::ThinkingBlockConflict { message } => {
317                write!(f, "thinking block conflict: {message}")
318            }
319            Self::Unknown { exit_code, message } => {
320                write!(f, "unknown error (exit {exit_code}): {message}")
321            }
322        }
323    }
324}
325
326impl error::Error for AgentError {}
327
328/// Return the variant name of an `AgentError` as a static string,
329/// for structured logging and `result.json` output.
330pub fn error_class_name(err: &AgentError) -> &'static str {
331    match err {
332        AgentError::RateLimit { .. } => "RateLimit",
333        AgentError::Auth { .. } => "Auth",
334        AgentError::ModelUnavailable { .. } => "ModelUnavailable",
335        AgentError::ContextOverflow { .. } => "ContextOverflow",
336        AgentError::Timeout { .. } => "Timeout",
337        AgentError::Interrupted { .. } => "Interrupted",
338        AgentError::MissingTool { .. } => "MissingTool",
339        AgentError::PermissionDenied { .. } => "PermissionDenied",
340        AgentError::WaitingForInput { .. } => "WaitingForInput",
341        AgentError::StaleSession { .. } => "StaleSession",
342        AgentError::InvalidResponse { .. } => "InvalidResponse",
343        AgentError::AgentFailed { .. } => "AgentFailed",
344        AgentError::NetworkError { .. } => "NetworkError",
345        AgentError::ThinkingBlockConflict { .. } => "ThinkingBlockConflict",
346        AgentError::Unknown { .. } => "Unknown",
347    }
348}
349
350/// Extract file paths from free-form text.
351///
352/// Matches common source file patterns like `src/foo/bar.rs`, `tests/x.py`,
353/// `path/to/file.ts`, etc. Deduplicates and returns them sorted.
354fn extract_file_paths(text: &str) -> Vec<String> {
355    // Match path-like tokens: optional leading slash or no slash, at least one
356    // directory segment or a plain filename, with a recognised extension.
357    let extensions = [
358        "rs", "py", "ts", "tsx", "js", "jsx", "go", "java", "c", "cpp", "h", "hpp", "rb", "sh",
359        "md", "toml", "yaml", "yml", "json", "sql", "html", "css", "swift", "kt",
360    ];
361    let mut found: BTreeSet<String> = BTreeSet::new();
362    for token in text.split_whitespace() {
363        // Strip surrounding punctuation (backticks, quotes, parens, commas).
364        // We intentionally do NOT strip '.' here because it is part of file extensions.
365        let token = token.trim_matches(|c: char| {
366            matches!(
367                c,
368                '`' | '\'' | '"' | '(' | ')' | '[' | ']' | ',' | ':' | ';'
369            )
370        });
371        // Strip a lone trailing dot that ends a sentence (e.g. "src/foo.rs.").
372        // Only strip if the result still has a recognised extension — this avoids
373        // accidentally stripping the final dot of "src/foo.rs" when there is none.
374        let token = if let Some(without) = token.strip_suffix('.') {
375            let still_has_ext = extensions
376                .iter()
377                .any(|ext| without.ends_with(&format!(".{ext}")));
378            if still_has_ext { without } else { token }
379        } else {
380            token
381        };
382        // Must contain at least one slash (directory separator) or look like a
383        // root-relative path, and end with a known extension.
384        let has_ext = extensions
385            .iter()
386            .any(|ext| token.ends_with(&format!(".{ext}")));
387        if !has_ext {
388            continue;
389        }
390        // Accept tokens with at least one path separator, or starting with a
391        // known top-level directory name common in Rust/JS/Python projects.
392        let path_like = token.contains('/')
393            || token.starts_with("src")
394            || token.starts_with("tests")
395            || token.starts_with("lib")
396            || token.starts_with("bin")
397            || token.starts_with("prompts")
398            || token.starts_with("migrations");
399        if path_like && token.len() >= 4 && !token.contains("://") {
400            found.insert(token.to_string());
401        }
402    }
403    found.into_iter().collect()
404}
405
406/// Split free-form text into accomplished and remaining bullet lists.
407///
408/// Lines under "remaining", "todo", "next steps", "still needed" headings are
409/// classified as `remaining`; all other bullet lines go into `accomplished`.
410fn extract_bullet_sections(text: &str) -> (Vec<String>, Vec<String>) {
411    let remaining_headers = [
412        "remaining",
413        "todo",
414        "to do",
415        "next steps",
416        "still needed",
417        "left to do",
418        "not done",
419        "outstanding",
420    ];
421
422    let mut accomplished: Vec<String> = vec![];
423    let mut remaining: Vec<String> = vec![];
424    let mut in_remaining_section = false;
425
426    for line in text.lines() {
427        let trimmed = line.trim();
428        if trimmed.is_empty() {
429            continue;
430        }
431        let lower = trimmed.to_lowercase();
432
433        // Detect section headings: only lines with explicit heading markers.
434        // Require trailing ':' or '#'-prefix to avoid misclassifying continuation
435        // lines (e.g. explanatory text after a bullet) as headings, which would
436        // incorrectly reset `in_remaining_section`.
437        let is_heading = trimmed.ends_with(':') || trimmed.starts_with('#');
438
439        if is_heading {
440            in_remaining_section = remaining_headers.iter().any(|h| lower.contains(h));
441            continue;
442        }
443
444        // Bullet lines: -, *, or numbered (1., 2.)
445        let is_bullet = trimmed.starts_with('-')
446            || trimmed.starts_with('*')
447            || trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains('.');
448
449        if !is_bullet {
450            continue;
451        }
452
453        // Strip leading bullet character(s).
454        let content = trimmed
455            .trim_start_matches(|c: char| c == '-' || c == '*' || c.is_ascii_digit() || c == '.')
456            .trim()
457            .to_string();
458
459        if content.is_empty() {
460            continue;
461        }
462
463        if in_remaining_section {
464            remaining.push(content);
465        } else {
466            accomplished.push(content);
467        }
468    }
469
470    (accomplished, remaining)
471}
472
473/// Detect if text is a CLI/arg-parser diagnostic rather than an agent response.
474/// CLI diagnostics indicate process startup failure, not an agent answer.
475fn is_cli_parser_diagnostic(text: &str) -> bool {
476    let lower = text.to_lowercase();
477
478    // Clap-style error messages
479    if lower.contains("error: unexpected argument") {
480        return true;
481    }
482
483    // Usage/help text patterns
484    if text.lines().any(|line| {
485        let trimmed = line.trim();
486        trimmed.starts_with("Usage:") || trimmed.starts_with("usage:")
487    }) {
488        return true;
489    }
490
491    // Clap help/info hints
492    if lower.contains("for more information, try '--help'") {
493        return true;
494    }
495
496    // Clap "tip" messages about passing values
497    if lower.contains("tip: to pass '") {
498        return true;
499    }
500
501    false
502}
503
504/// Detect whether `text` looks like an NDJSON event stream emitted by an
505/// agent CLI (opencode/claude/codex). Returns true when the first non-empty
506/// line parses as a JSON object containing a `type` field with one of the
507/// known event-type strings.
508///
509/// This guard prevents raw NDJSON from being interpreted as agent prose and
510/// leaking into notification summaries.
511fn looks_like_ndjson_event_stream(text: &str) -> bool {
512    let Some(first_line) = text.lines().map(str::trim).find(|l| !l.is_empty()) else {
513        return false;
514    };
515
516    if !first_line.starts_with('{') {
517        return false;
518    }
519
520    let Ok(value) = serde_json::from_str::<serde_json::Value>(first_line) else {
521        return false;
522    };
523
524    let Some(event_type) = value.get("type").and_then(|v| v.as_str()) else {
525        return false;
526    };
527
528    matches!(
529        event_type,
530        "step_start"
531            | "step_finish"
532            | "tool_use"
533            | "tool_result"
534            | "assistant"
535            | "system"
536            | "message"
537            | "text"
538    )
539}
540
541/// Build a synthetic agent response from plain text when structured parsing fails.
542///
543/// Returns `None` for empty/whitespace-only text so callers can preserve the
544/// original `InvalidResponse` behavior.
545pub fn synthesize_response_from_text(text: &str) -> Option<AgentResponse> {
546    // Returns true when `word` appears as a whole word in `text`
547    // (not preceded or followed by an ASCII alphanumeric character).
548    fn contains_word(text: &str, word: &str) -> bool {
549        let mut start = 0;
550        while let Some(pos) = text[start..].find(word) {
551            let abs = start + pos;
552            let before_ok = abs == 0 || !text.as_bytes()[abs - 1].is_ascii_alphanumeric();
553            let after_ok = abs + word.len() >= text.len()
554                || !text.as_bytes()[abs + word.len()].is_ascii_alphanumeric();
555            if before_ok && after_ok {
556                return true;
557            }
558            start = abs + 1;
559            if start >= text.len() {
560                break;
561            }
562        }
563        false
564    }
565
566    let trimmed = text.trim();
567    if trimmed.is_empty() {
568        return None;
569    }
570
571    // Detect CLI/arg-parser diagnostics and reject them. These indicate the agent
572    // process failed to start properly (e.g. invalid flag), not that the agent
573    // produced a free-form answer. Clap-based CLIs emit patterns like:
574    //   "error: unexpected argument '--flag' found"
575    //   "Usage: command [OPTIONS]"
576    //   "For more information, try '--help'"
577    //   "tip: to pass '...' as a value, use '-- ...'"
578    if is_cli_parser_diagnostic(trimmed) {
579        return None;
580    }
581
582    // Detect NDJSON event streams (opencode/claude/codex stdout) and reject
583    // them. Raw NDJSON masquerading as prose would otherwise leak into
584    // notification summaries — the "completed" substring inside tool state
585    // JSON triggers a false "done" classification and the first 500 bytes of
586    // NDJSON become the user-visible summary.
587    if looks_like_ndjson_event_stream(trimmed) {
588        return None;
589    }
590
591    let lower = trimmed.to_lowercase();
592    // Also accept plain-language confirmations of performed actions (issue/PR
593    // creation, comments, etc.) as a successful "done" signal. This prevents
594    // tasks from being retried when an agent reports success in free-form
595    // text instead of returning structured JSON.
596
597    // Negation phrases that override a "done/completed" match.
598    let looks_negative = [
599        "not done",
600        "not yet done",
601        "not complete",
602        "not yet complete",
603        "not completed",
604        "not yet completed",
605        "not committed",
606        "incomplete",
607        "undone",
608    ]
609    .iter()
610    .any(|needle| lower.contains(needle));
611
612    // Strong explicit completion phrases. These are high-confidence indicators
613    // that the agent performed an action (filed issues, created commits, etc.).
614    let explicit_done = [
615        "nothing to",
616        "nothing to do",
617        "nothing to execute",
618        "no positions",
619        "no open positions",
620        "no trades",
621        "no trade",
622        "no action needed",
623        "no changes to commit",
624        "completed",
625        // Action/issue completion phrases
626        "filed",
627        "filed issue",
628        "filed issues",
629        "created issue",
630        "created issues",
631        "opened issue",
632        "opened issues",
633        "issue created",
634        "issues created",
635        "issues filed",
636        "task created",
637        "posted comment",
638        "comment posted",
639        "changes committed",
640        "commit created",
641        "fixed.",
642        "has been fixed",
643        "the fix has been applied",
644        "the fix has already been applied",
645        // Agent completion phrases (regression: #1362/#1363)
646        "the fix is complete",
647        "fix is working",
648        "all tests pass",
649        "tests pass.",
650    ]
651    .iter()
652    .any(|needle| lower.contains(needle));
653
654    // Conservative sentence-level heuristics for single-word signals like "done".
655    // Accept "done" only when it appears in a short, self-contained sentence
656    // without hedging language ("let me", "checking", "will", etc.). This
657    // reduces false-positives from exploratory prose that mentions "done"
658    // as part of a planning or investigatory sentence.
659    let mut done_confident = false;
660    for sentence in trimmed
661        .split(['.', '!', '?', '\n'])
662        .map(str::trim)
663        .filter(|s| !s.is_empty())
664    {
665        let s_lower = sentence.to_lowercase();
666        // short sentence heuristic
667        let word_count = sentence.split_whitespace().count();
668        let hedging = [
669            "let",
670            "let me",
671            "check",
672            "checking",
673            "will",
674            "i'll",
675            "i will",
676            "trying",
677            "try",
678            "investigat",
679            "maybe",
680            "could",
681            "should",
682            "might",
683            "if ",
684            "plan",
685            "planning",
686        ];
687        let contains_hedge = hedging.iter().any(|h| s_lower.contains(h));
688
689        if contains_word(&s_lower, "done") && word_count <= 8 && !contains_hedge {
690            done_confident = true;
691            break;
692        }
693
694        // Commit/concrete action heuristics: require explicit commit language
695        // rather than opportunistic mentions. Examples: "I've committed the changes",
696        // "changes committed", or "commit created".
697        if s_lower.contains("committed") || s_lower.contains("commit created") {
698            // Accept only if sentence also suggests the changes were actually written
699            if s_lower.contains("changes")
700                || s_lower.contains("i've")
701                || s_lower.contains("i have")
702                || s_lower.contains("the commit")
703            {
704                done_confident = true;
705                break;
706            }
707        }
708
709        // Past-tense action verb at sentence start indicates a completed action
710        // (e.g. "Added detect_rate_limit patterns", "Fixed the nil-pointer bug").
711        // Accept only for short sentences without hedging language to avoid matching
712        // prose like "I added a note that this might fail later".
713        let past_tense_actions = [
714            "added ",
715            "fixed ",
716            "updated ",
717            "implemented ",
718            "created ",
719            "removed ",
720            "changed ",
721            "deleted ",
722            "applied ",
723            "resolved ",
724            "patched ",
725            "refactored ",
726            "merged ",
727            "pushed ",
728            "deployed ",
729        ];
730        if !contains_hedge
731            && word_count <= 12
732            && past_tense_actions.iter().any(|v| s_lower.starts_with(v))
733        {
734            done_confident = true;
735            break;
736        }
737    }
738
739    let looks_done = !looks_negative && (explicit_done || done_confident);
740
741    let looks_error = [
742        "error:",
743        "failed to",
744        "cannot",
745        "permission denied",
746        "unable to",
747    ]
748    .iter()
749    .any(|needle| lower.contains(needle));
750
751    let status = if looks_error {
752        "needs_review"
753    } else if looks_done {
754        "done"
755    } else if looks_negative {
756        // Agent explicitly stated the task is not complete — surface for human review.
757        "needs_review"
758    } else {
759        // Text is ambiguous: no error signal, no completion signal, no explicit negation.
760        // This happens when agents emit exploratory or startup text (e.g. "Let's go!",
761        // "I need to find where...") and exit without producing structured JSON.
762        // Returning None causes callers to treat this as an invalid response and reroute
763        // the task rather than falsely advancing it to needs_review / in_review.
764        return None;
765    };
766
767    let summary_end = truncate_at_char_boundary(trimmed, 500);
768    let summary = trimmed[..summary_end].to_string();
769    let error =
770        (status == "needs_review").then(|| "agent returned plain text instead of JSON".to_string());
771
772    // Extract structured fields from free-form text.
773    let files = extract_file_paths(trimmed);
774    let (accomplished, remaining) = extract_bullet_sections(trimmed);
775
776    Some(AgentResponse {
777        status: status.to_string(),
778        summary,
779        accomplished,
780        remaining,
781        files,
782        error,
783        input_tokens: None,
784        output_tokens: None,
785        learnings: vec![],
786        delegations: vec![],
787        screenshots: vec![],
788        screenshot_note: None,
789    })
790}
791
792/// Quote a string for safe insertion into a POSIX shell command.
793pub(crate) fn shell_single_quote(value: &str) -> String {
794    format!("'{}'", value.replace('\'', "'\\''"))
795}
796
797/// Find the largest byte index <= `max_bytes` that lies on a UTF-8 char
798/// boundary.  Used for safe string truncation in error messages.
799pub fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> usize {
800    if max_bytes >= s.len() {
801        return s.len();
802    }
803    // Walk backwards from max_bytes until we hit a char boundary
804    let mut end = max_bytes;
805    while end > 0 && !s.is_char_boundary(end) {
806        end -= 1;
807    }
808    end
809}
810
811/// One step of an agent's work, as `orch stream` shows it
812#[derive(Debug, Clone, PartialEq)]
813pub enum StreamEvent {
814    Started {
815        model: String,
816    },
817    Text(String),
818    Thinking(String),
819    /// `id` links the call to its result, empty when the agent has none
820    ToolCall {
821        id: String,
822        name: String,
823        input: serde_json::Value,
824    },
825    /// `name` is empty when only `id` names the call
826    ToolResult {
827        id: String,
828        name: String,
829        output: String,
830        is_error: bool,
831    },
832    Done(String),
833    Error(String),
834}
835
836/// String at a JSON pointer, empty when missing
837pub(crate) fn json_str<'a>(v: &'a serde_json::Value, pointer: &str) -> &'a str {
838    v.pointer(pointer)
839        .and_then(serde_json::Value::as_str)
840        .unwrap_or("")
841}
842
843/// Error text from any of the shapes agents use: `message`, `error`, `error.message`, `error.data.message`
844pub(crate) fn json_error_message(v: &serde_json::Value) -> String {
845    [
846        "/message",
847        "/error",
848        "/error/message",
849        "/error/data/message",
850    ]
851    .iter()
852    .find_map(|p| v.pointer(p).and_then(serde_json::Value::as_str))
853    .unwrap_or("unknown error")
854    .to_string()
855}
856
857/// Router stdout shape. Each runner reports its own
858#[derive(Debug, Clone, Copy, PartialEq, Eq)]
859pub enum RouterTranscript {
860    /// Claude Messages NDJSON (`type:result`)
861    Messages,
862    /// OpenCode NDJSON (`type:text`, `step_*`)
863    OpenCode,
864    /// Stdout is used as-is
865    Raw,
866}
867
868/// Per-agent runner trait.
869///
870/// Each agent implements this to handle its specific CLI invocation,
871/// output parsing, and error classification.
872pub trait AgentRunner: Send + Sync {
873    /// Agent name (e.g., "claude", "codex", "opencode"). Used in tests.
874    #[cfg(test)]
875    fn name(&self) -> &str;
876
877    /// Build the CLI command string for the legacy tmux runner.
878    ///
879    /// The returned string is embedded into a shell command that captures
880    /// output in the tmux session. The `permissions` struct carries unified
881    /// rules that each agent translates to its own CLI flags.
882    fn build_command(
883        &self,
884        model: Option<&str>,
885        timeout_cmd: &str,
886        sys_file: &str,
887        msg_file: &str,
888        permissions: &PermissionRules,
889    ) -> String;
890
891    /// Build a routed invocation with an optional native reasoning effort.
892    fn build_command_with_effort(
893        &self,
894        model: Option<&str>,
895        _effort: Option<&str>,
896        timeout_cmd: &str,
897        sys_file: &str,
898        msg_file: &str,
899        permissions: &PermissionRules,
900    ) -> String {
901        self.build_command(model, timeout_cmd, sys_file, msg_file, permissions)
902    }
903
904    /// Parse raw stdout into a ParsedResponse.
905    ///
906    /// Returns `Ok(ParsedResponse)` on success, `Err(AgentError)` if the
907    /// output indicates an error or cannot be parsed.
908    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError>;
909
910    /// Extract the raw inner text from an agent output envelope, without
911    /// attempting to parse it as an `AgentResponse`.
912    ///
913    /// Use this in the review pipeline so that a `ReviewResponse` JSON can be
914    /// recovered even when the text doesn't match the task `AgentResponse` schema.
915    ///
916    /// - For Claude/Kimi/MiniMax: strips the `--output-format stream-json` NDJSON
917    ///   wrapper and returns the `"result"` field of the final `"type":"result"` line.
918    /// - For Codex: returns the text of the last `agent_message` item.
919    /// - For OpenCode: concatenates all `text` events.
920    /// - Default: returns `raw` unchanged (safe fallback for unknown agents).
921    ///
922    /// Returns `Err(AgentError)` only for terminal errors (rate limit, auth, etc.)
923    /// that should abort the review pipeline entirely.
924    fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
925        Ok(raw.to_string())
926    }
927
928    /// Transcript steps for one parsed line of this agent's NDJSON output
929    fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent>;
930
931    /// Classify an error from exit code + stdout + stderr into an AgentError.
932    ///
933    /// Called when the agent process exits with a non-zero code, or when
934    /// parse_response fails to find a valid result.
935    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError;
936
937    /// Classify error with elapsed session time (for accurate timeout reporting).
938    fn classify_error_with_elapsed(
939        &self,
940        exit_code: i32,
941        stdout: &str,
942        stderr: &str,
943        elapsed_secs: Option<u64>,
944    ) -> AgentError {
945        let mut err = self.classify_error(exit_code, stdout, stderr);
946        if let AgentError::Timeout { elapsed } = &mut err
947            && let Some(actual_elapsed) = elapsed_secs
948        {
949            *elapsed = Duration::from_secs(actual_elapsed);
950        }
951        err
952    }
953
954    /// Models available for this agent (for intra-agent failover).
955    fn available_models(&self) -> Vec<String> {
956        vec![]
957    }
958
959    /// Free/fallback models for last-resort failover.
960    fn free_models(&self) -> Vec<String> {
961        vec![]
962    }
963
964    /// Router stdout shape. The router matches on this instead of agent names
965    fn router_transcript(&self) -> RouterTranscript {
966        RouterTranscript::Raw
967    }
968
969    /// Build a minimal CLI command for LLM-based routing.
970    ///
971    /// The command should run the agent with `prompt` as the sole task and
972    /// return structured (JSON or NDJSON) output on stdout. Used by the router
973    /// to classify tasks without launching a full agent session.
974    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command>;
975}
976
977/// Agents whose CLI takes `--session-id` for a new session and `--resume` to continue it
978pub fn supports_session(agent: &str) -> bool {
979    matches!(agent, "claude" | "kimi" | "minimax" | "grok")
980}
981
982/// Get the appropriate AgentRunner implementation for an agent name.
983/// Agents that are known to be claude-compatible (same NDJSON output format and flags)
984const CLAUDE_COMPATIBLE_AGENTS: &[&str] = &["claude", "kimi", "minimax", "olm", "glm"];
985
986/// Whether the agent runs Claude Code's CLI, and so honours a tool allowlist
987pub fn is_claude_compatible(agent_name: &str) -> bool {
988    CLAUDE_COMPATIBLE_AGENTS.contains(&agent_name)
989}
990
991pub fn get_runner(agent_name: &str) -> Box<dyn AgentRunner> {
992    match agent_name {
993        "claude" => Box::new(claude::ClaudeRunner::new(agent_name)),
994        "kimi" => Box::new(kimi::KimiClaudeRunner::new()),
995        "minimax" => Box::new(minimax::MiniMaxClaudeRunner::new(agent_name)),
996        "codex" => Box::new(codex::CodexRunner),
997        "opencode" => Box::new(opencode::OpenCodeRunner::new()),
998        "grok" => Box::new(grok::GrokRunner),
999        // Unknown agents fall back to Claude-compatible parsing
1000        other => {
1001            // Only warn if the agent is not known to be claude-compatible
1002            if !CLAUDE_COMPATIBLE_AGENTS.contains(&other) {
1003                tracing::warn!(
1004                    agent = other,
1005                    "unknown agent, using claude-compatible runner"
1006                );
1007            }
1008            Box::new(claude::ClaudeRunner::new(other))
1009        }
1010    }
1011}
1012
1013/// Parse an NDJSON stream into a list of JSON values.
1014///
1015/// Shared by all agents that emit NDJSON output (Codex, OpenCode, etc.).
1016/// Lines that are empty or unparseable are silently skipped with a debug log.
1017///
1018/// For fragmented streams where complete JSON objects span multiple lines,
1019/// we also attempt to concatenate non-empty lines and parse them as a stream
1020/// of JSON objects to handle edge cases where models emit partial NDJSON.
1021pub(crate) fn parse_ndjson(raw: &str) -> Vec<serde_json::Value> {
1022    // Fast path: try parsing each line individually (handles most cases)
1023    let events: Vec<serde_json::Value> = raw
1024        .lines()
1025        .filter(|line| !line.trim().is_empty())
1026        .filter_map(|line| match serde_json::from_str(line) {
1027            Ok(val) => Some(val),
1028            Err(e) => {
1029                tracing::debug!(line, error = %e, "skipping unparseable NDJSON line");
1030                None
1031            }
1032        })
1033        .collect();
1034
1035    // If we got events, return them. Otherwise, try the accumulation fallback
1036    // for edge cases where models emit fragmented JSON (e.g., partial objects
1037    // that get split across lines, or streams with embedded newlines in strings).
1038    if !events.is_empty() {
1039        return events;
1040    }
1041
1042    // Fallback: accumulate all non-empty, non-comment lines and try to extract
1043    // JSON objects by scanning for balanced braces. This handles edge cases like:
1044    // - Closing fence inside JSON strings: {"text": "```json\n{\"status\": \"done\"}\n```"}
1045    // - Fragmented NDJSON where incomplete objects span multiple lines
1046    // - Model outputs with embedded newlines in text fields
1047    let acc: String = raw
1048        .lines()
1049        .filter(|line| {
1050            let t = line.trim();
1051            !t.is_empty() && !t.starts_with("//") && !t.starts_with('#')
1052        })
1053        .collect::<Vec<_>>()
1054        .join(" ");
1055
1056    if acc.is_empty() {
1057        return Vec::new();
1058    }
1059
1060    // Fallback: try to parse the accumulated text directly as a JSON value.
1061    // This handles multi-line JSON objects that don't fit on single lines.
1062    if let Ok(val) = serde_json::from_str::<serde_json::Value>(acc.trim()) {
1063        // Check if stripping ALL whitespace makes it a single JSON object with
1064        // the same content. If so, the input was plain multi-line JSON (not
1065        // fragmented NDJSON), and we should return empty to preserve original
1066        // behavior — callers then treat it as plain text.
1067        let stripped: String = acc.chars().filter(|c| !c.is_ascii_whitespace()).collect();
1068        if let Ok(stripped_val) = serde_json::from_str::<serde_json::Value>(&stripped) {
1069            // Only return empty if the stripped version parses identically,
1070            // meaning whitespace was insignificant. If they differ, whitespace
1071            // matters and this is likely fragmented input.
1072            if stripped_val == val {
1073                return Vec::new();
1074            }
1075        }
1076        return vec![val];
1077    }
1078
1079    // Direct parse failed — try to extract JSON objects by scanning for balanced
1080    // braces. This handles cases like embedded JSON within text:
1081    // `{"text": "```json\n{\"status\": \"done\"}\n```"}`
1082    extract_json_objects(&acc)
1083}
1084
1085/// Extract complete JSON objects from a string by scanning for balanced braces.
1086///
1087/// This is a fallback for fragmented NDJSON streams where complete objects
1088/// don't appear on single lines. Returns all parseable objects found.
1089fn extract_json_objects(text: &str) -> Vec<serde_json::Value> {
1090    let mut results = Vec::new();
1091    let mut start: Option<usize> = None;
1092    let mut depth: i32 = 0;
1093    let mut in_string = false;
1094    let mut escape = false;
1095
1096    for (idx, ch) in text.char_indices() {
1097        if let Some(start_idx) = start {
1098            if in_string {
1099                if escape {
1100                    escape = false;
1101                } else if ch == '\\' {
1102                    escape = true;
1103                } else if ch == '"' {
1104                    in_string = false;
1105                }
1106                continue;
1107            }
1108
1109            match ch {
1110                '"' => in_string = true,
1111                '{' => depth += 1,
1112                '}' => {
1113                    depth -= 1;
1114                    if depth == 0 {
1115                        let candidate = &text[start_idx..=idx];
1116                        if let Ok(val) = serde_json::from_str::<serde_json::Value>(candidate) {
1117                            results.push(val);
1118                        }
1119                        start = None;
1120                    }
1121                }
1122                _ => {}
1123            }
1124            continue;
1125        }
1126
1127        if ch == '{' {
1128            start = Some(idx);
1129            depth = 1;
1130            in_string = false;
1131            escape = false;
1132        }
1133    }
1134
1135    results
1136}
1137
1138/// Env vars that hold an agent's login, so a set one counts as signed in
1139pub(crate) fn login_env_vars(agent: &str) -> &'static [&'static str] {
1140    match agent {
1141        "claude" => &["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"],
1142        "codex" => &["OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_ACCESS_TOKEN"],
1143        "grok" => &["XAI_API_KEY"],
1144        "kimi" => &["KIMI_API_KEY"],
1145        "minimax" => &["MINIMAX_API_KEY"],
1146        "glm" => &["GLM_API_KEY"],
1147        _ => &[],
1148    }
1149}
1150
1151#[cfg(test)]
1152mod tests;