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