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