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