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                let end = truncate_at_char_boundary(raw, 200);
315                write!(f, "invalid response: {}", &raw[..end])
316            }
317            Self::AgentFailed { message } => write!(f, "agent failed: {message}"),
318            Self::NetworkError { message } => write!(f, "network error: {message}"),
319            Self::ThinkingBlockConflict { message } => {
320                write!(f, "thinking block conflict: {message}")
321            }
322            Self::Unknown { exit_code, message } => {
323                write!(f, "unknown error (exit {exit_code}): {message}")
324            }
325        }
326    }
327}
328
329impl error::Error for AgentError {}
330
331/// Return the variant name of an `AgentError` as a static string,
332/// for structured logging and `result.json` output.
333pub fn error_class_name(err: &AgentError) -> &'static str {
334    match err {
335        AgentError::RateLimit { .. } => "RateLimit",
336        AgentError::Auth { .. } => "Auth",
337        AgentError::ModelUnavailable { .. } => "ModelUnavailable",
338        AgentError::ContextOverflow { .. } => "ContextOverflow",
339        AgentError::Timeout { .. } => "Timeout",
340        AgentError::Interrupted { .. } => "Interrupted",
341        AgentError::MissingTool { .. } => "MissingTool",
342        AgentError::PermissionDenied { .. } => "PermissionDenied",
343        AgentError::WaitingForInput { .. } => "WaitingForInput",
344        AgentError::StaleSession { .. } => "StaleSession",
345        AgentError::InvalidResponse { .. } => "InvalidResponse",
346        AgentError::AgentFailed { .. } => "AgentFailed",
347        AgentError::NetworkError { .. } => "NetworkError",
348        AgentError::ThinkingBlockConflict { .. } => "ThinkingBlockConflict",
349        AgentError::Unknown { .. } => "Unknown",
350    }
351}
352
353/// Extract file paths from free-form text.
354///
355/// Matches common source file patterns like `src/foo/bar.rs`, `tests/x.py`,
356/// `path/to/file.ts`, etc. Deduplicates and returns them sorted.
357fn extract_file_paths(text: &str) -> Vec<String> {
358    // Match path-like tokens: optional leading slash or no slash, at least one
359    // directory segment or a plain filename, with a recognised extension.
360    let extensions = [
361        "rs", "py", "ts", "tsx", "js", "jsx", "go", "java", "c", "cpp", "h", "hpp", "rb", "sh",
362        "md", "toml", "yaml", "yml", "json", "sql", "html", "css", "swift", "kt",
363    ];
364    let mut found: BTreeSet<String> = BTreeSet::new();
365    for token in text.split_whitespace() {
366        // Strip surrounding punctuation (backticks, quotes, parens, commas).
367        // We intentionally do NOT strip '.' here because it is part of file extensions.
368        let token = token.trim_matches(|c: char| {
369            matches!(
370                c,
371                '`' | '\'' | '"' | '(' | ')' | '[' | ']' | ',' | ':' | ';'
372            )
373        });
374        // Strip a lone trailing dot that ends a sentence (e.g. "src/foo.rs.").
375        // Only strip if the result still has a recognised extension — this avoids
376        // accidentally stripping the final dot of "src/foo.rs" when there is none.
377        let token = if let Some(without) = token.strip_suffix('.') {
378            let still_has_ext = extensions
379                .iter()
380                .any(|ext| without.ends_with(&format!(".{ext}")));
381            if still_has_ext { without } else { token }
382        } else {
383            token
384        };
385        // Must contain at least one slash (directory separator) or look like a
386        // root-relative path, and end with a known extension.
387        let has_ext = extensions
388            .iter()
389            .any(|ext| token.ends_with(&format!(".{ext}")));
390        if !has_ext {
391            continue;
392        }
393        // Accept tokens with at least one path separator, or starting with a
394        // known top-level directory name common in Rust/JS/Python projects.
395        let path_like = token.contains('/')
396            || token.starts_with("src")
397            || token.starts_with("tests")
398            || token.starts_with("lib")
399            || token.starts_with("bin")
400            || token.starts_with("prompts")
401            || token.starts_with("migrations");
402        if path_like && token.len() >= 4 && !token.contains("://") {
403            found.insert(token.to_string());
404        }
405    }
406    found.into_iter().collect()
407}
408
409/// Split free-form text into accomplished and remaining bullet lists.
410///
411/// Lines under "remaining", "todo", "next steps", "still needed" headings are
412/// classified as `remaining`; all other bullet lines go into `accomplished`.
413fn extract_bullet_sections(text: &str) -> (Vec<String>, Vec<String>) {
414    let remaining_headers = [
415        "remaining",
416        "todo",
417        "to do",
418        "next steps",
419        "still needed",
420        "left to do",
421        "not done",
422        "outstanding",
423    ];
424
425    let mut accomplished: Vec<String> = vec![];
426    let mut remaining: Vec<String> = vec![];
427    let mut in_remaining_section = false;
428
429    for line in text.lines() {
430        let trimmed = line.trim();
431        if trimmed.is_empty() {
432            continue;
433        }
434        let lower = trimmed.to_lowercase();
435
436        // Detect section headings: only lines with explicit heading markers.
437        // Require trailing ':' or '#'-prefix to avoid misclassifying continuation
438        // lines (e.g. explanatory text after a bullet) as headings, which would
439        // incorrectly reset `in_remaining_section`.
440        let is_heading = trimmed.ends_with(':') || trimmed.starts_with('#');
441
442        if is_heading {
443            in_remaining_section = remaining_headers.iter().any(|h| lower.contains(h));
444            continue;
445        }
446
447        // Bullet lines: -, *, or numbered (1., 2.)
448        let is_bullet = trimmed.starts_with('-')
449            || trimmed.starts_with('*')
450            || trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains('.');
451
452        if !is_bullet {
453            continue;
454        }
455
456        // Strip leading bullet character(s).
457        let content = trimmed
458            .trim_start_matches(|c: char| c == '-' || c == '*' || c.is_ascii_digit() || c == '.')
459            .trim()
460            .to_string();
461
462        if content.is_empty() {
463            continue;
464        }
465
466        if in_remaining_section {
467            remaining.push(content);
468        } else {
469            accomplished.push(content);
470        }
471    }
472
473    (accomplished, remaining)
474}
475
476/// Detect if text is a CLI/arg-parser diagnostic rather than an agent response.
477/// CLI diagnostics indicate process startup failure, not an agent answer.
478fn is_cli_parser_diagnostic(text: &str) -> bool {
479    let lower = text.to_lowercase();
480
481    // Clap-style error messages
482    if lower.contains("error: unexpected argument") {
483        return true;
484    }
485
486    // Usage/help text patterns
487    if text.lines().any(|line| {
488        let trimmed = line.trim();
489        trimmed.starts_with("Usage:") || trimmed.starts_with("usage:")
490    }) {
491        return true;
492    }
493
494    // Clap help/info hints
495    if lower.contains("for more information, try '--help'") {
496        return true;
497    }
498
499    // Clap "tip" messages about passing values
500    if lower.contains("tip: to pass '") {
501        return true;
502    }
503
504    false
505}
506
507/// Detect whether `text` looks like an NDJSON event stream emitted by an
508/// agent CLI (opencode/claude/codex). Returns true when the first non-empty
509/// line parses as a JSON object containing a `type` field with one of the
510/// known event-type strings.
511///
512/// This guard prevents raw NDJSON from being interpreted as agent prose and
513/// leaking into notification summaries.
514fn looks_like_ndjson_event_stream(text: &str) -> bool {
515    let Some(first_line) = text.lines().map(str::trim).find(|l| !l.is_empty()) else {
516        return false;
517    };
518
519    if !first_line.starts_with('{') {
520        return false;
521    }
522
523    let Ok(value) = serde_json::from_str::<serde_json::Value>(first_line) else {
524        return false;
525    };
526
527    let Some(event_type) = value.get("type").and_then(|v| v.as_str()) else {
528        return false;
529    };
530
531    matches!(
532        event_type,
533        "step_start"
534            | "step_finish"
535            | "tool_use"
536            | "tool_result"
537            | "assistant"
538            | "system"
539            | "message"
540            | "text"
541    )
542}
543
544/// Build a synthetic agent response from plain text when structured parsing fails.
545///
546/// Returns `None` for empty/whitespace-only text so callers can preserve the
547/// original `InvalidResponse` behavior.
548pub fn synthesize_response_from_text(text: &str) -> Option<AgentResponse> {
549    // Returns true when `word` appears as a whole word in `text`
550    // (not preceded or followed by an ASCII alphanumeric character).
551    fn contains_word(text: &str, word: &str) -> bool {
552        let mut start = 0;
553        while let Some(pos) = text[start..].find(word) {
554            let abs = start + pos;
555            let before_ok = abs == 0 || !text.as_bytes()[abs - 1].is_ascii_alphanumeric();
556            let after_ok = abs + word.len() >= text.len()
557                || !text.as_bytes()[abs + word.len()].is_ascii_alphanumeric();
558            if before_ok && after_ok {
559                return true;
560            }
561            start = abs + 1;
562            if start >= text.len() {
563                break;
564            }
565        }
566        false
567    }
568
569    let trimmed = text.trim();
570    if trimmed.is_empty() {
571        return None;
572    }
573
574    // Detect CLI/arg-parser diagnostics and reject them. These indicate the agent
575    // process failed to start properly (e.g. invalid flag), not that the agent
576    // produced a free-form answer. Clap-based CLIs emit patterns like:
577    //   "error: unexpected argument '--flag' found"
578    //   "Usage: command [OPTIONS]"
579    //   "For more information, try '--help'"
580    //   "tip: to pass '...' as a value, use '-- ...'"
581    if is_cli_parser_diagnostic(trimmed) {
582        return None;
583    }
584
585    // Detect NDJSON event streams (opencode/claude/codex stdout) and reject
586    // them. Raw NDJSON masquerading as prose would otherwise leak into
587    // notification summaries — the "completed" substring inside tool state
588    // JSON triggers a false "done" classification and the first 500 bytes of
589    // NDJSON become the user-visible summary.
590    if looks_like_ndjson_event_stream(trimmed) {
591        return None;
592    }
593
594    let lower = trimmed.to_lowercase();
595    // Also accept plain-language confirmations of performed actions (issue/PR
596    // creation, comments, etc.) as a successful "done" signal. This prevents
597    // tasks from being retried when an agent reports success in free-form
598    // text instead of returning structured JSON.
599
600    // Negation phrases that override a "done/completed" match.
601    let looks_negative = [
602        "not done",
603        "not yet done",
604        "not complete",
605        "not yet complete",
606        "not completed",
607        "not yet completed",
608        "not committed",
609        "incomplete",
610        "undone",
611    ]
612    .iter()
613    .any(|needle| lower.contains(needle));
614
615    // Strong explicit completion phrases. These are high-confidence indicators
616    // that the agent performed an action (filed issues, created commits, etc.).
617    let explicit_done = [
618        "nothing to",
619        "nothing to do",
620        "nothing to execute",
621        "no positions",
622        "no open positions",
623        "no trades",
624        "no trade",
625        "no action needed",
626        "no changes to commit",
627        "completed",
628        // Action/issue completion phrases
629        "filed",
630        "filed issue",
631        "filed issues",
632        "created issue",
633        "created issues",
634        "opened issue",
635        "opened issues",
636        "issue created",
637        "issues created",
638        "issues filed",
639        "task created",
640        "posted comment",
641        "comment posted",
642        "changes committed",
643        "commit created",
644        "fixed.",
645        "has been fixed",
646        "the fix has been applied",
647        "the fix has already been applied",
648        // Agent completion phrases (regression: #1362/#1363)
649        "the fix is complete",
650        "fix is working",
651        "all tests pass",
652        "tests pass.",
653    ]
654    .iter()
655    .any(|needle| lower.contains(needle));
656
657    // Conservative sentence-level heuristics for single-word signals like "done".
658    // Accept "done" only when it appears in a short, self-contained sentence
659    // without hedging language ("let me", "checking", "will", etc.). This
660    // reduces false-positives from exploratory prose that mentions "done"
661    // as part of a planning or investigatory sentence.
662    let mut done_confident = false;
663    for sentence in trimmed
664        .split(['.', '!', '?', '\n'])
665        .map(str::trim)
666        .filter(|s| !s.is_empty())
667    {
668        let s_lower = sentence.to_lowercase();
669        // short sentence heuristic
670        let word_count = sentence.split_whitespace().count();
671        let hedging = [
672            "let",
673            "let me",
674            "check",
675            "checking",
676            "will",
677            "i'll",
678            "i will",
679            "trying",
680            "try",
681            "investigat",
682            "maybe",
683            "could",
684            "should",
685            "might",
686            "if ",
687            "plan",
688            "planning",
689        ];
690        let contains_hedge = hedging.iter().any(|h| s_lower.contains(h));
691
692        if contains_word(&s_lower, "done") && word_count <= 8 && !contains_hedge {
693            done_confident = true;
694            break;
695        }
696
697        // Commit/concrete action heuristics: require explicit commit language
698        // rather than opportunistic mentions. Examples: "I've committed the changes",
699        // "changes committed", or "commit created".
700        if s_lower.contains("committed") || s_lower.contains("commit created") {
701            // Accept only if sentence also suggests the changes were actually written
702            if s_lower.contains("changes")
703                || s_lower.contains("i've")
704                || s_lower.contains("i have")
705                || s_lower.contains("the commit")
706            {
707                done_confident = true;
708                break;
709            }
710        }
711
712        // Past-tense action verb at sentence start indicates a completed action
713        // (e.g. "Added detect_rate_limit patterns", "Fixed the nil-pointer bug").
714        // Accept only for short sentences without hedging language to avoid matching
715        // prose like "I added a note that this might fail later".
716        let past_tense_actions = [
717            "added ",
718            "fixed ",
719            "updated ",
720            "implemented ",
721            "created ",
722            "removed ",
723            "changed ",
724            "deleted ",
725            "applied ",
726            "resolved ",
727            "patched ",
728            "refactored ",
729            "merged ",
730            "pushed ",
731            "deployed ",
732        ];
733        if !contains_hedge
734            && word_count <= 12
735            && past_tense_actions.iter().any(|v| s_lower.starts_with(v))
736        {
737            done_confident = true;
738            break;
739        }
740    }
741
742    let looks_done = !looks_negative && (explicit_done || done_confident);
743
744    let looks_error = [
745        "error:",
746        "failed to",
747        "cannot",
748        "permission denied",
749        "unable to",
750    ]
751    .iter()
752    .any(|needle| lower.contains(needle));
753
754    let status = if looks_error {
755        "needs_review"
756    } else if looks_done {
757        "done"
758    } else if looks_negative {
759        // Agent explicitly stated the task is not complete — surface for human review.
760        "needs_review"
761    } else {
762        // Text is ambiguous: no error signal, no completion signal, no explicit negation.
763        // This happens when agents emit exploratory or startup text (e.g. "Let's go!",
764        // "I need to find where...") and exit without producing structured JSON.
765        // Returning None causes callers to treat this as an invalid response and reroute
766        // the task rather than falsely advancing it to needs_review / in_review.
767        return None;
768    };
769
770    let summary_end = truncate_at_char_boundary(trimmed, 500);
771    let summary = trimmed[..summary_end].to_string();
772    let error =
773        (status == "needs_review").then(|| "agent returned plain text instead of JSON".to_string());
774
775    // Extract structured fields from free-form text.
776    let files = extract_file_paths(trimmed);
777    let (accomplished, remaining) = extract_bullet_sections(trimmed);
778
779    Some(AgentResponse {
780        status: status.to_string(),
781        summary,
782        accomplished,
783        remaining,
784        files,
785        error,
786        input_tokens: None,
787        output_tokens: None,
788        learnings: vec![],
789        delegations: vec![],
790        screenshots: vec![],
791        screenshot_note: None,
792    })
793}
794
795/// Quote a string for safe insertion into a POSIX shell command.
796pub(crate) fn shell_single_quote(value: &str) -> String {
797    format!("'{}'", value.replace('\'', "'\\''"))
798}
799
800/// Find the largest byte index <= `max_bytes` that lies on a UTF-8 char
801/// boundary.  Used for safe string truncation in error messages.
802pub fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> usize {
803    if max_bytes >= s.len() {
804        return s.len();
805    }
806    // Walk backwards from max_bytes until we hit a char boundary
807    let mut end = max_bytes;
808    while end > 0 && !s.is_char_boundary(end) {
809        end -= 1;
810    }
811    end
812}
813
814/// One step of an agent's work, as `orch stream` shows it
815#[derive(Debug, Clone, PartialEq)]
816pub enum StreamEvent {
817    Started {
818        model: String,
819    },
820    Text(String),
821    Thinking(String),
822    /// `id` links the call to its result, empty when the agent has none
823    ToolCall {
824        id: String,
825        name: String,
826        input: serde_json::Value,
827    },
828    /// `name` is empty when only `id` names the call
829    ToolResult {
830        id: String,
831        name: String,
832        output: String,
833        is_error: bool,
834    },
835    Done(String),
836    Error(String),
837}
838
839/// String at a JSON pointer, empty when missing
840pub(crate) fn json_str<'a>(v: &'a serde_json::Value, pointer: &str) -> &'a str {
841    v.pointer(pointer)
842        .and_then(serde_json::Value::as_str)
843        .unwrap_or("")
844}
845
846/// Error text from any of the shapes agents use: `message`, `error`, `error.message`, `error.data.message`
847pub(crate) fn json_error_message(v: &serde_json::Value) -> String {
848    [
849        "/message",
850        "/error",
851        "/error/message",
852        "/error/data/message",
853    ]
854    .iter()
855    .find_map(|p| v.pointer(p).and_then(serde_json::Value::as_str))
856    .unwrap_or("unknown error")
857    .to_string()
858}
859
860/// Router stdout shape. Each runner reports its own
861#[derive(Debug, Clone, Copy, PartialEq, Eq)]
862pub enum RouterTranscript {
863    /// Claude Messages NDJSON (`type:result`)
864    Messages,
865    /// OpenCode NDJSON (`type:text`, `step_*`)
866    OpenCode,
867    /// Stdout is used as-is
868    Raw,
869}
870
871/// Per-agent runner trait.
872///
873/// Each agent implements this to handle its specific CLI invocation,
874/// output parsing, and error classification.
875pub trait AgentRunner: Send + Sync {
876    /// Agent name (e.g., "claude", "codex", "opencode"). Used in tests.
877    #[cfg(test)]
878    fn name(&self) -> &str;
879
880    /// Build the CLI command string for the legacy tmux runner.
881    ///
882    /// The returned string is embedded into a shell command that captures
883    /// output in the tmux session. The `permissions` struct carries unified
884    /// rules that each agent translates to its own CLI flags.
885    fn build_command(
886        &self,
887        model: Option<&str>,
888        timeout_cmd: &str,
889        sys_file: &str,
890        msg_file: &str,
891        permissions: &PermissionRules,
892    ) -> String;
893
894    /// Build a routed invocation with an optional native reasoning effort.
895    fn build_command_with_effort(
896        &self,
897        model: Option<&str>,
898        _effort: Option<&str>,
899        timeout_cmd: &str,
900        sys_file: &str,
901        msg_file: &str,
902        permissions: &PermissionRules,
903    ) -> String {
904        self.build_command(model, timeout_cmd, sys_file, msg_file, permissions)
905    }
906
907    /// Parse raw stdout into a ParsedResponse.
908    ///
909    /// Returns `Ok(ParsedResponse)` on success, `Err(AgentError)` if the
910    /// output indicates an error or cannot be parsed.
911    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError>;
912
913    /// Extract the raw inner text from an agent output envelope, without
914    /// attempting to parse it as an `AgentResponse`.
915    ///
916    /// Use this in the review pipeline so that a `ReviewResponse` JSON can be
917    /// recovered even when the text doesn't match the task `AgentResponse` schema.
918    ///
919    /// - For Claude/Kimi/MiniMax: strips the `--output-format stream-json` NDJSON
920    ///   wrapper and returns the `"result"` field of the final `"type":"result"` line.
921    /// - For Codex: returns the text of the last `agent_message` item.
922    /// - For OpenCode: concatenates all `text` events.
923    /// - Default: returns `raw` unchanged (safe fallback for unknown agents).
924    ///
925    /// Returns `Err(AgentError)` only for terminal errors (rate limit, auth, etc.)
926    /// that should abort the review pipeline entirely.
927    fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
928        Ok(raw.to_string())
929    }
930
931    /// Transcript steps for one parsed line of this agent's NDJSON output
932    fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent>;
933
934    /// Classify an error from exit code + stdout + stderr into an AgentError.
935    ///
936    /// Called when the agent process exits with a non-zero code, or when
937    /// parse_response fails to find a valid result.
938    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError;
939
940    /// Classify error with elapsed session time (for accurate timeout reporting).
941    fn classify_error_with_elapsed(
942        &self,
943        exit_code: i32,
944        stdout: &str,
945        stderr: &str,
946        elapsed_secs: Option<u64>,
947    ) -> AgentError {
948        let mut err = self.classify_error(exit_code, stdout, stderr);
949        if let AgentError::Timeout { elapsed } = &mut err
950            && let Some(actual_elapsed) = elapsed_secs
951        {
952            *elapsed = Duration::from_secs(actual_elapsed);
953        }
954        err
955    }
956
957    /// Models available for this agent (for intra-agent failover).
958    fn available_models(&self) -> Vec<String> {
959        vec![]
960    }
961
962    /// Free/fallback models for last-resort failover.
963    fn free_models(&self) -> Vec<String> {
964        vec![]
965    }
966
967    /// Router stdout shape. The router matches on this instead of agent names
968    fn router_transcript(&self) -> RouterTranscript {
969        RouterTranscript::Raw
970    }
971
972    /// Build a minimal CLI command for LLM-based routing.
973    ///
974    /// The command should run the agent with `prompt` as the sole task and
975    /// return structured (JSON or NDJSON) output on stdout. Used by the router
976    /// to classify tasks without launching a full agent session.
977    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command>;
978}
979
980/// Agents whose CLI takes `--session-id` for a new session and `--resume` to continue it
981pub fn supports_session(agent: &str) -> bool {
982    matches!(agent, "claude" | "kimi" | "minimax" | "grok")
983}
984
985/// Get the appropriate AgentRunner implementation for an agent name.
986/// Agents that are known to be claude-compatible (same NDJSON output format and flags)
987const CLAUDE_COMPATIBLE_AGENTS: &[&str] = &["claude", "kimi", "minimax", "olm", "glm"];
988
989/// Whether the agent runs Claude Code's CLI, and so honours a tool allowlist
990pub fn is_claude_compatible(agent_name: &str) -> bool {
991    CLAUDE_COMPATIBLE_AGENTS.contains(&agent_name)
992}
993
994pub fn get_runner(agent_name: &str) -> Box<dyn AgentRunner> {
995    match agent_name {
996        "claude" => Box::new(claude::ClaudeRunner::new(agent_name)),
997        "kimi" => Box::new(kimi::KimiClaudeRunner::new()),
998        "minimax" => Box::new(minimax::MiniMaxClaudeRunner::new(agent_name)),
999        "codex" => Box::new(codex::CodexRunner),
1000        "opencode" => Box::new(opencode::OpenCodeRunner::new()),
1001        "grok" => Box::new(grok::GrokRunner),
1002        // Unknown agents fall back to Claude-compatible parsing
1003        other => {
1004            // Only warn if the agent is not known to be claude-compatible
1005            if !CLAUDE_COMPATIBLE_AGENTS.contains(&other) {
1006                tracing::warn!(
1007                    agent = other,
1008                    "unknown agent, using claude-compatible runner"
1009                );
1010            }
1011            Box::new(claude::ClaudeRunner::new(other))
1012        }
1013    }
1014}
1015
1016/// Parse an NDJSON stream into a list of JSON values.
1017///
1018/// Shared by all agents that emit NDJSON output (Codex, OpenCode, etc.).
1019/// Lines that are empty or unparseable are silently skipped with a debug log.
1020///
1021/// For fragmented streams where complete JSON objects span multiple lines,
1022/// we also attempt to concatenate non-empty lines and parse them as a stream
1023/// of JSON objects to handle edge cases where models emit partial NDJSON.
1024pub(crate) fn parse_ndjson(raw: &str) -> Vec<serde_json::Value> {
1025    // Fast path: try parsing each line individually (handles most cases)
1026    let events: Vec<serde_json::Value> = raw
1027        .lines()
1028        .filter(|line| !line.trim().is_empty())
1029        .filter_map(|line| match serde_json::from_str(line) {
1030            Ok(val) => Some(val),
1031            Err(e) => {
1032                tracing::debug!(line, error = %e, "skipping unparseable NDJSON line");
1033                None
1034            }
1035        })
1036        .collect();
1037
1038    // If we got events, return them. Otherwise, try the accumulation fallback
1039    // for edge cases where models emit fragmented JSON (e.g., partial objects
1040    // that get split across lines, or streams with embedded newlines in strings).
1041    if !events.is_empty() {
1042        return events;
1043    }
1044
1045    // Fallback: accumulate all non-empty, non-comment lines and try to extract
1046    // JSON objects by scanning for balanced braces. This handles edge cases like:
1047    // - Closing fence inside JSON strings: {"text": "```json\n{\"status\": \"done\"}\n```"}
1048    // - Fragmented NDJSON where incomplete objects span multiple lines
1049    // - Model outputs with embedded newlines in text fields
1050    let acc: String = raw
1051        .lines()
1052        .filter(|line| {
1053            let t = line.trim();
1054            !t.is_empty() && !t.starts_with("//") && !t.starts_with('#')
1055        })
1056        .collect::<Vec<_>>()
1057        .join(" ");
1058
1059    if acc.is_empty() {
1060        return Vec::new();
1061    }
1062
1063    // Fallback: try to parse the accumulated text directly as a JSON value.
1064    // This handles multi-line JSON objects that don't fit on single lines.
1065    if let Ok(val) = serde_json::from_str::<serde_json::Value>(acc.trim()) {
1066        // Check if stripping ALL whitespace makes it a single JSON object with
1067        // the same content. If so, the input was plain multi-line JSON (not
1068        // fragmented NDJSON), and we should return empty to preserve original
1069        // behavior — callers then treat it as plain text.
1070        let stripped: String = acc.chars().filter(|c| !c.is_ascii_whitespace()).collect();
1071        if let Ok(stripped_val) = serde_json::from_str::<serde_json::Value>(&stripped) {
1072            // Only return empty if the stripped version parses identically,
1073            // meaning whitespace was insignificant. If they differ, whitespace
1074            // matters and this is likely fragmented input.
1075            if stripped_val == val {
1076                return Vec::new();
1077            }
1078        }
1079        return vec![val];
1080    }
1081
1082    // Direct parse failed — try to extract JSON objects by scanning for balanced
1083    // braces. This handles cases like embedded JSON within text:
1084    // `{"text": "```json\n{\"status\": \"done\"}\n```"}`
1085    extract_json_objects(&acc)
1086}
1087
1088/// Extract complete JSON objects from a string by scanning for balanced braces.
1089///
1090/// This is a fallback for fragmented NDJSON streams where complete objects
1091/// don't appear on single lines. Returns all parseable objects found.
1092fn extract_json_objects(text: &str) -> Vec<serde_json::Value> {
1093    let mut results = Vec::new();
1094    let mut start: Option<usize> = None;
1095    let mut depth: i32 = 0;
1096    let mut in_string = false;
1097    let mut escape = false;
1098
1099    for (idx, ch) in text.char_indices() {
1100        if let Some(start_idx) = start {
1101            if in_string {
1102                if escape {
1103                    escape = false;
1104                } else if ch == '\\' {
1105                    escape = true;
1106                } else if ch == '"' {
1107                    in_string = false;
1108                }
1109                continue;
1110            }
1111
1112            match ch {
1113                '"' => in_string = true,
1114                '{' => depth += 1,
1115                '}' => {
1116                    depth -= 1;
1117                    if depth == 0 {
1118                        let candidate = &text[start_idx..=idx];
1119                        if let Ok(val) = serde_json::from_str::<serde_json::Value>(candidate) {
1120                            results.push(val);
1121                        }
1122                        start = None;
1123                    }
1124                }
1125                _ => {}
1126            }
1127            continue;
1128        }
1129
1130        if ch == '{' {
1131            start = Some(idx);
1132            depth = 1;
1133            in_string = false;
1134            escape = false;
1135        }
1136    }
1137
1138    results
1139}
1140
1141/// Env vars that hold an agent's login, so a set one counts as signed in
1142pub(crate) fn login_env_vars(agent: &str) -> &'static [&'static str] {
1143    match agent {
1144        "claude" => &["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"],
1145        "codex" => &["OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_ACCESS_TOKEN"],
1146        "grok" => &["XAI_API_KEY"],
1147        "kimi" => &["KIMI_API_KEY"],
1148        "minimax" => &["MINIMAX_API_KEY"],
1149        "glm" => &["GLM_API_KEY"],
1150        _ => &[],
1151    }
1152}
1153
1154#[cfg(test)]
1155mod tests;