Skip to main content

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