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