Skip to content
Back to search

agent-designer

Portable SKILLs workspace for Claude Code, Codex, and Gemini — issue-driven workflows and cross-agent collaboration via bridge scripts with session continuity.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/appautomaton--agent-designer/badge.svg)](/listings/appautomaton--agent-designer)

HTML

<a href="/listings/appautomaton--agent-designer"><img src="/api/listings/appautomaton--agent-designer/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

> [!TIP] > 1) Pick the skills you want from `skills/`. > 2) Follow the runbook for your harness in [`docs/setup/`](docs/setup/README.md): install, approve, verify. > - To add the issue-driven workflow to a project: ask your agent to "apply `AGENTS.issues.template.md` on top of `AGENTS.md`". > 3) Start working. Ask your agent to create a plan, generate an Issue CSV, or collaborate with another agent. > - Example: "Create a plan and Issue CSV for <goal>."

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 69 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. Language: English | [中文](README.zh-CN.md)
  2. # Agent Designer
  3. A catalog of installable skills for AI coding agents: Claude Code, Codex, Antigravity, and Grok.
  4. Structured, reusable skills that give your agents clear workflows, safe defaults, and multi-turn collaboration capabilities. Install the ones you want into the harness you already use, and your agents work methodically rather than freestyle.
  5. ## What's inside
  6. **Collaboration skills** — let your agents delegate to each other via bridge scripts with session continuity:
  7. | Skill | Purpose |
  8. |---|---|
  9. | `collaborating-with-claude` | Delegate to Claude Code CLI (review, diff, consultation) |
  10. | `collaborating-with-antigravity` | Delegate to Antigravity CLI `agy` (review, web search, image analysis) |
  11. | `collaborating-with-codex` | Delegate to Codex CLI (implementation, diagnosis, review, image generation) |
  12. | `collaborating-with-grok` | Delegate to Grok CLI (review, diagnosis, live web/X search; coding model e.g. `grok-4.5`) |
  13. **Issue-driven development** — structure work into plans and trackable Issue CSVs:
  14. | Skill | Purpose |
  15. |---|---|
  16. | `issue-driven-workflow` | Plan → Issue CSV → autonomous execution with status tracking |
  17. ## Getting started
  18. > [!TIP]
  19. > 1) Pick the skills you want from `skills/`.
  20. > 2) Follow the runbook for your harness in [`docs/setup/`](docs/setup/README.md): install, approve, verify.
  21. > - To add the issue-driven workflow to a project: ask your agent to "apply `AGENTS.issues.template.md` on top of `AGENTS.md`".
  22. > 3) Start working. Ask your agent to create a plan, generate an Issue CSV, or collaborate with another agent.
  23. > - Example: "Create a plan and Issue CSV for <goal>."
  24. ## Project structure
  25. ```
  26. skills/ ← skill source (the real content)
  27. collaborating-with-claude/ ← bridge script + SKILL.md + references
  28. collaborating-with-antigravity/ ← bridge script + SKILL.md + references (agy; succeeds the retired Gemini CLI)
  29. collaborating-with-codex/ ← bridge script + SKILL.md + references + prompt recipes
  30. collaborating-with-grok/ ← bridge script + SKILL.md + references (Grok CLI; live web/X search)
  31. issue-driven-workflow/ ← plan/CSV workflow + templates + scripts
  32. docs/setup/ ← install runbooks per harness
  33. AGENTS.md ← project-specific rules
  34. AGENTS.issues.template.md ← issue-driven workflow (apply on top of AGENTS.md)
  35. ```
  36. ## How it works
  37. Each skill follows **progressive disclosure**:
  38. - **Level 1 (metadata)** — `name` + `description` in YAML frontmatter. Always loaded. Used for discovery.
  39. - **Level 2 (instructions)** — the SKILL.md body. Loaded when the skill is invoked. Contains workflow, safety, quick start.
  40. - **Level 3 (resources)** — `scripts/`, `references/`, `assets/`. Loaded on demand. Contains deep docs, templates, helper scripts.
  41. ## Notes
  42. - This repo is workflow-first — most changes are text, not code.
  43. - Bridge scripts wrap CLI tools and return structured JSON with session continuity.
  44. - Approval rules for the bridge scripts are documented per harness in [`docs/setup/`](docs/setup/README.md), in wildcard forms that work at any install location. See the "Host-side approval" section in each skill.
  45. - Skills are portable across Codex and Claude Code with minimal adaptation.
  46. - If invoking bridge scripts directly, prefer `python3`.
  47. ## Acknowledgements
  48. Inspired by:
  49. - [anthropics/skills](https://github.com/anthropics/skills)
  50. - [GuDaStudio/skills](https://github.com/GuDaStudio/skills)
skills/collaborating-with-antigravity/scripts/agy_bridge.py · Bundled script · 428 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """
  3. Antigravity CLI Bridge Script.
  4. Wraps the Antigravity CLI (`agy --print`) to provide a JSON interface, live
  5. stderr progress, and multi-turn continuity via SESSION_ID.
  6. Antigravity CLI is Google's replacement for the retired Gemini CLI. Quirks of
  7. `agy` shape this bridge and are worked around here:
  8. 1. No surfaced conversation ID. `agy -p` never prints the conversation ID and
  9. has no `--session-id`. We recover it from
  10. `~/.gemini/antigravity-cli/cache/last_conversations.json`, which maps the
  11. workspace abspath -> conversation UUID, and resume via `--conversation`.
  12. (Upstream: antigravity-cli issue #7.)
  13. 2. No structured output. We capture agy's plain text under a pseudo-terminal
  14. (pty), strip ANSI, return JSON, and enforce our own wall-clock kill. (The
  15. historical non-TTY stdout hang, issue #76, is fixed upstream; the pty is
  16. kept as cheap insurance.)
  17. Because `agy` rewrites that cache on every run, concurrent runs would race ID
  18. recovery; the bridge serializes with an advisory file lock. Verified against
  19. `agy` (Antigravity CLI) v1.0.16 on macOS.
  20. """
  21. from __future__ import annotations
  22. import argparse
  23. import json
  24. import os
  25. import re
  26. import select
  27. import shutil
  28. import signal
  29. import subprocess
  30. import sys
  31. import time
  32. from pathlib import Path
  33. from typing import Any, Dict, List, Optional, Tuple
  34. # Control sequences agy emits even in print mode (no --no-color flag exists):
  35. # CSI/OSC escapes, single-char escapes, and lone control bytes (keep \t \n).
  36. ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*\x07|\x1b[=>]|[\x00-\x08\x0b\x0c\x0e-\x1f]")
  37. CACHE_REL = ".gemini/antigravity-cli/cache/last_conversations.json"
  38. CONV_DIR_REL = ".gemini/antigravity-cli/conversations"
  39. AGY_HOME_REL = ".gemini/antigravity-cli"
  40. def emit_json(result: Dict[str, Any], exit_code: int = 0) -> None:
  41. print(json.dumps(result, indent=2, ensure_ascii=False))
  42. raise SystemExit(exit_code)
  43. def find_executable(name: str) -> str:
  44. found = shutil.which(name)
  45. return found if found else name
  46. def list_models() -> Tuple[List[str], Optional[str]]:
  47. """Return (models, error) from `agy models`. Pipe-safe, unlike `agy -p`."""
  48. try:
  49. proc = subprocess.run(
  50. [find_executable("agy"), "models"],
  51. stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=30,
  52. )
  53. except (OSError, subprocess.SubprocessError) as exc:
  54. return [], f"Failed to run `agy models`: {exc}"
  55. if proc.returncode != 0:
  56. return [], proc.stderr.strip() or f"`agy models` exited {proc.returncode}."
  57. models = [line.strip() for line in proc.stdout.splitlines() if line.strip()]
  58. return (models, None) if models else ([], "`agy models` returned no models.")
  59. def parse_duration(text: str) -> Optional[float]:
  60. """Parse Go-style durations like '5m', '90s', '5m0s', or bare seconds."""
  61. text = text.strip().lower()
  62. if not text:
  63. return None
  64. if text.isdigit():
  65. return float(text)
  66. total = 0.0
  67. matched = False
  68. for value, unit in re.findall(r"(\d+(?:\.\d+)?)([hms])", text):
  69. matched = True
  70. total += float(value) * {"h": 3600, "m": 60, "s": 1}[unit]
  71. return total if matched else None
  72. def strip_ansi(raw: str) -> List[str]:
  73. """Strip control sequences and spinner redraws; return non-empty lines."""
  74. clean = ANSI_RE.sub("", raw)
  75. clean = re.sub(r"[ \t]*\r", "\n", clean) # treat carriage returns as newlines
  76. return [line.rstrip() for line in clean.splitlines() if line.strip()]
  77. def preflight_check(cd: Path, warnings: List[str]) -> Optional[str]:
  78. if os.name != "posix":
  79. return "agy_bridge requires a POSIX system (it allocates a pty); not supported on this OS."
  80. if shutil.which("agy") is None:
  81. return "Antigravity CLI not found in PATH. Install it (`curl -fsSL https://antigravity.google/cli/install.sh | bash`) and ensure `agy` is available."
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 101 on GitHub
  82. if not cd.exists():
  83. return f"Workspace root `{cd.absolute().as_posix()}` does not exist."
  84. if not cd.is_dir():
  85. return f"Workspace root `{cd.absolute().as_posix()}` is not a directory."
  86. if not (Path.home() / AGY_HOME_REL).is_dir():
  87. warnings.append(
  88. "Antigravity CLI has never run on this host (~/.gemini/antigravity-cli/ missing). "
  89. "Run `agy` once and sign in with Google, or the call may hang on auth."
  90. )
  91. return None
  92. def acquire_lock() -> Optional[Any]:
  93. """Serialize bridge runs so concurrent agy invocations don't race the cache."""
  94. try:
  95. import fcntl
  96. except ImportError:
  97. return None
  98. lock_dir = Path.home() / ".gemini/antigravity-cli/cache"
  99. try:
  100. lock_dir.mkdir(parents=True, exist_ok=True)
  101. lock_path = lock_dir / ".agy_bridge.lock"
  102. except OSError:
  103. lock_path = Path("/tmp/.agy_bridge.lock")
  104. handle = open(lock_path, "w")
  105. fcntl.flock(handle.fileno(), fcntl.LOCK_EX)
  106. return handle
  107. def release_lock(handle: Optional[Any]) -> None:
  108. if handle is None:
  109. return
  110. try:
  111. import fcntl
  112. fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
  113. except Exception:
  114. pass
  115. finally:
  116. handle.close()
  117. def build_command(args: argparse.Namespace, prompt: str) -> List[str]:
  118. cmd = ["agy", "-p", prompt]
  119. if args.model:
  120. cmd.extend(["--model", args.model])
  121. if args.sandbox:
  122. cmd.append("--sandbox")
  123. if args.skip_permissions:
  124. cmd.append("--dangerously-skip-permissions")
  125. for extra_dir in args.add_dir:
  126. cmd.extend(["--add-dir", extra_dir])
  127. if args.print_timeout:
  128. cmd.extend(["--print-timeout", args.print_timeout])
  129. if args.log_file:
  130. cmd.extend(["--log-file", args.log_file])
  131. if args.SESSION_ID:
  132. cmd.extend(["--conversation", args.SESSION_ID])
  133. elif args.continue_session:
  134. cmd.append("-c")
  135. return cmd
  136. def run_agy_pty(
  137. cmd: List[str], cwd: Path, wall_timeout: float, start_time: float
  138. ) -> Tuple[str, int, bool]:
  139. """Run agy under a pty, forward cleaned output to stderr, return (raw, rc, timed_out)."""
  140. import pty
  141. def status(message: str) -> None:
  142. elapsed = time.time() - start_time
  143. print(f"[agy {elapsed:5.1f}s] {message}", file=sys.stderr, flush=True)
  144. resolved = cmd.copy()
  145. resolved[0] = find_executable(cmd[0])
  146. master, slave = pty.openpty()
  147. proc = subprocess.Popen(
  148. resolved,
  149. stdin=subprocess.DEVNULL,
  150. stdout=slave,
  151. stderr=slave,
  152. cwd=str(cwd),
  153. close_fds=True,
  154. start_new_session=True,
  155. )
  156. os.close(slave)
  157. status(f"Started agy (pid {proc.pid}); waiting for response…")
  158. chunks: List[bytes] = []
  159. pending = "" # partial line buffer for progress forwarding
  160. saw_output = False
  161. timed_out = False
  162. def forward(text: str, flush_all: bool = False) -> None:
  163. nonlocal pending
  164. pending += text
  165. *lines, pending = pending.split("\n")
  166. if flush_all and pending:
  167. lines.append(pending)
  168. pending = ""
  169. for line in lines:
  170. for clean in strip_ansi(line):
  171. status(clean[:200])
  172. while True:
  173. if time.time() - start_time > wall_timeout:
  174. timed_out = True
  175. status(f"Wall-clock timeout after {wall_timeout:g}s; killing agy")
  176. _killpg(proc)
  177. break
  178. try:
  179. ready, _, _ = select.select([master], [], [], 0.5)
  180. except (OSError, ValueError):
  181. break
  182. if master in ready:
  183. try:
  184. data = os.read(master, 65536)
  185. except OSError: # EIO on Linux once the child exits
  186. break
  187. if not data:
  188. break
  189. if not saw_output:
  190. saw_output = True
  191. status("Receiving output…")
  192. chunks.append(data)
  193. forward(data.decode("utf-8", "replace"))
  194. elif proc.poll() is not None:
  195. try: # drain anything left in the pty buffer
  196. while True:
  197. data = os.read(master, 65536)
  198. if not data:
  199. break
  200. chunks.append(data)
  201. except OSError:
  202. pass
  203. break
  204. forward("", flush_all=True)
  205. try:
  206. returncode = proc.wait(timeout=5)
  207. except subprocess.TimeoutExpired:
  208. _killpg(proc)
  209. returncode = proc.wait()
  210. try:
  211. os.close(master)
  212. except OSError:
  213. pass
  214. raw = b"".join(chunks).decode("utf-8", "replace")
  215. return raw, returncode, timed_out
  216. def _killpg(proc: subprocess.Popen) -> None:
  217. try:
  218. os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
  219. except (ProcessLookupError, PermissionError):
  220. try:
  221. proc.kill()
  222. except ProcessLookupError:
  223. pass
  224. def recover_session_id(cd: Path, start_time: float) -> Tuple[Optional[str], Optional[str]]:
  225. """Recover the conversation UUID for this workspace; return (id, db_path)."""
  226. cache_path = Path.home() / CACHE_REL
  227. cd_abs = str(cd.resolve())
  228. conv_id: Optional[str] = None
  229. try:
  230. mapping = json.loads(cache_path.read_text(encoding="utf-8"))
  231. if isinstance(mapping, dict):
  232. conv_id = mapping.get(cd_abs) or mapping.get(cd.absolute().as_posix())
  233. except (OSError, json.JSONDecodeError):
  234. pass
  235. conv_dir = Path.home() / CONV_DIR_REL
  236. if conv_id:
  237. db = conv_dir / f"{conv_id}.db"
  238. return conv_id, (str(db) if db.is_file() else None)
  239. # Fallback: newest .db touched since this run began.
  240. try:
  241. candidates = [
  242. p for p in conv_dir.glob("*.db") if p.stat().st_mtime >= start_time - 1
  243. ]
  244. if candidates:
  245. newest = max(candidates, key=lambda p: p.stat().st_mtime)
  246. return newest.stem, str(newest)
  247. except OSError:
  248. pass
  249. return None, None
  250. def parse_args() -> argparse.Namespace:
  251. parser = argparse.ArgumentParser(description="Antigravity CLI (agy) Bridge")
  252. parser.add_argument("--PROMPT", default="", help="Instruction to send to agy. Use this or --prompt-file.")
  253. parser.add_argument("--prompt-file", type=Path, default=None, help="Read the prompt from a file (avoids argv/shell-quoting limits).")
  254. parser.add_argument("--cd", type=Path, default=None, help="Workspace root for agy (required unless --list-models).")
  255. parser.add_argument("--list-models", action="store_true", help="Print models from `agy models` as JSON and exit (no prompt/cd needed).")
  256. session_group = parser.add_mutually_exclusive_group()
  257. session_group.add_argument("--SESSION_ID", default="", help="Resume a conversation by ID (maps to `agy --conversation`).")
  258. session_group.add_argument("--continue", dest="continue_session", action="store_true", help="Continue the most recent conversation (maps to `agy -c`).")
  259. parser.add_argument("--model", default="", help='Model name from `agy models`, e.g. "Gemini 3.5 Flash (Low)" or "Claude Sonnet 4.6 (Thinking)".')
  260. parser.add_argument("--no-validate-model", action="store_true", help="Skip validating --model against `agy models` (agy does not validate; unknown names silently fall back to the default).")
  261. parser.add_argument("--sandbox", action=argparse.BooleanOptionalAction, default=True, help="Run agy with terminal restrictions (default: on). Use --no-sandbox to allow shell/tools.")
  262. parser.add_argument("--skip-permissions", action="store_true", help="Pass --dangerously-skip-permissions (auto-approve tools). Use only with explicit consent.")
  263. parser.add_argument("--add-dir", action="append", default=[], help="Add a directory to the workspace (repeatable).")
  264. parser.add_argument("--print-timeout", default="5m", help="agy print-mode wait, e.g. '5m' or '90s' (default 5m). Note: agy may ignore this; --timeout is the real cap.")
  265. parser.add_argument("--log-file", default="", help="Override agy's log file path.")
  266. parser.add_argument("--timeout", type=float, default=0, help="Bridge wall-clock kill, in seconds. Default: print-timeout + 120s buffer.")
  267. parser.add_argument("--return-all-messages", action="store_true", help="Include raw captured output and the conversation .db path.")
  268. return parser.parse_args()
  269. def main() -> None:
  270. args = parse_args()
  271. warnings: List[str] = []
  272. if args.list_models:
  273. if shutil.which("agy") is None:
  274. emit_json({"success": False, "error": "Antigravity CLI not found in PATH. Install it and ensure `agy` is available."}, exit_code=1)
  275. models, err = list_models()
  276. if err:
  277. emit_json({"success": False, "error": err}, exit_code=1)
  278. emit_json({"success": True, "models": models})
  279. if args.cd is None:
  280. emit_json({"success": False, "error": "`--cd` is required (omit it only with --list-models)."}, exit_code=2)
  281. if args.PROMPT and args.prompt_file is not None:
  282. emit_json({"success": False, "error": "Use either `--PROMPT` or `--prompt-file`, not both."}, exit_code=2)
  283. if not args.PROMPT and args.prompt_file is None:
  284. emit_json({"success": False, "error": "Provide `--PROMPT` or `--prompt-file`."}, exit_code=2)
  285. if args.timeout < 0:
  286. emit_json({"success": False, "error": "`--timeout` must be zero or a positive number of seconds."}, exit_code=2)
  287. prompt = args.PROMPT
  288. if args.prompt_file is not None:
  289. if not args.prompt_file.is_file():
  290. emit_json({"success": False, "error": f"Prompt file not found: {args.prompt_file}"}, exit_code=2)
  291. prompt = args.prompt_file.read_text(encoding="utf-8")
  292. if not prompt.strip():
  293. emit_json({"success": False, "error": "Prompt is empty."}, exit_code=2)
  294. cd: Path = args.cd
  295. error = preflight_check(cd, warnings)
  296. if error:
  297. emit_json({"success": False, "error": error, "warnings": warnings}, exit_code=1)
  298. wall_timeout = args.timeout
  299. if not wall_timeout:
  300. wall_timeout = (parse_duration(args.print_timeout) or 300.0) + 120.0
  301. if args.skip_permissions:
  302. warnings.append("`--skip-permissions` auto-approves all agy tool actions without prompting.")
  303. if args.model and not args.no_validate_model:
  304. models, err = list_models()
  305. if err:
  306. warnings.append(f"Could not validate --model against `agy models` ({err}); proceeding.")
  307. elif args.model not in models:
  308. emit_json({
  309. "success": False,
  310. "error": (
  311. f"Model {args.model!r} is not listed by `agy models`; agy would silently fall "
  312. f"back to its default. Available: {models}. Use --no-validate-model to skip."
  313. ),
  314. "warnings": warnings,
  315. }, exit_code=2)
  316. cmd = build_command(args, prompt)
  317. start_time = time.time()
  318. lock = acquire_lock()
  319. try:
  320. raw, returncode, timed_out = run_agy_pty(cmd, cd.absolute(), wall_timeout, start_time)
  321. conv_id, db_path = recover_session_id(cd, start_time)
  322. except Exception as exc: # pragma: no cover - defensive boundary
  323. release_lock(lock)
  324. emit_json({"success": False, "error": f"Failed to run agy: {exc}", "warnings": warnings}, exit_code=1)
  325. release_lock(lock)
  326. lines = strip_ansi(raw)
  327. agent_messages = "\n".join(lines).strip()
  328. errors: List[str] = []
  329. success = returncode == 0 and bool(agent_messages) and not timed_out
  330. if timed_out:
  331. errors.append(
  332. f"agy did not finish within {wall_timeout:g}s and was killed. "
  333. "agy hangs without a real terminal; the bridge runs it under a pty, "
  334. "but a long task may still exceed the wall-clock cap (raise --timeout)."
  335. )
  336. if returncode != 0 and not timed_out:
  337. errors.append(f"agy exited with non-zero status: {returncode}.")
  338. if not agent_messages and not errors:
  339. errors.append("No response captured from agy.")
  340. if conv_id:
  341. warnings.append(
  342. "SESSION_ID was recovered from last_conversations.json (agy does not surface it "
  343. "in print mode). Serialize concurrent bridge calls to keep recovery reliable."
  344. )
  345. elif success:
  346. warnings.append("Could not recover SESSION_ID; multi-turn resume will not be possible for this run.")
  347. result: Dict[str, Any] = {"success": success}
  348. if conv_id:
  349. result["SESSION_ID"] = conv_id
  350. result["agent_messages"] = agent_messages
  351. if args.model:
  352. result["model"] = args.model
  353. if warnings:
  354. result["warnings"] = warnings
  355. if not success:
  356. result["error"] = "\n".join(errors) or "agy did not return a usable response."
  357. if args.return_all_messages:
  358. result["raw_output"] = raw
  359. if db_path:
  360. result["db_path"] = db_path
  361. print(json.dumps(result, indent=2, ensure_ascii=False))
  362. raise SystemExit(0 if success else 1)
  363. if __name__ == "__main__":
  364. main()
skills/collaborating-with-grok/scripts/grok_bridge.py · Bundled script · 868 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """
  3. Grok CLI Bridge Script.
  4. Wraps the Grok CLI (`grok -p`, headless mode) to provide a JSON interface,
  5. live stderr progress, and multi-turn continuity via SESSION_ID.
  6. Verified against `grok` (Grok Build TUI) v0.2.93 on macOS. Facts the bridge
  7. relies on:
  8. * Headless `grok -p` streams cleanly to a pipe (no TTY required) and exits on
  9. its own — no pseudo-terminal needed (unlike the Antigravity CLI).
  10. * `--output-format streaming-json` emits newline-delimited JSON events:
  11. {"type":"thought","data":"..."} reasoning tokens
  12. {"type":"text","data":"..."} answer tokens
  13. {"type":"end","stopReason":"EndTurn","sessionId":"...","requestId":"..."}
  14. Tool calls are NOT surfaced as events in headless mode (rich tool/plan
  15. updates are an ACP-mode feature of `grok agent stdio`). The bridge recovers
  16. tool telemetry after the run from the session files under
  17. `~/.grok/sessions/<encoded-cwd>/<session-id>/` (updates.jsonl for tool
  18. calls, summary.json for the model that actually answered — the host's
  19. ~/.grok/config.toml `[models] default` may override the CLI default).
  20. Session paths are encoded from the resolved cwd (symlinks matter: macOS
  21. `/tmp` → `/private/tmp`).
  22. * `--output-format json` emits a single object:
  23. {"text":..,"stopReason":..,"sessionId":..,"requestId":..,"thought":..}
  24. * `sessionId` appears only in the terminal `end`/json object. Resume a prior
  25. session with `-r <sessionId>` (errors if the session does not exist).
  26. * The exit code is the authoritative success signal; `stopReason` is the
  27. completeness signal. An approval-gated action is *cancelled* in headless
  28. mode (stopReason "Cancelled", exit 0, files untouched) — it never hangs.
  29. A `--max-turns` cutoff is stopReason "Cancelled" with a NON-zero exit and an
  30. `Error:` line on stderr.
  31. Safety: the user's `~/.grok/config.toml` may set
  32. `permission_mode = "always-approve"`, which auto-approves edits and shell
  33. commands. To keep write/shell authority approval-gated by default, the bridge passes
  34. `--permission-mode default` unless the caller chooses a mutually exclusive
  35. authority flag. A standalone `--always-approve` grants explicit write/shell
  36. authority; it is never combined with the safe default.
  37. """
  38. from __future__ import annotations
  39. import argparse
  40. import datetime
  41. import json
  42. import os
  43. import queue
  44. import re
  45. import shutil
  46. import subprocess
  47. import sys
  48. import tempfile
  49. import threading
  50. import time
  51. import urllib.parse
  52. from pathlib import Path
  53. from typing import Any, Dict, Generator, List, Optional
  54. OUTPUT_FORMATS = ("plain", "json", "streaming-json")
  55. PERMISSION_MODES = ("default", "plan", "acceptEdits", "auto", "dontAsk", "bypassPermissions")
  56. ENFORCED_CLI_PERMISSION_MODES = ("default", "bypassPermissions")
  57. UNWIRED_CLI_PERMISSION_MODES = tuple(
  58. mode for mode in PERMISSION_MODES if mode not in ENFORCED_CLI_PERMISSION_MODES
  59. )
  60. BUILTIN_SANDBOX_PROFILES = ("off", "workspace", "devbox", "read-only", "strict")
  61. EFFORT_LEVELS = ("none", "minimal", "low", "medium", "high", "xhigh", "max")
  62. # Grok prints ANSI-coloured log lines to stderr (e.g. "\x1b[2m...\x1b[0m").
  63. ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*\x07|\x1b[=>]")
  64. # stderr lines worth surfacing as the failure reason.
  65. ERROR_LINE_RE = re.compile(r"(^|\s)(Error:|ERROR\b|panicked|fatal)", re.IGNORECASE)
  66. def emit_json(result: Dict[str, Any], exit_code: int = 0) -> None:
  67. result.setdefault("complete", False)
  68. print(json.dumps(result, indent=2, ensure_ascii=False))
  69. raise SystemExit(exit_code)
  70. def find_executable(name: str) -> str:
  71. """Locate the grok executable, handling a Windows `.exe`/`.cmd` shim."""
  72. found = shutil.which(name)
  73. if found:
  74. return found
  75. if os.name == "nt":
  76. for ext in (".exe", ".cmd", ".bat"):
  77. alt = shutil.which(f"{name}{ext}")
  78. if alt:
  79. return alt
  80. return name
  81. def strip_ansi(text: str) -> str:
  82. return ANSI_RE.sub("", text)
  83. def parse_sandbox_profile(value: str) -> str:
  84. """Preserve built-in/custom profile names with a targeted Codex-term hint."""
  85. if value == "":
  86. return value
  87. if value == "workspace-write":
  88. raise argparse.ArgumentTypeError(
  89. "Grok calls this profile 'workspace'; use `--sandbox workspace` "
  90. "(`workspace-write` is Codex CLI terminology)."
  91. )
  92. # Grok also accepts names from global/project sandbox.toml files and
  93. # validates unknown profiles fail-closed.
  94. return value
  95. def resolve_workspace_path(path: Path, cd: Path) -> Path:
  96. """Resolve an input path, using --cd as the base for relative paths."""
  97. expanded = path.expanduser()
  98. if not expanded.is_absolute():
  99. expanded = cd / expanded
  100. return expanded.resolve()
  101. def permission_mode_error(mode: Optional[str]) -> Optional[str]:
  102. """Reject modes that Grok 0.2.93 parses but does not enforce from the CLI."""
  103. if mode not in UNWIRED_CLI_PERMISSION_MODES:
  104. return None
  105. return (
  106. f"`--permission-mode {mode}` is accepted but not enforced by Grok CLI 0.2.93. "
  107. "The bridge refuses to provide a false authority or safety signal. Use `default`, "
  108. "explicit `--allow`/`--deny` rules, or `--always-approve`/`bypassPermissions` only "
  109. "with user consent. For acceptEdits/dontAsk policy, configure `defaultMode` in the "
  110. "applicable Claude Code `settings.json`."
  111. )
  112. def materialize_context_prompt(
  113. prompt: str,
  114. context_file: Path,
  115. temp_dir: Optional[Path] = None,
  116. ) -> Path:
  117. """Combine an instruction and context file into a native prompt file.
  118. Grok 0.2.93 ignores stdin when `-p` is present. A temporary prompt file
  119. preserves large-file behavior without putting the context on argv.
  120. """
  121. context = context_file.read_text(encoding="utf-8", errors="replace")
  122. fd, name = tempfile.mkstemp(
  123. prefix="grok-bridge-context-",
  124. suffix=".md",
  125. dir=str(temp_dir) if temp_dir is not None else None,
  126. text=True,
  127. )
  128. path = Path(name)
  129. payload = json.dumps(
  130. {"source": context_file.as_posix(), "content": context},
  131. ensure_ascii=False,
  132. )
  133. # Prevent context text from closing the XML wrapper. JSON escapes remain
  134. # legible to the model while keeping arbitrary file contents data-only.
  135. payload = (
  136. payload.replace("&", "\\u0026")
  137. .replace("<", "\\u003c")
  138. .replace(">", "\\u003e")
  139. )
  140. try:
  141. with os.fdopen(fd, "w", encoding="utf-8") as handle:
  142. handle.write(prompt.rstrip())
  143. handle.write('\n\n<context_file format="json" trust="untrusted-data">\n')
  144. handle.write(payload)
  145. handle.write("\n</context_file>\n")
  146. except BaseException:
  147. # os.fdopen owns fd after it succeeds; close defensively when it fails.
  148. try:
  149. os.close(fd)
  150. except OSError:
  151. pass
  152. path.unlink(missing_ok=True)
  153. raise
  154. return path
  155. def find_ancestor_git_root(cd: Path) -> Optional[Path]:
  156. """Return the nearest Git root marker at or above cd, if one exists."""
  157. for candidate in (cd, *cd.parents):
  158. if (candidate / ".git").exists():
  159. return candidate
  160. return None
  161. def completion_state(
  162. success: bool,
  163. output_format: str,
  164. stop_reason: Optional[str],
  165. ) -> Optional[bool]:
  166. """Return known completion, or None when plain output hides stopReason."""
  167. if not success:
  168. return False
  169. if output_format == "plain":
  170. return None
  171. return stop_reason == "EndTurn"
  172. def session_recovery_warning(output_format: str) -> str:
  173. if output_format == "plain":
  174. return (
  175. "SESSION_ID recovered from session storage; plain output does not emit it, so resume "
  176. "is available on a best-effort basis."
  177. )
  178. return (
  179. "SESSION_ID was recovered from the session directory because grok ended before emitting "
  180. "it; resume with `--SESSION_ID` to continue."
  181. )
  182. def configuration_warnings(args: argparse.Namespace, cd: Path) -> List[str]:
  183. """Describe authority, observability, and isolation sharp edges."""
  184. warnings: List[str] = []
  185. if args.always_approve:
  186. warnings.append(
  187. "`--always-approve` auto-approves all grok tool actions "
  188. "(writes + shell) without prompting."
  189. )
  190. if args.permission_mode == "bypassPermissions":
  191. warnings.append(
  192. f"`--permission-mode {args.permission_mode}` reduces approval gating; "
  193. "grok may edit files or run commands."
  194. )
  195. if args.permission_mode == "":
  196. warnings.append(
  197. "No `--permission-mode` set: grok inherits ~/.grok/config.toml, which may "
  198. "auto-approve tools. Omit the flag for the bridge's gated `default` mode."
  199. )
  200. if args.output_format == "plain":
  201. warnings.append(
  202. "`--output-format plain` cannot capture stopReason, so `complete` will be null."
  203. )
  204. if args.sandbox == "workspace":
  205. warnings.append(
  206. "`--sandbox workspace` reads everywhere and writes only CWD, ~/.grok, and temp "
  207. "directories. Prompt scope is not a hard read boundary; use `strict`, a custom "
  208. "deny profile, or external isolation when required."
  209. )
  210. elif args.sandbox == "devbox":
  211. warnings.append(
  212. "`--sandbox devbox` permits broad filesystem writes and is intended only for "
  213. "disposable development VMs."
  214. )
  215. elif args.sandbox and args.sandbox not in BUILTIN_SANDBOX_PROFILES:
  216. warnings.append(
  217. f"`--sandbox {args.sandbox}` is a custom profile; verify the applicable "
  218. "sandbox.toml because its read, write, deny, and network rules are external "
  219. "to this bridge."
  220. )
  221. git_root = find_ancestor_git_root(cd)
  222. if git_root is not None and git_root != cd:
  223. warnings.append(
  224. f"`--cd` is nested below Git root {git_root.as_posix()!r}; grok may discover "
  225. "parent instructions, configuration, and repository metadata. Use a standalone "
  226. "workspace outside the parent repository for stronger isolation."
  227. )
  228. allow_tools = [tool.strip() for tool in args.tools.split(",") if tool.strip()]
  229. if any(tool in ("run_terminal_cmd", "web_search", "web_fetch") for tool in allow_tools):
  230. warnings.append(
  231. "`--tools` allowlist includes run_terminal_cmd or web_search/web_fetch: on the "
  232. "GrokBuild-lineage coding agent (e.g. grok-4.5) these allowlists fail session build with "
  233. "run_terminal_cmd's auto-background RequirementError, which is still "
  234. "present for those tool combinations on CLI 0.2.93. Use a read-only allowlist "
  235. "without those tools, or keep the default toolset and use `--disallowed-tools`."
  236. )
  237. return warnings
  238. def preflight_check(cd: Path) -> Optional[str]:
  239. if shutil.which("grok") is None:
  240. return (
  241. "Grok CLI not found in PATH. Install it "
  242. "(`curl -fsSL https://x.ai/cli/install.sh | bash`) and ensure `grok` is available."
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 277 on GitHub
  243. )
  244. if not cd.exists():
  245. return f"Workspace root `{cd.absolute().as_posix()}` does not exist."
  246. if not cd.is_dir():
  247. return f"Workspace root `{cd.absolute().as_posix()}` is not a directory."
  248. has_env_key = bool(os.environ.get("XAI_API_KEY"))
  249. has_auth_file = Path.home().joinpath(".grok", "auth.json").is_file()
  250. if not has_env_key and not has_auth_file:
  251. return "No Grok auth found. Run `grok login`, or export `XAI_API_KEY`."
  252. return None
  253. def list_models() -> Dict[str, Any]:
  254. """Parse `grok models` (plain text) into a JSON-friendly structure."""
  255. try:
  256. proc = subprocess.run(
  257. [find_executable("grok"), "models"],
  258. stdin=subprocess.DEVNULL,
  259. capture_output=True,
  260. text=True,
  261. timeout=60,
  262. )
  263. except (OSError, subprocess.SubprocessError) as exc:
  264. return {"success": False, "error": f"Failed to run `grok models`: {exc}"}
  265. text = strip_ansi(proc.stdout)
  266. models: List[str] = []
  267. default: Optional[str] = None
  268. for line in text.splitlines():
  269. match = re.match(r"\s*([*-])\s+(\S+)", line)
  270. if not match:
  271. continue
  272. bullet, model = match.group(1), match.group(2)
  273. models.append(model)
  274. if bullet == "*" or "(default)" in line:
  275. default = model
  276. if not models:
  277. err = strip_ansi(proc.stderr).strip() or "`grok models` returned no models."
  278. return {"success": False, "error": err}
  279. return {"success": True, "models": models, "default": default}
  280. def build_command(args: argparse.Namespace, cd: Path, prompt: str) -> List[str]:
  281. mode_error = permission_mode_error(args.permission_mode)
  282. if mode_error:
  283. raise ValueError(mode_error)
  284. cmd = ["grok"]
  285. if args.prompt_file is not None:
  286. cmd.extend(["--prompt-file", str(args.prompt_file)])
  287. else:
  288. cmd.extend(["-p", prompt])
  289. cmd.extend(["--output-format", args.output_format, "--cwd", cd.absolute().as_posix()])
  290. if args.model:
  291. cmd.extend(["-m", args.model])
  292. # Session continuity (mutually exclusive in argparse).
  293. if args.SESSION_ID:
  294. cmd.extend(["-r", args.SESSION_ID])
  295. elif args.session_id:
  296. cmd.extend(["-s", args.session_id])
  297. elif args.continue_session:
  298. cmd.append("-c")
  299. if args.always_approve and args.permission_mode is not None:
  300. raise ValueError("--always-approve and --permission-mode are mutually exclusive")
  301. if args.always_approve:
  302. cmd.append("--always-approve")
  303. elif args.permission_mode is None:
  304. cmd.extend(["--permission-mode", "default"])
  305. elif args.permission_mode:
  306. cmd.extend(["--permission-mode", args.permission_mode])
  307. if args.sandbox:
  308. cmd.extend(["--sandbox", args.sandbox])
  309. if args.tools:
  310. cmd.extend(["--tools", args.tools])
  311. if args.disallowed_tools:
  312. cmd.extend(["--disallowed-tools", args.disallowed_tools])
  313. for rule in args.allow:
  314. cmd.extend(["--allow", rule])
  315. for rule in args.deny:
  316. cmd.extend(["--deny", rule])
  317. if args.effort:
  318. cmd.extend(["--effort", args.effort])
  319. if args.reasoning_effort:
  320. cmd.extend(["--reasoning-effort", args.reasoning_effort])
  321. if args.max_turns:
  322. cmd.extend(["--max-turns", str(args.max_turns)])
  323. if args.rules:
  324. cmd.extend(["--rules", args.rules])
  325. if args.disable_web_search:
  326. cmd.append("--disable-web-search")
  327. if args.no_plan:
  328. cmd.append("--no-plan")
  329. return cmd
  330. def stream_command(
  331. cmd: List[str],
  332. cwd: Path,
  333. timeout_seconds: float,
  334. stderr_sink: List[str],
  335. ) -> Generator[str, None, int]:
  336. """Run grok, yield stdout lines, and forward cleaned stderr as progress."""
  337. resolved = cmd.copy()
  338. resolved[0] = find_executable(cmd[0])
  339. proc = subprocess.Popen(
  340. resolved,
  341. shell=False,
  342. stdin=subprocess.DEVNULL,
  343. stdout=subprocess.PIPE,
  344. stderr=subprocess.PIPE,
  345. universal_newlines=True,
  346. encoding="utf-8",
  347. errors="replace",
  348. cwd=str(cwd),
  349. )
  350. out_q: "queue.Queue[Optional[str]]" = queue.Queue()
  351. started_at = time.time()
  352. def read_stdout() -> None:
  353. assert proc.stdout is not None
  354. for line in iter(proc.stdout.readline, ""):
  355. stripped = line.strip()
  356. if stripped:
  357. out_q.put(stripped)
  358. proc.stdout.close()
  359. out_q.put(None)
  360. def read_stderr() -> None:
  361. assert proc.stderr is not None
  362. for line in iter(proc.stderr.readline, ""):
  363. text = strip_ansi(line).rstrip()
  364. if not text:
  365. continue
  366. print(f"[grok stderr] {text}", file=sys.stderr, flush=True)
  367. if ERROR_LINE_RE.search(text):
  368. stderr_sink.append(text)
  369. proc.stderr.close()
  370. t_out = threading.Thread(target=read_stdout, daemon=True)
  371. t_err = threading.Thread(target=read_stderr, daemon=True)
  372. t_out.start()
  373. t_err.start()
  374. while True:
  375. if timeout_seconds and time.time() - started_at > timeout_seconds:
  376. print(
  377. f"[grok] timeout after {timeout_seconds:g}s; terminating grok",
  378. file=sys.stderr,
  379. flush=True,
  380. )
  381. proc.kill()
  382. proc.wait()
  383. return 124
  384. try:
  385. line = out_q.get(timeout=0.5)
  386. if line is None:
  387. break
  388. yield line
  389. except queue.Empty:
  390. if proc.poll() is not None and not t_out.is_alive():
  391. break
  392. t_out.join(timeout=5)
  393. t_err.join(timeout=2)
  394. try:
  395. return proc.wait(timeout=5)
  396. except subprocess.TimeoutExpired:
  397. proc.kill()
  398. return proc.wait()
  399. def handle_event(event: Dict[str, Any], state: Dict[str, Any], start_time: float) -> None:
  400. """Fold one streaming-json event into state and emit throttled progress."""
  401. def status(message: str) -> None:
  402. elapsed = time.time() - start_time
  403. print(f"[grok {elapsed:5.1f}s] {message}", file=sys.stderr, flush=True)
  404. etype = event.get("type", "")
  405. if etype == "text":
  406. data = event.get("data", "")
  407. state["agent_messages"] += data
  408. if not state["responding"]:
  409. state["responding"] = True
  410. status("Responding…")
  411. state["last_status"] = time.time()
  412. elif time.time() - state["last_status"] >= 1.5:
  413. status(f"Responding… ({len(state['agent_messages'])} chars)")
  414. state["last_status"] = time.time()
  415. elif etype == "thought":
  416. state["reasoning"] += event.get("data", "")
  417. if not state["thinking"]:
  418. state["thinking"] = True
  419. status("Thinking…")
  420. state["last_status"] = time.time()
  421. elif time.time() - state["last_status"] >= 1.5:
  422. status(f"Thinking… ({len(state['reasoning'])} chars)")
  423. state["last_status"] = time.time()
  424. elif etype == "end":
  425. state["stop_reason"] = event.get("stopReason")
  426. state["session_id"] = event.get("sessionId") or state["session_id"]
  427. state["request_id"] = event.get("requestId") or state["request_id"]
  428. preview = state["agent_messages"][:80].replace("\n", " ")
  429. status(f"Done · {state['stop_reason']} · {preview}{'…' if len(state['agent_messages']) > 80 else ''}")
  430. elif "error" in etype.lower():
  431. message = ""
  432. err = event.get("error")
  433. if isinstance(err, dict):
  434. message = str(err.get("message", ""))
  435. message = message or str(event.get("data") or event.get("message") or "")
  436. if message:
  437. state["errors"].append(message)
  438. status(f"Error event: {message[:80]}")
  439. def parse_json_blob(raw: str, state: Dict[str, Any]) -> None:
  440. """Parse a single `--output-format json` object."""
  441. raw = raw.strip()
  442. if not raw:
  443. state["errors"].append("No output received from grok.")
  444. return
  445. try:
  446. obj = json.loads(raw)
  447. except json.JSONDecodeError as exc:
  448. state["errors"].append(f"Failed to parse grok JSON output: {exc}")
  449. return
  450. if not isinstance(obj, dict):
  451. state["errors"].append("Unexpected grok JSON output (not an object).")
  452. return
  453. state["all_messages"].append(obj)
  454. if isinstance(obj.get("text"), str):
  455. state["agent_messages"] += obj["text"]
  456. if isinstance(obj.get("thought"), str):
  457. state["reasoning"] += obj["thought"]
  458. state["stop_reason"] = obj.get("stopReason") or state["stop_reason"]
  459. state["session_id"] = obj.get("sessionId") or state["session_id"]
  460. state["request_id"] = obj.get("requestId") or state["request_id"]
  461. def session_cwd_encodings(cd: Path) -> List[str]:
  462. """Return URL-encoded cwd keys grok may use under ~/.grok/sessions/.
  463. Grok encodes the resolved workspace path. On macOS, `/tmp` is a symlink to
  464. `/private/tmp`, so absolute() and resolve() can disagree — try both.
  465. """
  466. encodings: List[str] = []
  467. for candidate in (cd.resolve(), cd.absolute()):
  468. key = urllib.parse.quote(str(candidate), safe="")
  469. if key not in encodings:
  470. encodings.append(key)
  471. return encodings
  472. def snapshot_session_dirs(cd: Path) -> set[str]:
  473. """Record existing session directories so recovery ignores older runs."""
  474. existing: set[str] = set()
  475. try:
  476. for enc in session_cwd_encodings(cd):
  477. sessions_root = Path.home() / ".grok" / "sessions" / enc
  478. if sessions_root.is_dir():
  479. existing.update(
  480. str(path) for path in sessions_root.iterdir() if path.is_dir()
  481. )
  482. except OSError:
  483. pass
  484. return existing
  485. def collect_session_telemetry(
  486. cd: Path,
  487. session_id: Optional[str],
  488. run_start: float,
  489. preexisting_session_dirs: Optional[set[str]] = None,
  490. ) -> Dict[str, Any]:
  491. """Recover post-run telemetry from grok's session files.
  492. Headless grok emits no tool events, but `updates.jsonl` records every tool
  493. call and `summary.json` records the model that actually answered. Explicit
  494. resume/new-session IDs provide a deterministic hint. Otherwise,
  495. recovery considers only session directories absent from the pre-run
  496. snapshot, then uses mtime. Concurrent new runs in the same cwd remain
  497. best-effort. Returns {} on any failure.
  498. """
  499. telemetry: Dict[str, Any] = {}
  500. try:
  501. session_dir: Optional[Path] = None
  502. for enc in session_cwd_encodings(cd):
  503. sessions_root = Path.home() / ".grok" / "sessions" / enc
  504. if session_id and (sessions_root / session_id).is_dir():
  505. session_dir = sessions_root / session_id
  506. break
  507. if sessions_root.is_dir():
  508. excluded = preexisting_session_dirs or set()
  509. fresh = [
  510. d for d in sessions_root.iterdir()
  511. if d.is_dir()
  512. and str(d) not in excluded
  513. and d.stat().st_mtime >= run_start - 2
  514. ]
  515. if fresh:
  516. session_dir = max(fresh, key=lambda d: d.stat().st_mtime)
  517. telemetry["recovered_session_id"] = session_dir.name
  518. break
  519. if session_dir is None:
  520. return telemetry
  521. telemetry["session_id"] = session_dir.name
  522. summary_path = session_dir / "summary.json"
  523. if summary_path.is_file():
  524. summary = json.loads(summary_path.read_text(encoding="utf-8", errors="replace"))
  525. if isinstance(summary, dict):
  526. if summary.get("current_model_id"):
  527. telemetry["model"] = summary["current_model_id"]
  528. if summary.get("agent_name"):
  529. telemetry["agent"] = summary["agent_name"]
  530. updates_path = session_dir / "updates.jsonl"
  531. if updates_path.is_file():
  532. tool_counts: Dict[str, int] = {}
  533. last_ts: Optional[str] = None
  534. with updates_path.open(encoding="utf-8", errors="replace") as handle:
  535. for line in handle:
  536. try:
  537. event = json.loads(line)
  538. except json.JSONDecodeError:
  539. continue
  540. if not isinstance(event, dict):
  541. continue
  542. if isinstance(event.get("timestamp"), str):
  543. last_ts = event["timestamp"]
  544. params = event.get("params")
  545. update = params.get("update") if isinstance(params, dict) else None
  546. if isinstance(update, dict) and update.get("sessionUpdate") == "tool_call":
  547. title = str(update.get("title") or "unknown")
  548. tool_counts[title] = tool_counts.get(title, 0) + 1
  549. if tool_counts:
  550. telemetry["tool_counts"] = tool_counts
  551. telemetry["tools_used"] = sorted(tool_counts)
  552. if last_ts:
  553. try:
  554. parsed = datetime.datetime.fromisoformat(last_ts.replace("Z", "+00:00"))
  555. now = datetime.datetime.now(datetime.timezone.utc)
  556. telemetry["last_activity_age_s"] = round((now - parsed).total_seconds(), 1)
  557. except ValueError:
  558. pass
  559. except Exception: # pragma: no cover - telemetry must never break the result
  560. pass
  561. return telemetry
  562. def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
  563. parser = argparse.ArgumentParser(description="Grok CLI Bridge")
  564. parser.add_argument("--PROMPT", default="", help="Instruction to send to grok. Use this or --prompt-file.")
  565. parser.add_argument("--prompt-file", type=Path, default=None, help="Read the whole prompt from a file (grok --prompt-file). Relative paths resolve against --cd.")
  566. parser.add_argument("--stdin-file", type=Path, default=None, help="Combine a context/handoff file with the instruction in --PROMPT. Relative paths resolve against --cd; mutually exclusive with --prompt-file.")
  567. parser.add_argument("--cd", type=Path, default=None, help="Workspace root for grok (maps to grok --cwd). Required unless --list-models.")
  568. parser.add_argument("--list-models", action="store_true", help="Print models from `grok models` as JSON and exit (no prompt/--cd needed).")
  569. session = parser.add_mutually_exclusive_group()
  570. session.add_argument("--SESSION_ID", default="", help="Resume a session by ID (grok -r; errors if it does not exist).")
  571. session.add_argument("--session-id", dest="session_id", default="", help="Name a NEW session (grok -s; valid unused UUID; does not resume — use --SESSION_ID/--continue).")
  572. session.add_argument("--continue", dest="continue_session", action="store_true", help="Continue the most recent session in --cd (grok -c).")
  573. parser.add_argument("--model", default="", help="Model ID (e.g. grok-4.5 as of CLI 0.2.93). Discover with --list-models — do not hardcode.")
  574. parser.add_argument("--output-format", default="streaming-json", choices=OUTPUT_FORMATS, help="grok output format. Default streaming-json (live progress + SESSION_ID).")
  575. authority = parser.add_mutually_exclusive_group()
  576. authority.add_argument("--permission-mode", default=None, choices=("",) + PERMISSION_MODES, help="Tool-approval mode. Omit for gated 'default'; pass '' to inherit grok config. Grok 0.2.93 only enforces default and bypassPermissions from this CLI flag.")
  577. authority.add_argument("--always-approve", action="store_true", help="Auto-approve every tool action (writes + shell). Use only with explicit user consent, ideally in an isolated worktree.")
  578. parser.add_argument("--sandbox", default=None, type=parse_sandbox_profile, help="Grok sandbox profile: off, workspace, devbox, read-only, strict, or a custom sandbox.toml profile.")
  579. parser.add_argument("--tools", default="", help='Allowlist of built-in tools (comma-separated), e.g. "read_file,grep,list_dir" for hard read-only.')
  580. parser.add_argument("--disallowed-tools", default="", help='Denylist of built-in tools (comma-separated). Supports Agent / Agent(type) entries.')
  581. parser.add_argument("--allow", action="append", default=[], help='Permission allow rule, e.g. "Bash(npm*)" or "WebFetch(domain:docs.rs)". Repeatable.')
  582. parser.add_argument("--deny", action="append", default=[], help='Permission deny rule, e.g. "Bash(rm*)". Repeatable. Deny beats allow.')
  583. parser.add_argument("--effort", default="", choices=("",) + EFFORT_LEVELS, help="Effort level (model-dependent; CLI alias of --reasoning-effort).")
  584. parser.add_argument("--reasoning-effort", default="", help="Reasoning effort for models that support it (e.g. grok-4.5).")
  585. parser.add_argument("--max-turns", type=int, default=0, help="Maximum agentic turns before grok stops (0 = unset).")
  586. parser.add_argument("--rules", default="", help="Extra rules appended to the system prompt.")
  587. parser.add_argument("--disable-web-search", action="store_true", help="Remove the web_search/web_fetch tools.")
  588. parser.add_argument("--no-plan", action="store_true", help="Disable grok plan mode.")
  589. parser.add_argument("--timeout", type=float, default=0, help="Bridge wall-clock kill, in seconds. Default: no bridge timeout.")
  590. parser.add_argument("--return-all-messages", action="store_true", help="Include the captured reasoning and raw events in the result.")
  591. return parser.parse_args(argv)
  592. def main() -> None:
  593. args = parse_args()
  594. if args.list_models:
  595. if shutil.which("grok") is None:
  596. emit_json({"success": False, "error": "Grok CLI not found in PATH."}, exit_code=1)
  597. result = list_models()
  598. result["complete"] = bool(result.get("success"))
  599. emit_json(result, exit_code=0 if result.get("success") else 1)
  600. mode_error = permission_mode_error(args.permission_mode)
  601. if mode_error:
  602. emit_json({"success": False, "error": mode_error}, exit_code=2)
  603. if args.cd is None:
  604. emit_json({"success": False, "error": "`--cd` is required (omit it only with --list-models)."}, exit_code=2)
  605. if args.PROMPT and args.prompt_file is not None:
  606. emit_json({"success": False, "error": "Use either `--PROMPT` or `--prompt-file`, not both."}, exit_code=2)
  607. if not args.PROMPT and args.prompt_file is None:
  608. emit_json({"success": False, "error": "Provide `--PROMPT` or `--prompt-file`."}, exit_code=2)
  609. if args.prompt_file is not None and args.stdin_file is not None:
  610. emit_json({"success": False, "error": "Use either `--prompt-file` or `--stdin-file`, not both."}, exit_code=2)
  611. if args.stdin_file is not None and not args.PROMPT:
  612. emit_json({"success": False, "error": "`--stdin-file` requires `--PROMPT` (the instruction); the bridge combines both into a native prompt file."}, exit_code=2)
  613. if args.timeout < 0:
  614. emit_json({"success": False, "error": "`--timeout` must be zero or a positive number of seconds."}, exit_code=2)
  615. cd = args.cd.expanduser().resolve()
  616. if args.prompt_file is not None:
  617. args.prompt_file = resolve_workspace_path(args.prompt_file, cd)
  618. if args.stdin_file is not None:
  619. args.stdin_file = resolve_workspace_path(args.stdin_file, cd)
  620. prompt = args.PROMPT
  621. if args.prompt_file is not None:
  622. if not args.prompt_file.is_file():
  623. emit_json({"success": False, "error": f"Prompt file not found: {args.prompt_file}"}, exit_code=2)
  624. if not args.prompt_file.read_text(encoding="utf-8", errors="replace").strip():
  625. emit_json({"success": False, "error": "Prompt file is empty."}, exit_code=2)
  626. elif not prompt.strip():
  627. emit_json({"success": False, "error": "Prompt is empty."}, exit_code=2)
  628. if args.stdin_file is not None and not args.stdin_file.is_file():
  629. emit_json({"success": False, "error": f"Stdin context file not found: {args.stdin_file}"}, exit_code=2)
  630. error = preflight_check(cd)
  631. if error:
  632. emit_json({"success": False, "error": error}, exit_code=1)
  633. warnings = configuration_warnings(args, cd)
  634. preexisting_session_dirs = snapshot_session_dirs(cd)
  635. state: Dict[str, Any] = {
  636. "agent_messages": "",
  637. "reasoning": "",
  638. "stop_reason": None,
  639. "session_id": None,
  640. "request_id": None,
  641. "thinking": False,
  642. "responding": False,
  643. "last_status": 0.0,
  644. "errors": [],
  645. "all_messages": [],
  646. }
  647. stderr_sink: List[str] = []
  648. raw_json_lines: List[str] = []
  649. start_time = time.time()
  650. returncode = 1
  651. temporary_prompt_file: Optional[Path] = None
  652. try:
  653. if args.stdin_file is not None:
  654. temporary_prompt_file = materialize_context_prompt(prompt, args.stdin_file)
  655. args.prompt_file = temporary_prompt_file
  656. cmd = build_command(args, cd, prompt)
  657. generator = stream_command(cmd, cd.absolute(), args.timeout, stderr_sink)
  658. while True:
  659. try:
  660. line = next(generator)
  661. except StopIteration as finished:
  662. returncode = int(finished.value or 0)
  663. break
  664. if args.output_format == "streaming-json":
  665. try:
  666. event = json.loads(line)
  667. except json.JSONDecodeError:
  668. state["errors"].append(f"[json decode error] {line}")
  669. continue
  670. if isinstance(event, dict):
  671. state["all_messages"].append(event)
  672. handle_event(event, state, start_time)
  673. elif args.output_format == "json":
  674. raw_json_lines.append(line)
  675. else: # plain
  676. state["agent_messages"] += line + "\n"
  677. except Exception as exc: # pragma: no cover - defensive boundary
  678. emit_json({"success": False, "error": f"Failed to run grok: {exc}", "warnings": warnings}, exit_code=1)
  679. finally:
  680. if temporary_prompt_file is not None:
  681. temporary_prompt_file.unlink(missing_ok=True)
  682. if args.output_format == "json":
  683. parse_json_blob("\n".join(raw_json_lines), state)
  684. elif args.output_format == "plain":
  685. state["agent_messages"] = state["agent_messages"].strip()
  686. agent_messages = state["agent_messages"]
  687. stop_reason = state["stop_reason"]
  688. # Exit code is authoritative; stopReason signals completeness.
  689. success = returncode == 0
  690. complete = completion_state(success, args.output_format, stop_reason)
  691. if success and stop_reason and stop_reason != "EndTurn":
  692. warnings.append(
  693. f"grok stopReason={stop_reason!r}: the turn ended without a clean completion "
  694. "(an approval-gated action may have been cancelled, or output was truncated). "
  695. "Treat the result as possibly incomplete."
  696. )
  697. if success and state["session_id"] is None and args.output_format in ("json", "streaming-json"):
  698. warnings.append("Could not capture SESSION_ID; multi-turn resume will not be possible for this run.")
  699. if success and not agent_messages and stop_reason == "EndTurn":
  700. warnings.append("grok returned an empty response.")
  701. errors = list(state["errors"])
  702. if not success:
  703. errors.extend(stderr_sink)
  704. if returncode == 124:
  705. errors.append(f"grok exceeded the bridge timeout of {args.timeout:g}s and was killed.")
  706. elif returncode != 0:
  707. errors.append(f"grok exited with non-zero status: {returncode}.")
  708. if not errors:
  709. errors.append("No response captured from grok.")
  710. session_hint = state["session_id"] or args.SESSION_ID or args.session_id or None
  711. telemetry = collect_session_telemetry(
  712. cd, session_hint, start_time, preexisting_session_dirs
  713. )
  714. telemetry_session_id = telemetry.get("session_id") or telemetry.get("recovered_session_id")
  715. if state["session_id"] is None and telemetry_session_id:
  716. state["session_id"] = telemetry_session_id
  717. warnings.append(session_recovery_warning(args.output_format))
  718. actual_model = telemetry.get("model") or args.model
  719. actual_agent = telemetry.get("agent") or ""
  720. # Only warn when the effective agent is the alternate (composer/cursor) lineage —
  721. # not on every omit-`--model` coding run. Result still reports `model`/`agent`.
  722. if not args.model and actual_model:
  723. composer_like = (
  724. "composer" in actual_model.lower()
  725. or actual_agent == "cursor"
  726. or str(actual_agent).startswith("cursor")
  727. )
  728. if composer_like:
  729. warnings.append(
  730. f"No `--model` was passed; composer/cursor agent ran: model={actual_model!r}, "
  731. f"agent={actual_agent or 'unknown'!r}. Tool names and research timing differ from "
  732. "the GrokBuild-lineage coding model. For search/X or predictable tool ids, pass "
  733. "`--model` with a coding model from `--list-models` (e.g. grok-4.5 as of 0.2.93)."
  734. )
  735. if returncode == 124 and telemetry.get("tool_counts"):
  736. total_calls = sum(telemetry["tool_counts"].values())
  737. age = telemetry.get("last_activity_age_s")
  738. recency = f"; last activity {age:g}s before this report" if isinstance(age, (int, float)) else ""
  739. warnings.append(
  740. f"grok was still actively working when killed ({total_calls} tool calls recorded{recency}) — "
  741. "a slow research loop, not a hang. Rerun with a larger `--timeout` or resume with `--SESSION_ID`."
  742. )
  743. result: Dict[str, Any] = {"success": success, "complete": complete}
  744. if state["session_id"] is not None:
  745. result["SESSION_ID"] = state["session_id"]
  746. result["agent_messages"] = agent_messages
  747. if actual_model:
  748. result["model"] = actual_model
  749. if telemetry.get("agent"):
  750. result["agent"] = telemetry["agent"]
  751. if telemetry.get("tool_counts"):
  752. result["tool_counts"] = telemetry["tool_counts"]
  753. result["tools_used"] = telemetry["tools_used"]
  754. if stop_reason is not None:
  755. result["stop_reason"] = stop_reason
  756. if state["request_id"] is not None:
  757. result["request_id"] = state["request_id"]
  758. if warnings:
  759. result["warnings"] = warnings
  760. if not success:
  761. # De-duplicate while preserving order.
  762. seen: set = set()
  763. ordered = [e for e in errors if e and not (e in seen or seen.add(e))]
  764. result["error"] = "\n".join(ordered) or "grok did not return a usable response."
  765. if args.return_all_messages:
  766. result["reasoning"] = state["reasoning"]
  767. result["all_messages"] = state["all_messages"]
  768. print(json.dumps(result, indent=2, ensure_ascii=False))
  769. raise SystemExit(0 if success else 1)
  770. if __name__ == "__main__":
  771. main()

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.