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