Skip to main content

orch/engine/agents/
grok.rs

1//! Grok agent runner.
2//!
3//! Headless Grok (`grok -p`) does not read the prompt from stdin. The task
4//! message is `--prompt-file`. The system prompt is passed with
5//! `--system-prompt-override`. Output is `streaming-messages-json`, the
6//! Messages API NDJSON shape, so parsing delegates to the Claude runner.
7//!
8//! ```bash
9//! grok --no-plan --no-wait-for-background \
10//!   --output-format streaming-messages-json \
11//!   --permission-mode bypassPermissions \
12//!   --sandbox off \
13//!   --deny 'Bash(rm *)' \
14//!   --system-prompt-override "$(cat "{sys_file}")" \
15//!   --prompt-file "{msg_file}"
16//! ```
17//!
18//! `--sandbox workspace` only writes the cwd. A worktree's git dir lives
19//! outside that cwd, and the CLI has no extra-dir flag, so task runs use
20//! `--sandbox off`. Orch still isolates the agent in the worktree and denies
21//! `rm` and `git push`. Control sessions (`deny_read_only`) use `read-only`.
22
23use std::iter;
24use std::time::Duration;
25
26use tokio::process::Command;
27
28use super::claude::{self, ClaudeRunner};
29use super::{
30    AgentError, AgentRunner, ParsedResponse, PermissionRules, SandboxLevel, StreamEvent,
31    shell_single_quote,
32};
33
34/// Grok waits this long for background tools when no timeout flag is passed
35const GROK_BACKGROUND_WAIT_SECS: u64 = 600;
36
37/// Runner for the `grok` CLI
38#[derive(Debug)]
39pub struct GrokRunner;
40
41impl GrokRunner {
42    fn parser() -> ClaudeRunner {
43        ClaudeRunner::new("grok")
44    }
45}
46
47impl AgentRunner for GrokRunner {
48    fn find_result(&self, ndjson: &str) -> Option<super::AgentResult> {
49        find_grok_result(ndjson)
50    }
51
52    #[cfg(test)]
53    fn name(&self) -> &'static str {
54        "grok"
55    }
56
57    fn stream_events(&self, event: &serde_json::Value) -> Vec<StreamEvent> {
58        claude::stream_events(event)
59    }
60
61    fn router_transcript(&self) -> super::RouterTranscript {
62        super::RouterTranscript::Messages
63    }
64
65    fn extract_text(&self, raw: &str) -> Result<String, AgentError> {
66        Self::parser().extract_text(raw)
67    }
68
69    fn build_command(
70        &self,
71        model: Option<&str>,
72        timeout_cmd: &str,
73        sys_file: &str,
74        msg_file: &str,
75        permissions: &PermissionRules,
76    ) -> String {
77        let sq_sys = shell_single_quote(sys_file);
78        let sq_msg = shell_single_quote(msg_file);
79        let mut args = Vec::new();
80        if !timeout_cmd.is_empty() {
81            args.push(timeout_cmd.to_string());
82        }
83        args.push("grok".to_string());
84        args.push("--no-plan".to_string());
85        // Leftover background tool calls wait 600s, then grok exits 1 and the task blocks
86        args.push("--no-wait-for-background".to_string());
87        args.push("--output-format".to_string());
88        args.push("streaming-messages-json".to_string());
89        args.push("--permission-mode".to_string());
90        args.push(permission_mode(permissions).to_string());
91        args.push("--sandbox".to_string());
92        args.push(sandbox_profile(permissions).to_string());
93        if let Some(model) = model.filter(|m| !m.is_empty()) {
94            args.push("--model".to_string());
95            args.push(shell_single_quote(model));
96        }
97        args.extend(permission_args(permissions));
98        args.push("--system-prompt-override".to_string());
99        args.push(format!("\"$(cat {sq_sys})\""));
100        args.push("--prompt-file".to_string());
101        args.push(sq_msg);
102        args.join(" ")
103    }
104
105    fn parse_response(&self, raw: &str) -> Result<ParsedResponse, AgentError> {
106        Self::parser().parse_response(raw)
107    }
108
109    fn classify_error(&self, exit_code: i32, stdout: &str, stderr: &str) -> AgentError {
110        let extracted = startup_errors(stdout);
111        for message in extracted
112            .iter()
113            .map(String::as_str)
114            .chain(iter::once(stdout))
115            .chain(iter::once(stderr))
116        {
117            if let Some(err) = classify_grok_message(message) {
118                return err;
119            }
120        }
121        let stderr = if extracted.is_empty() {
122            stderr.to_string()
123        } else {
124            format!("{stderr}\n{}", extracted.join("\n"))
125        };
126        Self::parser().classify_error(exit_code, stdout, &stderr)
127    }
128
129    fn router_command(&self, prompt: &str, model: Option<&str>) -> anyhow::Result<Command> {
130        // Classification only needs a JSON answer. One leftover tool call
131        // spends `--max-turns 1` and grok exits with max turns reached
132        let mut cmd = Command::new("grok");
133        cmd.arg("--no-plan")
134            .arg("--no-subagents")
135            .arg("--disable-web-search")
136            .arg("--max-turns")
137            .arg("1")
138            .arg("--output-format")
139            .arg("streaming-messages-json")
140            .arg("--permission-mode")
141            .arg("dontAsk")
142            .arg("--disallowed-tools")
143            .arg(ROUTER_DISALLOWED_TOOLS);
144        if let Some(model) = model.filter(|m| !m.is_empty()) {
145            cmd.arg("--model").arg(model);
146        }
147        cmd.arg("-p").arg(prompt);
148        Ok(cmd)
149    }
150}
151
152/// `streaming-messages-json` result, plus Grok's cost and stop reason
153pub fn find_grok_result(ndjson: &str) -> Option<super::AgentResult> {
154    let mut result = claude::find_claude_result(ndjson)?;
155    let Some((line, _)) = claude::find_ndjson_result_line(ndjson.trim()) else {
156        return Some(result);
157    };
158    let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
159        return Some(result);
160    };
161    if result.cost_usd.is_none() {
162        result.cost_usd = val
163            .get("total_cost_usd")
164            .and_then(serde_json::Value::as_f64);
165    }
166    if val.get("stop_reason").and_then(|v| v.as_str()) == Some("max_tokens") {
167        result.truncated_by_length = true;
168    }
169    Some(result)
170}
171
172fn permission_mode(permissions: &PermissionRules) -> &'static str {
173    if permissions.autonomous {
174        "bypassPermissions"
175    } else if permissions.deny_read_only {
176        "dontAsk"
177    } else {
178        "acceptEdits"
179    }
180}
181
182fn sandbox_profile(permissions: &PermissionRules) -> &'static str {
183    // Grok's own Seatbelt profile cannot start inside the OS sandbox, which already limits it
184    if permissions.sandbox == SandboxLevel::Os {
185        "off"
186    } else if permissions.deny_read_only {
187        "read-only"
188    } else {
189        "off"
190    }
191}
192
193/// Tools the grok router must not expose. One tool call spends `--max-turns 1`
194const ROUTER_DISALLOWED_TOOLS: &str = concat!(
195    "read_file,grep,list_dir,search_replace,write,run_terminal_cmd,",
196    "web_search,web_fetch,task,todo_write,monitor,search_tool,use_tool,",
197    "workflow,enter_plan_mode,exit_plan_mode,ask_user_question,",
198    "send_feedback,image_gen,image_edit,image_to_video,reference_to_video"
199);
200
201/// Claude tool names that map to a Grok tool id for `--tools` / `--disallowed-tools`
202fn grok_tool_id(name: &str) -> Option<&'static str> {
203    Some(match name {
204        "Read" => "read_file",
205        "Grep" => "grep",
206        "Glob" => "list_dir",
207        "Edit" => "search_replace",
208        "Write" => "write",
209        "Bash" => "run_terminal_cmd",
210        "WebFetch" => "web_fetch",
211        "WebSearch" => "web_search",
212        "Task" => "task",
213        "TodoWrite" => "todo_write",
214        _ => return None,
215    })
216}
217
218fn permission_args(permissions: &PermissionRules) -> Vec<String> {
219    if !permissions.allowed_tools.is_empty() {
220        return allow_args(permissions);
221    }
222    deny_args(&permissions.disallowed_tools)
223}
224
225fn allow_args(permissions: &PermissionRules) -> Vec<String> {
226    let mut tools = Vec::new();
227    let mut allows = Vec::new();
228    for item in &permissions.allowed_tools {
229        if let Some(id) = grok_tool_id(item) {
230            if !tools.contains(&id) {
231                tools.push(id);
232            }
233            if (item == "Edit" || item == "Write") && !permissions.allowed_edit_paths.is_empty() {
234                for path in &permissions.allowed_edit_paths {
235                    allows.push(format!("{item}({}/**)", path.display()));
236                }
237            }
238        } else if item.chars().next().is_some_and(|c| c.is_ascii_lowercase()) {
239            // CLI command names become shell allow rules. PascalCase leftovers
240            // such as Skill are Claude-only tools, not shell commands
241            allows.push(format!("Bash({item} *)"));
242        }
243    }
244    // An allowlist does not express the rm / git-push bans. Keep those denies.
245    let mut args = Vec::new();
246    if !tools.is_empty() {
247        args.push("--tools".to_string());
248        args.push(shell_single_quote(&tools.join(",")));
249    }
250    for rule in allows {
251        args.push("--allow".to_string());
252        args.push(shell_single_quote(&rule));
253    }
254    args.extend(deny_args(&permissions.disallowed_tools));
255    args
256}
257
258fn deny_args(rules: &[String]) -> Vec<String> {
259    let mut remove = Vec::new();
260    let mut denies = Vec::new();
261    for rule in rules {
262        match rule.as_str() {
263            "Read" | "Grep" | "Glob" | "Edit" | "Write" | "Bash" => {
264                if let Some(id) = grok_tool_id(rule)
265                    && !remove.contains(&id)
266                {
267                    remove.push(id);
268                }
269            }
270            _ => denies.push(rule.as_str()),
271        }
272    }
273    let mut args = Vec::new();
274    if !remove.is_empty() {
275        args.push("--disallowed-tools".to_string());
276        args.push(shell_single_quote(&remove.join(",")));
277    }
278    for rule in denies {
279        args.push("--deny".to_string());
280        args.push(shell_single_quote(rule));
281    }
282    args
283}
284
285/// `type:error` messages. These are startup failures, not assistant prose.
286fn startup_errors(stdout: &str) -> Vec<String> {
287    let mut out = Vec::new();
288    for line in stdout.lines() {
289        let line = line.trim();
290        if line.is_empty() {
291            continue;
292        }
293        let Ok(val) = serde_json::from_str::<serde_json::Value>(line) else {
294            continue;
295        };
296        if val.get("type").and_then(|t| t.as_str()) != Some("error") {
297            continue;
298        }
299        if let Some(message) = val.get("message").and_then(|m| m.as_str())
300            && !message.is_empty()
301        {
302            out.push(message.to_string());
303        }
304    }
305    out
306}
307
308/// Grok phrases the shared classifier does not already name
309fn classify_grok_message(message: &str) -> Option<AgentError> {
310    let lower = message.to_lowercase();
311    if lower.contains("not logged in")
312        || lower.contains("please log in")
313        || lower.contains("grok login")
314        || lower.contains("xai_api_key")
315        || lower.contains("authentication failed")
316        || lower.contains("could not refresh")
317    {
318        return Some(AgentError::Auth {
319            message: message.to_string(),
320        });
321    }
322    if lower.contains("permission required") {
323        return Some(AgentError::PermissionDenied {
324            message: message.to_string(),
325        });
326    }
327    if lower.contains("the wait for background work ran out") {
328        return Some(AgentError::Timeout {
329            elapsed: Duration::from_secs(GROK_BACKGROUND_WAIT_SECS),
330        });
331    }
332    None
333}
334
335#[cfg(test)]
336mod tests {
337    use std::path::PathBuf;
338
339    use super::*;
340    use crate::engine::runner::parse_session_output;
341    use crate::engine::runner::session::SessionOutput;
342
343    fn runner() -> GrokRunner {
344        GrokRunner
345    }
346
347    fn perms(autonomous: bool, disallowed: &[&str], allowed: &[&str]) -> PermissionRules {
348        PermissionRules {
349            autonomous,
350            sandbox: SandboxLevel::WorkspaceWrite,
351            disallowed_tools: disallowed.iter().map(|s| (*s).to_string()).collect(),
352            allowed_tools: allowed.iter().map(|s| (*s).to_string()).collect(),
353            allowed_edit_paths: vec![],
354            deny_read_only: false,
355            extra_writable_dirs: vec![],
356        }
357    }
358
359    #[test]
360    fn grok_s_own_sandbox_is_off_inside_the_os_sandbox() {
361        let chat = PermissionRules {
362            deny_read_only: true,
363            ..PermissionRules::default()
364        };
365        assert_eq!(sandbox_profile(&chat), "read-only");
366        let sandboxed_chat = PermissionRules {
367            sandbox: SandboxLevel::Os,
368            ..chat
369        };
370        assert_eq!(sandbox_profile(&sandboxed_chat), "off");
371    }
372
373    #[test]
374    fn build_command_autonomous_denies_rm_and_passes_files() {
375        let cmd = runner().build_command(
376            Some("fast"),
377            "timeout 1800",
378            "/tmp/sys.txt",
379            "/tmp/msg.txt",
380            &perms(true, &["Bash(rm *)", "Bash(git push*)"], &[]),
381        );
382        assert!(cmd.starts_with("timeout 1800 grok "), "{cmd}");
383        assert!(cmd.contains("--model 'fast'"), "{cmd}");
384        assert!(
385            cmd.contains("--output-format streaming-messages-json"),
386            "{cmd}"
387        );
388        assert!(cmd.contains("--permission-mode bypassPermissions"), "{cmd}");
389        assert!(cmd.contains("--sandbox off"), "{cmd}");
390        assert!(cmd.contains("--no-plan"), "{cmd}");
391        assert!(cmd.contains("--no-wait-for-background"), "{cmd}");
392        assert!(cmd.contains("--deny 'Bash(rm *)'"), "{cmd}");
393        assert!(cmd.contains("--deny 'Bash(git push*)'"), "{cmd}");
394        assert!(cmd.contains("--prompt-file '/tmp/msg.txt'"), "{cmd}");
395        assert!(
396            cmd.contains("--system-prompt-override \"$(cat '/tmp/sys.txt')\""),
397            "{cmd}"
398        );
399        assert!(!cmd.contains("< "), "{cmd}");
400    }
401
402    #[test]
403    fn build_command_omits_empty_model() {
404        let cmd = runner().build_command(
405            Some(""),
406            "",
407            "/tmp/sys.txt",
408            "/tmp/msg.txt",
409            &perms(true, &[], &[]),
410        );
411        assert!(!cmd.contains("--model"), "{cmd}");
412    }
413
414    #[test]
415    fn build_command_supervised_accepts_edits() {
416        let cmd = runner().build_command(
417            None,
418            "",
419            "/tmp/sys.txt",
420            "/tmp/msg.txt",
421            &perms(false, &[], &[]),
422        );
423        assert!(cmd.contains("--permission-mode acceptEdits"), "{cmd}");
424    }
425
426    #[test]
427    fn build_command_read_only_removes_read_tools() {
428        let rules = PermissionRules::deny_read_only();
429        let cmd = runner().build_command(None, "", "/tmp/sys.txt", "/tmp/msg.txt", &rules);
430        assert!(cmd.contains("--sandbox read-only"), "{cmd}");
431        assert!(cmd.contains("--permission-mode bypassPermissions"), "{cmd}");
432        assert!(cmd.contains("read_file"), "{cmd}");
433        assert!(cmd.contains("grep"), "{cmd}");
434        assert!(cmd.contains("list_dir"), "{cmd}");
435        assert!(cmd.contains("--deny 'Bash(cat *)'"), "{cmd}");
436    }
437
438    #[test]
439    fn build_command_allowlist_keeps_destructive_denies() {
440        let mut rules = perms(true, &["Bash(rm *)"], &["Edit", "Write", "Bash", "git"]);
441        rules.allowed_edit_paths = vec![PathBuf::from("/work/tree")];
442        let cmd = runner().build_command(None, "", "/tmp/sys.txt", "/tmp/msg.txt", &rules);
443        assert!(
444            cmd.contains("--tools 'search_replace,write,run_terminal_cmd'"),
445            "{cmd}"
446        );
447        assert!(cmd.contains("--allow 'Edit(/work/tree/**)'"), "{cmd}");
448        assert!(cmd.contains("--allow 'Write(/work/tree/**)'"), "{cmd}");
449        assert!(cmd.contains("--allow 'Bash(git *)'"), "{cmd}");
450        assert!(cmd.contains("--deny 'Bash(rm *)'"), "{cmd}");
451    }
452
453    #[test]
454    fn parse_response_reads_messages_result() {
455        let raw = concat!(
456            r#"{"type":"system","subtype":"init","model":"test"}"#,
457            "\n",
458            r#"{"type":"result","subtype":"success","is_error":false,"result":"{\"status\":\"done\",\"summary\":\"shipped\",\"accomplished\":[\"a\"],\"remaining\":[],\"files\":[]}","usage":{"input_tokens":8,"output_tokens":3},"total_cost_usd":0.02,"duration_ms":40,"stop_reason":"end_turn"}"#,
459            "\n",
460        );
461        let parsed = runner().parse_response(raw).expect("parse");
462        assert_eq!(parsed.response.status, "done");
463        assert_eq!(parsed.response.summary, "shipped");
464        assert_eq!(parsed.input_tokens, Some(8));
465        assert_eq!(parsed.output_tokens, Some(3));
466    }
467
468    #[test]
469    fn find_result_reads_cost_and_max_tokens() {
470        let raw = r#"{"type":"result","subtype":"success","is_error":false,"result":"partial","usage":{"input_tokens":1,"output_tokens":2},"total_cost_usd":1.5,"stop_reason":"max_tokens"}"#;
471        let result = find_grok_result(raw).expect("result");
472        assert_eq!(result.result_text, "partial");
473        assert_eq!(result.cost_usd, Some(1.5));
474        assert!(result.truncated_by_length);
475        assert_eq!(result.input_tokens, Some(1));
476    }
477
478    #[test]
479    fn classify_error_rate_limit_from_error_event() {
480        let stdout = r#"{"type":"error","message":"429 Too Many Requests"}"#;
481        let err = runner().classify_error(1, stdout, "");
482        assert!(matches!(err, AgentError::RateLimit { .. }), "{err}");
483    }
484
485    #[test]
486    fn classify_error_model_unavailable() {
487        let stdout = r#"{"type":"error","message":"The model `missing` is not supported"}"#;
488        let err = runner().classify_error(1, stdout, "");
489        match err {
490            AgentError::ModelUnavailable { model, .. } => assert_eq!(model, "missing"),
491            other => panic!("expected model unavailable, got {other}"),
492        }
493    }
494
495    #[test]
496    fn classify_error_login_is_auth() {
497        let stdout = r#"{"type":"error","message":"Not logged in. Run grok login."}"#;
498        let err = runner().classify_error(1, stdout, "");
499        assert!(matches!(err, AgentError::Auth { .. }), "{err}");
500    }
501
502    #[test]
503    fn classify_error_permission_required() {
504        let stdout =
505            r#"{"type":"error","message":"permission required: Edit calc.py was not run"}"#;
506        let err = runner().classify_error(1, stdout, "");
507        assert!(matches!(err, AgentError::PermissionDenied { .. }), "{err}");
508    }
509
510    #[test]
511    fn router_command_disallows_leftover_tools() {
512        let cmd = runner()
513            .router_command("classify this task", None)
514            .expect("router command");
515        let args: Vec<String> = cmd
516            .as_std()
517            .get_args()
518            .map(|a| a.to_string_lossy().into_owned())
519            .collect();
520        let disallowed = args
521            .windows(2)
522            .find(|pair| pair[0] == "--disallowed-tools")
523            .map(|pair| pair[1].as_str())
524            .expect("disallowed-tools flag");
525        for tool in ["search_tool", "use_tool", "todo_write", "workflow"] {
526            assert!(
527                disallowed.split(',').any(|name| name == tool),
528                "{tool} missing from {disallowed}"
529            );
530        }
531    }
532
533    #[test]
534    fn classify_error_background_wait_expiry_is_timeout() {
535        let stdout = r#"{"type":"error","message":"the wait for background work ran out after 600 s and exit stopped 1 background task. Pass --background-wait-timeout <secs> to wait longer, or --no-wait-for-background to exit as soon as the prompt's turn ends"}"#;
536        let err = runner().classify_error(1, stdout, "");
537        assert!(matches!(err, AgentError::Timeout { .. }), "{err}");
538    }
539
540    #[test]
541    fn parse_session_output_background_wait_envelope_is_timeout() {
542        let ndjson = r#"{"type":"result","subtype":"error_during_execution","is_error":true,"num_turns":12,"errors":["the wait for background work ran out after 600 s and exit stopped 1 background task. Pass --background-wait-timeout <secs> to wait longer, or --no-wait-for-background to exit as soon as the prompt's turn ends"],"costUSD":2.01,"usage":{"input_tokens":100,"output_tokens":50}}"#;
543        let session = SessionOutput {
544            exit_code: 1,
545            raw_stdout: ndjson.to_string(),
546            raw_stderr: String::new(),
547            elapsed_secs: Some(1313),
548            sandbox_error: None,
549        };
550        let err = parse_session_output("489522", "grok", &runner(), &session)
551            .expect_err("background-wait expiry should be an error");
552        match err {
553            AgentError::Timeout { elapsed } => {
554                assert_eq!(elapsed, Duration::from_secs(1313));
555            }
556            other => panic!("expected Timeout, got {other}"),
557        }
558    }
559}