#[macro_use]
mod delegate;
#[cfg(test)]
pub(crate) mod fixture;
pub(crate) mod patterns;
pub mod claude;
pub mod codex;
pub mod grok;
pub mod kimi;
pub mod minimax;
pub mod opencode;
use crate::config;
use crate::parser::AgentResponse;
use std::collections::BTreeSet;
use std::error;
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
use std::path::PathBuf;
use std::time::Duration;
use tokio::process::Command;
#[derive(Debug, Clone)]
pub struct PermissionRules {
pub autonomous: bool,
pub sandbox: SandboxLevel,
pub disallowed_tools: Vec<String>,
pub allowed_tools: Vec<String>,
pub allowed_edit_paths: Vec<PathBuf>,
pub deny_read_only: bool,
pub extra_writable_dirs: Vec<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SandboxLevel {
WorkspaceWrite,
FullAccess,
None,
Os,
ReadOnly,
}
impl Default for PermissionRules {
fn default() -> Self {
Self {
autonomous: true,
sandbox: SandboxLevel::WorkspaceWrite,
disallowed_tools: vec![
"Bash(rm *)".to_string(),
"Bash(rm -*)".to_string(),
"Bash(git push*)".to_string(),
],
allowed_tools: vec![],
allowed_edit_paths: vec![],
deny_read_only: false,
extra_writable_dirs: vec![],
}
}
}
impl PermissionRules {
pub fn from_config() -> Self {
let mut rules = Self::default();
if let Ok(mode) = config::get("workflow.permissions.mode") {
rules.autonomous = mode != "supervised";
}
if let Ok(sandbox) = config::get("workflow.permissions.sandbox") {
rules.sandbox = match sandbox.as_str() {
"full-access" | "danger-full-access" => SandboxLevel::FullAccess,
"none" => SandboxLevel::None,
_ => SandboxLevel::WorkspaceWrite,
};
}
if let Ok(tools) = config::get("workflow.disallowed_tools") {
let parsed: Vec<String> = tools
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if !parsed.is_empty() {
rules.disallowed_tools = parsed;
}
}
if let Ok(tools) = config::get_list("workflow.allowed_tools") {
rules.allowed_tools = tools;
}
rules
}
pub fn read_only(allowed: Vec<String>) -> Self {
Self {
autonomous: false,
sandbox: SandboxLevel::ReadOnly,
disallowed_tools: vec![],
allowed_tools: allowed,
allowed_edit_paths: vec![],
deny_read_only: false,
extra_writable_dirs: vec![],
}
}
pub fn deny_read_only() -> Self {
Self {
autonomous: true,
sandbox: SandboxLevel::WorkspaceWrite,
disallowed_tools: vec![
"Bash(rm *)".to_string(),
"Bash(rm -*)".to_string(),
"Bash(git push*)".to_string(),
"Bash(ls *)".to_string(),
"Bash(ls)".to_string(),
"Bash(find *)".to_string(),
"Bash(cat *)".to_string(),
"Bash(head *)".to_string(),
"Bash(tail *)".to_string(),
"Bash(fzf *)".to_string(),
"Bash(less *)".to_string(),
"Bash(more *)".to_string(),
"Read".to_string(),
"Glob".to_string(),
"Grep".to_string(),
],
allowed_tools: vec![],
allowed_edit_paths: vec![],
deny_read_only: true,
extra_writable_dirs: vec![],
}
}
}
#[derive(Debug, Clone)]
pub struct AgentResult {
pub is_error: bool,
pub result_text: String,
pub input_tokens: Option<u64>,
pub output_tokens: Option<u64>,
pub cost_usd: Option<f64>,
pub duration_ms: Option<u64>,
pub truncated_by_length: bool,
}
pub fn collect_assistant_messages_text(_agent: &str, ndjson: &str) -> String {
claude::collect_assistant_messages_text(ndjson)
}
pub fn find_agent_result(agent: &str, ndjson: &str) -> Option<AgentResult> {
match agent {
"grok" => grok::find_grok_result(ndjson),
"opencode" => opencode::find_opencode_result(ndjson),
"codex" => codex::find_codex_result(ndjson),
_ => claude::find_claude_result(ndjson),
}
}
#[derive(Debug, Clone)]
pub struct ParsedResponse {
pub response: AgentResponse,
pub input_tokens: Option<u64>,
pub output_tokens: Option<u64>,
pub cost_usd: Option<f64>,
pub duration_ms: Option<u64>,
}
#[derive(Debug, Clone)]
pub enum AgentError {
RateLimit { message: String },
Auth { message: String },
ModelUnavailable { message: String, model: String },
ContextOverflow { message: String },
Timeout { elapsed: Duration },
Interrupted { message: String },
MissingTool { tool: String },
PermissionDenied { message: String },
WaitingForInput { message: String },
StaleSession { session_id: String },
InvalidResponse { raw: String },
AgentFailed { message: String },
NetworkError { message: String },
ThinkingBlockConflict { message: String },
Unknown { exit_code: i32, message: String },
}
impl Display for AgentError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::RateLimit { message, .. } => write!(f, "rate limit: {message}"),
Self::Auth { message } => write!(f, "auth error: {message}"),
Self::ModelUnavailable { message, model } => {
write!(f, "model unavailable ({model}): {message}")
}
Self::ContextOverflow { message, .. } => write!(f, "context overflow: {message}"),
Self::Timeout { elapsed } => write!(f, "timeout after {}s", elapsed.as_secs()),
Self::Interrupted { message } => write!(f, "interrupted: {message}"),
Self::MissingTool { tool } => write!(f, "missing tool: {tool}"),
Self::PermissionDenied { message } => write!(f, "permission denied: {message}"),
Self::WaitingForInput { message } => write!(f, "waiting for input: {message}"),
Self::StaleSession { session_id } => {
write!(f, "stale session (session expired): {session_id}")
}
Self::InvalidResponse { raw } => {
let end = truncate_at_char_boundary(raw, 200);
write!(f, "invalid response: {}", &raw[..end])
}
Self::AgentFailed { message } => write!(f, "agent failed: {message}"),
Self::NetworkError { message } => write!(f, "network error: {message}"),
Self::ThinkingBlockConflict { message } => {
write!(f, "thinking block conflict: {message}")
}
Self::Unknown { exit_code, message } => {
write!(f, "unknown error (exit {exit_code}): {message}")
}
}
}
}
impl error::Error for AgentError {}
pub fn error_class_name(err: &AgentError) -> &'static str {
match err {
AgentError::RateLimit { .. } => "RateLimit",
AgentError::Auth { .. } => "Auth",
AgentError::ModelUnavailable { .. } => "ModelUnavailable",
AgentError::ContextOverflow { .. } => "ContextOverflow",
AgentError::Timeout { .. } => "Timeout",
AgentError::Interrupted { .. } => "Interrupted",
AgentError::MissingTool { .. } => "MissingTool",
AgentError::PermissionDenied { .. } => "PermissionDenied",
AgentError::WaitingForInput { .. } => "WaitingForInput",
AgentError::StaleSession { .. } => "StaleSession",
AgentError::InvalidResponse { .. } => "InvalidResponse",
AgentError::AgentFailed { .. } => "AgentFailed",
AgentError::NetworkError { .. } => "NetworkError",
AgentError::ThinkingBlockConflict { .. } => "ThinkingBlockConflict",
AgentError::Unknown { .. } => "Unknown",
}
}
fn extract_file_paths(text: &str) -> Vec<String> {
let extensions = [
"rs", "py", "ts", "tsx", "js", "jsx", "go", "java", "c", "cpp", "h", "hpp", "rb", "sh",
"md", "toml", "yaml", "yml", "json", "sql", "html", "css", "swift", "kt",
];
let mut found: BTreeSet<String> = BTreeSet::new();
for token in text.split_whitespace() {
let token = token.trim_matches(|c: char| {
matches!(
c,
'`' | '\'' | '"' | '(' | ')' | '[' | ']' | ',' | ':' | ';'
)
});
let token = if let Some(without) = token.strip_suffix('.') {
let still_has_ext = extensions
.iter()
.any(|ext| without.ends_with(&format!(".{ext}")));
if still_has_ext { without } else { token }
} else {
token
};
let has_ext = extensions
.iter()
.any(|ext| token.ends_with(&format!(".{ext}")));
if !has_ext {
continue;
}
let path_like = token.contains('/')
|| token.starts_with("src")
|| token.starts_with("tests")
|| token.starts_with("lib")
|| token.starts_with("bin")
|| token.starts_with("prompts")
|| token.starts_with("migrations");
if path_like && token.len() >= 4 && !token.contains("://") {
found.insert(token.to_string());
}
}
found.into_iter().collect()
}
fn extract_bullet_sections(text: &str) -> (Vec<String>, Vec<String>) {
let remaining_headers = [
"remaining",
"todo",
"to do",
"next steps",
"still needed",
"left to do",
"not done",
"outstanding",
];
let mut accomplished: Vec<String> = vec![];
let mut remaining: Vec<String> = vec![];
let mut in_remaining_section = false;
for line in text.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let lower = trimmed.to_lowercase();
let is_heading = trimmed.ends_with(':') || trimmed.starts_with('#');
if is_heading {
in_remaining_section = remaining_headers.iter().any(|h| lower.contains(h));
continue;
}
let is_bullet = trimmed.starts_with('-')
|| trimmed.starts_with('*')
|| trimmed.chars().next().is_some_and(|c| c.is_ascii_digit()) && trimmed.contains('.');
if !is_bullet {
continue;
}
let content = trimmed
.trim_start_matches(|c: char| c == '-' || c == '*' || c.is_ascii_digit() || c == '.')
.trim()
.to_string();
if content.is_empty() {
continue;
}
if in_remaining_section {
remaining.push(content);
} else {
accomplished.push(content);
}
}
(accomplished, remaining)
}
fn is_cli_parser_diagnostic(text: &str) -> bool {
let lower = text.to_lowercase();
if lower.contains("error: unexpected argument") {
return true;
}
if text.lines().any(|line| {
let trimmed = line.trim();
trimmed.starts_with("Usage:") || trimmed.starts_with("usage:")
}) {
return true;
}
if lower.contains("for more information, try '--help'") {
return true;
}
if lower.contains("tip: to pass '") {
return true;
}
false
}
fn looks_like_ndjson_event_stream(text: &str) -> bool {
let Some(first_line) = text.lines().map(str::trim).find(|l| !l.is_empty()) else {
return false;
};
if !first_line.starts_with('{') {
return false;
}
let Ok(value) = serde_json::from_str::<serde_json::Value>(first_line) else {
return false;
};
let Some(event_type) = value.get("type").and_then(|v| v.as_str()) else {
return false;
};
matches!(
event_type,
"step_start"
| "step_finish"
| "tool_use"
| "tool_result"
| "assistant"
| "system"
| "message"
| "text"
)
}
pub fn synthesize_response_from_text(text: &str) -> Option<AgentResponse> {
fn contains_word(text: &str, word: &str) -> bool {
let mut start = 0;
while let Some(pos) = text[start..].find(word) {
let abs = start + pos;
let before_ok = abs == 0 || !text.as_bytes()[abs - 1].is_ascii_alphanumeric();
let after_ok = abs + word.len() >= text.len()
|| !text.as_bytes()[abs + word.len()].is_ascii_alphanumeric();
if before_ok && after_ok {
return true;
}
start = abs + 1;
if start >= text.len() {
break;
}
}
false
}
let trimmed = text.trim();
if trimmed.is_empty() {
return None;
}
if is_cli_parser_diagnostic(trimmed) {
return None;
}
if looks_like_ndjson_event_stream(trimmed) {
return None;
}
let lower = trimmed.to_lowercase();
let looks_negative = [
"not done",
"not yet done",
"not complete",
"not yet complete",
"not completed",
"not yet completed",
"not committed",
"incomplete",
"undone",
]
.iter()
.any(|needle| lower.contains(needle));
let explicit_done = [
"nothing to",
"nothing to do",
"nothing to execute",
"no positions",
"no open positions",
"no trades",
"no trade",
"no action needed",
"no changes to commit",
"completed",
"filed",
"filed issue",
"filed issues",
"created issue",
"created issues",
"opened issue",
"opened issues",
"issue created",
"issues created",
"issues filed",
"task created",
"posted comment",
"comment posted",
"changes committed",
"commit created",
"fixed.",
"has been fixed",
"the fix has been applied",
"the fix has already been applied",
"the fix is complete",
"fix is working",
"all tests pass",
"tests pass.",
]
.iter()
.any(|needle| lower.contains(needle));
let mut done_confident = false;
for sentence in trimmed
.split(['.', '!', '?', '\n'])
.map(str::trim)
.filter(|s| !s.is_empty())
{
let s_lower = sentence.to_lowercase();
let word_count = sentence.split_whitespace().count();
let hedging = [
"let",
"let me",
"check",
"checking",
"will",
"i'll",
"i will",
"trying",
"try",
"investigat",
"maybe",
"could",
"should",
"might",
"if ",
"plan",
"planning",
];
let contains_hedge = hedging.iter().any(|h| s_lower.contains(h));
if contains_word(&s_lower, "done") && word_count <= 8 && !contains_hedge {
done_confident = true;
break;
}
if s_lower.contains("committed") || s_lower.contains("commit created") {
if s_lower.contains("changes")
|| s_lower.contains("i've")
|| s_lower.contains("i have")
|| s_lower.contains("the commit")
{
done_confident = true;
break;
}
}
let past_tense_actions = [
"added ",
"fixed ",
"updated ",
"implemented ",
"created ",
"removed ",
"changed ",
"deleted ",
"applied ",
"resolved ",
"patched ",
"refactored ",
"merged ",
"pushed ",
"deployed ",
];
if !contains_hedge
&& word_count <= 12
&& past_tense_actions.iter().any(|v| s_lower.starts_with(v))
{
done_confident = true;
break;
}
}
let looks_done = !looks_negative && (explicit_done || done_confident);
let looks_error = [
"error:",
"failed to",
"cannot",
"permission denied",
"unable to",
]
.iter()
.any(|needle| lower.contains(needle));
let status = if looks_error {
"needs_review"
} else if looks_done {
"done"
} else if looks_negative {
"needs_review"
} else {
return None;
};
let summary_end = truncate_at_char_boundary(trimmed, 500);
let summary = trimmed[..summary_end].to_string();
let error =
(status == "needs_review").then(|| "agent returned plain text instead of JSON".to_string());
let files = extract_file_paths(trimmed);
let (accomplished, remaining) = extract_bullet_sections(trimmed);
Some(AgentResponse {
status: status.to_string(),
summary,
accomplished,
remaining,
files,
error,
input_tokens: None,
output_tokens: None,
learnings: vec![],
delegations: vec![],
screenshots: vec![],
screenshot_note: None,
})
}
pub(crate) fn shell_single_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
pub fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> usize {
if max_bytes >= s.len() {
return s.len();
}
let mut end = max_bytes;
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
end
}
#[derive(Debug, Clone, PartialEq)]
pub enum StreamEvent {
Started {
model: String,
},
Text(String),
Thinking(String),
ToolCall {
id: String,
name: String,
input: serde_json::Value,
},
ToolResult {
id: String,
name: String,
output: String,
is_error: bool,
},
Done(String),
Error(String),
}
pub(crate) fn json_str<'a>(v: &'a serde_json::Value, pointer: &str) -> &'a str {
v.pointer(pointer)
.and_then(serde_json::Value::as_str)
.unwrap_or("")
}
pub(crate) fn json_error_message(v: &serde_json::Value) -> String {
[
"/message",
"/error",
"/error/message",
"/error/data/message",
]
.iter()
.find_map(|p| v.pointer(p).and_then(serde_json::Value::as_str))
.unwrap_or("unknown error")
.to_string()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RouterTranscript {
Messages,
OpenCode,
Raw,
}
pub trait AgentRunner: Send + Sync {
#[cfg(test)]
fn name(&self) -> &str;
fn build_command(
&self,
model: Option<&str>,
timeout_cmd: &str,
sys_file: &str,
msg_file: &str,
permissions: &PermissionRules,
) -> String;
fn build_command_with_effort(
&self,
model: Option<&str>,
_effort: Option<&str>,
timeout_cmd: &str,
sys_file: &str,
msg_file: &str,
permissions: &PermissionRules,
) -> String {
self.build_command(model, timeout_cmd, sys_file, msg_file, permissions)
}
fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError>;
fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
Ok(raw.to_string())
}
fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent>;
fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError;
fn classify_error_with_elapsed(
&self,
exit_code: i32,
stdout: &str,
stderr: &str,
elapsed_secs: Option<u64>,
) -> AgentError {
let mut err = self.classify_error(exit_code, stdout, stderr);
if let AgentError::Timeout { elapsed } = &mut err
&& let Some(actual_elapsed) = elapsed_secs
{
*elapsed = Duration::from_secs(actual_elapsed);
}
err
}
fn available_models(&self) -> Vec<String> {
vec![]
}
fn free_models(&self) -> Vec<String> {
vec![]
}
fn router_transcript(&self) -> RouterTranscript {
RouterTranscript::Raw
}
fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command>;
}
pub fn supports_session(agent: &str) -> bool {
matches!(agent, "claude" | "kimi" | "minimax" | "grok")
}
const CLAUDE_COMPATIBLE_AGENTS: &[&str] = &["claude", "kimi", "minimax", "olm", "glm"];
pub fn is_claude_compatible(agent_name: &str) -> bool {
CLAUDE_COMPATIBLE_AGENTS.contains(&agent_name)
}
pub fn get_runner(agent_name: &str) -> Box<dyn AgentRunner> {
match agent_name {
"claude" => Box::new(claude::ClaudeRunner::new(agent_name)),
"kimi" => Box::new(kimi::KimiClaudeRunner::new()),
"minimax" => Box::new(minimax::MiniMaxClaudeRunner::new(agent_name)),
"codex" => Box::new(codex::CodexRunner),
"opencode" => Box::new(opencode::OpenCodeRunner::new()),
"grok" => Box::new(grok::GrokRunner),
other => {
if !CLAUDE_COMPATIBLE_AGENTS.contains(&other) {
tracing::warn!(
agent = other,
"unknown agent, using claude-compatible runner"
);
}
Box::new(claude::ClaudeRunner::new(other))
}
}
}
pub(crate) fn parse_ndjson(raw: &str) -> Vec<serde_json::Value> {
let events: Vec<serde_json::Value> = raw
.lines()
.filter(|line| !line.trim().is_empty())
.filter_map(|line| match serde_json::from_str(line) {
Ok(val) => Some(val),
Err(e) => {
tracing::debug!(line, error = %e, "skipping unparseable NDJSON line");
None
}
})
.collect();
if !events.is_empty() {
return events;
}
let acc: String = raw
.lines()
.filter(|line| {
let t = line.trim();
!t.is_empty() && !t.starts_with("//") && !t.starts_with('#')
})
.collect::<Vec<_>>()
.join(" ");
if acc.is_empty() {
return Vec::new();
}
if let Ok(val) = serde_json::from_str::<serde_json::Value>(acc.trim()) {
let stripped: String = acc.chars().filter(|c| !c.is_ascii_whitespace()).collect();
if let Ok(stripped_val) = serde_json::from_str::<serde_json::Value>(&stripped) {
if stripped_val == val {
return Vec::new();
}
}
return vec![val];
}
extract_json_objects(&acc)
}
fn extract_json_objects(text: &str) -> Vec<serde_json::Value> {
let mut results = Vec::new();
let mut start: Option<usize> = None;
let mut depth: i32 = 0;
let mut in_string = false;
let mut escape = false;
for (idx, ch) in text.char_indices() {
if let Some(start_idx) = start {
if in_string {
if escape {
escape = false;
} else if ch == '\\' {
escape = true;
} else if ch == '"' {
in_string = false;
}
continue;
}
match ch {
'"' => in_string = true,
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
let candidate = &text[start_idx..=idx];
if let Ok(val) = serde_json::from_str::<serde_json::Value>(candidate) {
results.push(val);
}
start = None;
}
}
_ => {}
}
continue;
}
if ch == '{' {
start = Some(idx);
depth = 1;
in_string = false;
escape = false;
}
}
results
}
pub(crate) fn login_env_vars(agent: &str) -> &'static [&'static str] {
match agent {
"claude" => &["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"],
"codex" => &["OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_ACCESS_TOKEN"],
"grok" => &["XAI_API_KEY"],
"kimi" => &["KIMI_API_KEY"],
"minimax" => &["MINIMAX_API_KEY"],
"glm" => &["GLM_API_KEY"],
_ => &[],
}
}
#[cfg(test)]
mod tests;