@indigoai-us/hq-cli 5.345.203 → 5.345.205

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/command-catalog.generated.d.ts +51 -1
  3. package/dist/command-catalog.generated.js +63 -1
  4. package/dist/commands/bot.d.ts +67 -0
  5. package/dist/commands/bot.js +308 -41
  6. package/dist/commands/cloud-off-gate.d.ts +9 -2
  7. package/dist/commands/cloud-off-gate.js +49 -13
  8. package/dist/commands/cloud.d.ts +14 -2
  9. package/dist/commands/cloud.js +25 -16
  10. package/dist/commands/feedback.d.ts +26 -0
  11. package/dist/commands/feedback.js +91 -5
  12. package/dist/commands/install-global.d.ts +3 -1
  13. package/dist/commands/install-global.js +15 -4
  14. package/dist/commands/lanes.d.ts +2 -0
  15. package/dist/commands/lanes.js +9 -3
  16. package/dist/commands/mcp-serve.d.ts +5 -2
  17. package/dist/commands/mcp-serve.js +45 -3
  18. package/dist/commands/mcp-status.d.ts +3 -1
  19. package/dist/commands/mcp-status.js +24 -14
  20. package/dist/commands/secrets.js +11 -1
  21. package/dist/commands/sources.js +10 -15
  22. package/dist/commands/sync-core.js +2 -0
  23. package/dist/index.js +7 -2
  24. package/dist/lib/bot/claude-login.d.ts +7 -1
  25. package/dist/lib/bot/claude-login.js +56 -16
  26. package/dist/lib/bot/executive-settings.d.ts +13 -0
  27. package/dist/lib/bot/executive-settings.js +20 -17
  28. package/dist/lib/bot/executive-sync.d.ts +12 -0
  29. package/dist/lib/bot/executive-sync.js +36 -0
  30. package/dist/lib/bot/executive.d.ts +51 -0
  31. package/dist/lib/bot/executive.js +144 -0
  32. package/dist/lib/bot/fleet-cron.d.ts +7 -0
  33. package/dist/lib/bot/fleet-cron.js +2 -1
  34. package/dist/lib/bot/jobs/executive-handover.d.ts +6 -0
  35. package/dist/lib/bot/jobs/executive-handover.js +33 -0
  36. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +22 -0
  37. package/dist/lib/bot/jobs/hot-signal-sync.js +47 -0
  38. package/dist/lib/bot/listed-running.d.ts +16 -0
  39. package/dist/lib/bot/listed-running.js +16 -0
  40. package/dist/lib/bot/pending-switch.d.ts +51 -0
  41. package/dist/lib/bot/pending-switch.js +103 -0
  42. package/dist/lib/bot/run.js +27 -3
  43. package/dist/lib/bot/runtime-failure.js +19 -3
  44. package/dist/lib/bot/status.d.ts +20 -0
  45. package/dist/lib/capacity/collectors/claude-oauth.d.ts +53 -5
  46. package/dist/lib/capacity/collectors/claude-oauth.js +251 -71
  47. package/dist/lib/company-skill-wrapper.js +29 -0
  48. package/dist/lib/daemon/catalog.js +2 -2
  49. package/dist/lib/daemon/hq-child-bootstrap.mjs +197 -2
  50. package/dist/lib/daemon/resolver.d.ts +14 -0
  51. package/dist/lib/daemon/resolver.js +96 -0
  52. package/dist/lib/daemon/run.d.ts +11 -0
  53. package/dist/lib/daemon/run.js +60 -8
  54. package/dist/lib/daemon/server.d.ts +2 -9
  55. package/dist/lib/daemon/server.js +3 -89
  56. package/dist/lib/doctor/checks/claude-wiring.js +41 -0
  57. package/dist/lib/doctor/checks/sync-health.d.ts +8 -0
  58. package/dist/lib/doctor/checks/sync-health.js +34 -2
  59. package/dist/lib/doctor/duplicate-hook-registrations.d.ts +34 -0
  60. package/dist/lib/doctor/duplicate-hook-registrations.js +130 -0
  61. package/dist/lib/doctor/fix/apply.js +79 -3
  62. package/dist/lib/doctor/fix/remediation.d.ts +1 -1
  63. package/dist/lib/doctor/fix/remediation.js +15 -0
  64. package/dist/lib/doctor/types.d.ts +1 -1
  65. package/dist/lib/doctor/types.js +1 -0
  66. package/dist/lib/lanes/config.js +13 -0
  67. package/dist/lib/lanes/throttle.d.ts +12 -1
  68. package/dist/lib/lanes/throttle.js +27 -8
  69. package/dist/lib/lanes/types.d.ts +5 -0
  70. package/dist/lib/mcp/local-native-tools.d.ts +40 -0
  71. package/dist/lib/mcp/local-native-tools.js +111 -0
  72. package/dist/lib/mcp/tools.d.ts +2 -0
  73. package/dist/lib/mcp/tools.js +2 -0
  74. package/dist/lib/signals/steps/extract.d.ts +111 -5
  75. package/dist/lib/signals/steps/extract.js +524 -55
  76. package/dist/lib/sync-core/engine-home.d.ts +2 -1
  77. package/dist/lib/sync-core/engine-home.js +25 -8
  78. package/dist/lib/sync-core/reconcile.d.ts +3 -1
  79. package/dist/lib/sync-core/reconcile.js +21 -8
  80. package/dist/lib/sync-core/release.d.ts +14 -5
  81. package/dist/lib/sync-core/release.js +58 -14
  82. package/dist/sentry-init.js +6 -0
  83. package/dist/utils/cli-network-lifecycle.d.ts +11 -1
  84. package/dist/utils/cli-network-lifecycle.js +36 -2
  85. package/dist/utils/daemon-helper-lifetime.d.ts +39 -0
  86. package/dist/utils/daemon-helper-lifetime.js +209 -0
  87. package/dist/utils/daemon-helper-markers.d.ts +24 -0
  88. package/dist/utils/daemon-helper-markers.js +53 -0
  89. package/dist/utils/mcp-launcher.d.ts +28 -0
  90. package/dist/utils/mcp-launcher.js +117 -0
  91. package/dist/utils/package-use-lease.d.ts +10 -0
  92. package/dist/utils/package-use-lease.js +31 -0
  93. package/dist/utils/resident-package-preload.js +4 -1
  94. package/docs/anywhere-runtime.md +7 -0
  95. package/package.json +7 -7
@@ -49,8 +49,60 @@
49
49
  * --ignore-user-config drops ~/.codex/config.toml (its MCP servers);
50
50
  * --ignore-rules drops execpolicy allow rules. Codex has no turn cap flag;
51
51
  * the per-item timeout is its only limit, and it reports no cost.
52
- * grok: src/lib/bot/runtime/grok.ts has no restricted tool or sandbox
53
- * mode, so the step refuses it.
52
+ *
53
+ * grok, checked 2026-11-05 against `grok --help` and the user guide grok
54
+ * 1.0.70 ships (its embedded 22-permissions-and-safety.md and 18-sandbox.md)
55
+ * on Shawon's Mac:
56
+ * grok -p <prompt> --output-format streaming-json --cwd <turn dir>
57
+ * --permission-mode dontAsk --tools read_file
58
+ * --disallowed-tools search_tool,use_tool,run_terminal_cmd --disable-web-search
59
+ * --no-subagents --max-turns <n> --sandbox hq_signals_extract
60
+ * --allow "Read(<channel dir>/**)" --deny Bash
61
+ * --deny MCPTool --deny WebFetch --deny WebSearch --deny Edit --deny Write
62
+ * --deny Grep --deny "Read(~/.grok/**)"
63
+ * --deny "Read(<turn home>/.grok/**)" --deny "Read(<real home>/.grok/**)"
64
+ * --deny "Bash(ls)" --deny "Bash(cat)" ... (GROK_READ_ONLY_COMMANDS)
65
+ * dontAsk denies every call no allow rule covers, but it still auto-approves
66
+ * grok's own read-only tools and read-only shell list (ls, cat, head, git,
67
+ * rg, ...), so those commands are denied by name (a Bash rule without `*`
68
+ * is a prefix match). A `~` path in a rule is matched literally, before grok
69
+ * expands `~`, so the login deny lists that spelling, the absolute isolated
70
+ * home and the real home. The isolated auth.json stays readable by the grok
71
+ * process itself (strict reads ~/.grok, and the process loads the login at
72
+ * startup). Those Read denies are what keep it out of the model tool.
73
+ * Grok gets only read_file; Bash and the terminal tool are disabled.
74
+ * It returns candidate commands as JSON data. HQ validates the whole batch,
75
+ * checks the pinned wrapper still matches the script it generated, then
76
+ * executes that wrapper with fixed argv (never shell -c).
77
+ * --disallowed-tools also drops the MCP bridge (search_tool, use_tool).
78
+ * --sandbox names a profile the step writes to <turn dir>/.grok/sandbox.toml
79
+ * for the turn: it extends grok's built-in `strict` (reads: cwd, system
80
+ * paths, ~/.grok; writes: cwd, temp dirs, ~/.grok/sessions) with read-only
81
+ * grants for bash's install prefix, core/scripts, the company's knowledge
82
+ * preferences and the item's channel folder, and restrict_network = true.
83
+ * The company's _candidates folders are not granted. The host writes them
84
+ * after the turn, outside the sandbox. The profile is
85
+ * kernel-enforced (Seatbelt on macOS, Landlock on Linux) for read_file and
86
+ * every child process; grok refuses to start when it cannot be applied.
87
+ * grok's own docs say child-process network blocking is Linux-only, so
88
+ * extract does not select grok except on linux: it falls through to claude,
89
+ * then codex. grok has no switch that skips user config: it always loads
90
+ * ~/.grok/config.toml and the Claude-compatible permission rules in
91
+ * ~/.claude/settings*.json. The turn therefore runs with HOME,
92
+ * XDG_CONFIG_HOME, XDG_DATA_HOME and CLAUDE_CONFIG_DIR pointed at a fresh
93
+ * isolated directory carrying only a private auth.json login copy, removed
94
+ * when the turn ends, and with an env
95
+ * allowlist instead of the parent process environment. GROK_SANDBOX,
96
+ * GROK_SANDBOX_AUTO_ALLOW_BASH, GROK_CONFIG and GROK_CONFIG_PATH are not on
97
+ * that allowlist, and the GROK_{CLAUDE,CURSOR}_*_ENABLED scans are off.
98
+ * A refused command ends the grok turn (stopReason "cancelled") instead of
99
+ * returning an error to the model. The `end` event carries num_turns and
100
+ * total_cost_usd (cost may be absent; then 0, as for codex).
101
+ * `grok --help` is probed once per grok binary path. A grok without every flag above
102
+ * is never run: the step falls back to claude, then codex, when that tool
103
+ * is installed and signed in, and otherwise fails the run naming the grok
104
+ * version it needs. A main bot on grok with no grok installed falls back the
105
+ * same way.
54
106
  */
55
107
  import * as fs from "node:fs";
56
108
  import * as os from "node:os";
@@ -59,8 +111,12 @@ import yaml from "js-yaml";
59
111
  import { findPriorSignals, normalizeSignalTitle, priorSignalPath } from "../prior-signals.js";
60
112
  import { splitFrontmatter } from "../../hot-channels/signals-pass.js";
61
113
  import { audienceKey } from "../../hot-channels/audience.js";
62
- import { readBotConfig, effectiveBotKind, isBotRuntimeId } from "../../bot/config.js";
114
+ import { isBotRuntimeId } from "../../bot/config.js";
115
+ import { resolveExecutiveBot } from "../../bot/executive.js";
63
116
  import { botsRoot } from "../../bot/paths.js";
117
+ import { parseClaudeAuthStatus } from "../../bot/runtime/claude.js";
118
+ import { parseCodexLoginStatus } from "../../bot/runtime/codex.js";
119
+ import { SIGN_IN_CHECK_TIMEOUT_MS } from "../../bot/runtime-sign-in.js";
64
120
  import { CLAUDE_LOGGED_OUT_RE, CLAUDE_ISOLATION_ARGS, parseClaudeSignals } from "../../hot-channels/signals-pass.js";
65
121
  import { assertAllowedPath, assertNoEscapingLinks, guardedRemove, guardedWrite, realRelPath } from "../write-guard.js";
66
122
  export const EXTRACT_SIGNAL_TYPES = [
@@ -88,27 +144,48 @@ export function worklistTimeoutMs(limit) {
88
144
  }
89
145
  export const CODEX_PERMISSION_PROFILE = "hq_signals_extract";
90
146
  export const CANDIDATE_WRAPPER_NAME = "write-candidate.sh";
147
+ /** The sandbox profile the step writes to <turn dir>/.grok/sandbox.toml for a grok turn. */
148
+ export const GROK_SANDBOX_PROFILE = "hq_signals_extract";
149
+ export const GROK_SANDBOX_FILE = path.join(".grok", "sandbox.toml");
150
+ /** The oldest grok whose `--help` lists every flag in GROK_EXTRACT_FLAGS. */
151
+ export const GROK_MIN_VERSION = "1.0.70";
152
+ /** Flags a grok turn needs; one missing from `--help` means the installed grok cannot be locked down. */
153
+ export const GROK_EXTRACT_FLAGS = [
154
+ "--permission-mode",
155
+ "--tools",
156
+ "--disallowed-tools",
157
+ "--allow",
158
+ "--deny",
159
+ "--sandbox",
160
+ "--disable-web-search",
161
+ "--no-subagents",
162
+ "--max-turns",
163
+ "--cwd",
164
+ "--output-format",
165
+ ];
166
+ /**
167
+ * grok's built-in read-only shell list (its permissions guide, "Read-Only
168
+ * Shell Commands"): auto-approved even under dontAsk, so each is denied by
169
+ * name. A Bash rule without `*` is a prefix match, so `Bash(cat)` also covers
170
+ * `cat` with any arguments.
171
+ */
172
+ export const GROK_READ_ONLY_COMMANDS = [
173
+ "ls", "cat", "pwd", "date", "whoami", "hostname", "uptime", "ps",
174
+ "head", "tail", "wc", "sort", "uniq", "tr", "cut",
175
+ "mkdir", "touch", "git", "grep", "rg", "kubectl",
176
+ ];
177
+ /** Environment keys that could widen or relocate a grok turn's configuration. */
178
+ const GROK_ENV_DROP = ["GROK_SANDBOX", "GROK_SANDBOX_AUTO_ALLOW_BASH", "GROK_CONFIG", "GROK_CONFIG_PATH"];
179
+ /** The Claude and Cursor configuration scans grok runs at start, turned off for a turn. */
180
+ const GROK_COMPAT_SCANS = ["SKILLS", "RULES", "AGENTS", "MCPS", "HOOKS"].flatMap((s) => [`GROK_CLAUDE_${s}_ENABLED`, `GROK_CURSOR_${s}_ENABLED`]);
91
181
  /** The only tools a claude turn may use: Read inside the channel folder and the pinned wrapper. */
92
182
  export function claudeAllowedTools(channelDir, wrapperPath) {
93
183
  // A rule path that starts with `//` is absolute.
94
184
  return [`Read(/${channelDir}/**)`, `Bash(bash ${wrapperPath} *)`];
95
185
  }
96
- /** First personal bot under ~/.hq/bots (by name) with a readable config. */
186
+ /** The Executive bot's runtime (lib/bot/executive.ts), or null when there is no personal bot. */
97
187
  export function defaultResolveBotRuntime(root = botsRoot()) {
98
- if (!fs.existsSync(root))
99
- return null;
100
- const names = fs.readdirSync(root).sort();
101
- const configs = names
102
- .map((n) => {
103
- try {
104
- return readBotConfig(path.join(root, n));
105
- }
106
- catch {
107
- return null;
108
- }
109
- })
110
- .filter((c) => c !== null);
111
- const main = configs.find((c) => effectiveBotKind(c) === "personal") ?? null;
188
+ const main = resolveExecutiveBot({ root })?.config ?? null;
112
189
  return main && isBotRuntimeId(main.runtime) ? main.runtime : null;
113
190
  }
114
191
  function yamlField(text, key) {
@@ -217,14 +294,21 @@ export function buildExtractPrompt(input) {
217
294
  "Rules:",
218
295
  input.runtime === "codex"
219
296
  ? "- Read the item with a shell command such as cat. Only files in the item's channel folder are readable."
220
- : "- Read the item with the Read tool. Only files in the item's channel folder are readable.",
297
+ : input.runtime === "grok"
298
+ ? "- Read the item with the read_file tool. Only files in the item's channel folder are readable."
299
+ : "- Read the item with the Read tool. Only files in the item's channel folder are readable.",
221
300
  `- Write candidates ONLY with: bash ${input.wrapperPath} --kind signal|entity --type <type> --body "<text>"`,
222
301
  "- That command already fixes the company, audience and source ref for this item. Do not pass --company, --audience, --source-ref or --body-file; it refuses them.",
302
+ ...(input.runtime === "grok"
303
+ ? ['- You have no terminal tool. Return JSON only: {"commands":["bash ..."]}. HQ executes validated commands after your turn. At most 8 commands; use an empty array for no candidates.', "- Use exactly the flags above in that order; quote the body as a literal. No pipes, no &&, no ;, no substitutions, redirections or other commands outside quoted text."]
304
+ : []),
223
305
  `- Signal types (exactly these): ${EXTRACT_SIGNAL_TYPES.join(", ")}.`,
224
306
  `- Entity types: ${ENTITY_TYPES.join(", ")}.`,
225
307
  "- Every signal body must end with a citation: a one-sentence quote from the item or its timestamp, for example: (cite: \"we ship Friday\") or (cite: 00:12:31).",
226
308
  "- No other command can run, and no other file can be written.",
227
- "- When finished, reply with one line: the number of candidates written.",
309
+ input.runtime === "grok"
310
+ ? '- Return only the JSON commands object, without markdown fences. This overrides the skill instructions about executing commands.'
311
+ : "- When finished, reply with one line: the number of candidates written.",
228
312
  "",
229
313
  ...(input.priorSignals?.length ? [
230
314
  "Already extracted for this source; do not repeat; return `update: <id>` to amend one",
@@ -290,11 +374,22 @@ export function buildCandidateWrapper(input) {
290
374
  "",
291
375
  ].join("\n");
292
376
  }
293
- /** Parse a stream-json transcript (or a codex --json event stream). */
377
+ /**
378
+ * Parse a stream-json transcript (claude), a codex --json event stream, or a
379
+ * grok streaming-json event stream.
380
+ *
381
+ * grok writes `{"type":"text","data":…}` deltas and one terminal
382
+ * `{"type":"end","stopReason":…,"num_turns":n,"total_cost_usd":x}`; a refused
383
+ * tool call ends the turn with stopReason "cancelled", and an API failure is
384
+ * `{"type":"error","message":…}`. Both are mapped to an error result so the
385
+ * item fails and is retried; only "end_turn" is success.
386
+ */
294
387
  export function parseTurnOutput(stdout) {
295
388
  let result = null;
296
389
  let codexTurns = 0;
297
390
  let codexDone = false;
391
+ let grokText = "";
392
+ let grokError;
298
393
  for (const line of stdout.split("\n")) {
299
394
  const t = line.trim();
300
395
  if (!t.startsWith("{"))
@@ -317,6 +412,25 @@ export function parseTurnOutput(stdout) {
317
412
  }
318
413
  if (o.type === "turn.failed")
319
414
  codexTurns += 1;
415
+ if (o.type === "text" && typeof o.data === "string")
416
+ grokText += o.data;
417
+ if (o.type === "error" && typeof o.message === "string")
418
+ grokError = o.message;
419
+ if (o.type === "end") {
420
+ const stop = typeof o.stopReason === "string" ? o.stopReason : "";
421
+ const ok = /^end_?turn$/i.test(stop);
422
+ result = {
423
+ type: "result",
424
+ subtype: ok ? "success" : stop || "no stop reason",
425
+ is_error: !ok,
426
+ result: ok ? grokText : `grok stopped: ${stop || "no stop reason"}`,
427
+ ...(typeof o.num_turns === "number" ? { num_turns: o.num_turns } : {}),
428
+ ...(typeof o.total_cost_usd === "number" ? { total_cost_usd: o.total_cost_usd } : {}),
429
+ };
430
+ }
431
+ }
432
+ if (!result && grokError !== undefined) {
433
+ result = { type: "result", subtype: "error", is_error: true, result: grokError };
320
434
  }
321
435
  if (result) {
322
436
  const turns = typeof result.num_turns === "number" ? result.num_turns : 1;
@@ -564,24 +678,315 @@ function toolPrefixRoots(bins, envPath, hqRoot) {
564
678
  }
565
679
  return [...new Set(roots)];
566
680
  }
567
- /** TOML inline table for the codex permission profile's filesystem entries. */
568
- export function codexFilesystemProfile(scope, codexBin, envPath) {
569
- const entries = [[":minimal", "read"]];
570
- for (const r of toolPrefixRoots([codexBin, "bash"], envPath, scope.hqRoot))
571
- entries.push([r, "read"]);
572
- entries.push([scope.turnDir, "read"]);
573
- entries.push([path.join(fs.realpathSync(scope.hqRoot), "core", "scripts"), "read"]);
574
- const prefs = path.join(fs.realpathSync(scope.hqRoot), "companies", scope.company, "settings", "knowledge");
681
+ /**
682
+ * The HQ paths a sandboxed turn may touch, beyond the turn dir and the tool
683
+ * install prefixes: core/scripts and the knowledge preferences the candidate
684
+ * script reads, the item's channel folder, and the company's _candidates
685
+ * folders it writes.
686
+ */
687
+ function hqTurnGrants(scope) {
688
+ const hq = fs.realpathSync(scope.hqRoot);
689
+ const entries = [[path.join(hq, "core", "scripts"), "read"]];
690
+ const prefs = path.join(hq, "companies", scope.company, "settings", "knowledge");
575
691
  if (fs.existsSync(prefs))
576
692
  entries.push([prefs, "read"]);
577
- const personalPrefs = path.join(fs.realpathSync(scope.hqRoot), "personal", "settings", "knowledge-preferences.yaml");
693
+ const personalPrefs = path.join(hq, "personal", "settings", "knowledge-preferences.yaml");
578
694
  if (fs.existsSync(personalPrefs))
579
695
  entries.push([personalPrefs, "read"]);
580
696
  entries.push([scope.channelDir, "read"]);
581
697
  for (const d of scope.candidateDirs)
582
698
  entries.push([d, "write"]);
699
+ return entries;
700
+ }
701
+ /** TOML inline table for the codex permission profile's filesystem entries. */
702
+ export function codexFilesystemProfile(scope, codexBin, envPath) {
703
+ const entries = [[":minimal", "read"]];
704
+ for (const r of toolPrefixRoots([codexBin, "bash"], envPath, scope.hqRoot))
705
+ entries.push([r, "read"]);
706
+ entries.push([scope.turnDir, "read"]);
707
+ entries.push(...hqTurnGrants(scope));
583
708
  return `{${entries.map(([k, v]) => `${JSON.stringify(k)}=${JSON.stringify(v)}`).join(",")}}`;
584
709
  }
710
+ /**
711
+ * The sandbox profile for a grok turn, written to <turn dir>/.grok/sandbox.toml.
712
+ * grok's `strict` already covers the turn dir (cwd), system paths and ~/.grok;
713
+ * the grants add bash's install prefix (Homebrew bash loads from it) and the
714
+ * read-only HQ paths of hqTurnGrants. Candidate folders are not granted:
715
+ * the host writes them after the turn, outside this sandbox.
716
+ */
717
+ export function grokSandboxProfile(scope, envPath) {
718
+ const reads = [...toolPrefixRoots(["bash"], envPath, scope.hqRoot)];
719
+ for (const [p, mode] of hqTurnGrants(scope))
720
+ if (mode === "read")
721
+ reads.push(p);
722
+ const list = (items) => `[${items.map((p) => JSON.stringify(p)).join(", ")}]`;
723
+ return [
724
+ `[profiles.${GROK_SANDBOX_PROFILE}]`,
725
+ 'extends = "strict"',
726
+ "restrict_network = true",
727
+ `read_only = ${list(reads)}`,
728
+ "read_write = []",
729
+ "",
730
+ ].join("\n");
731
+ }
732
+ /** Grok can read the source; candidate writing belongs to the host. */
733
+ export function grokAllowRules(channelDir) {
734
+ return [`Read(${channelDir}/**)`];
735
+ }
736
+ /** Parse literal arguments only. No shell ever interprets model output. */
737
+ export function grokCandidateArgv(command, wrapperPath) {
738
+ const words = [];
739
+ let i = 0;
740
+ while (i < command.length) {
741
+ while (command[i] === " " || command[i] === "\t")
742
+ i++;
743
+ if (i === command.length)
744
+ break;
745
+ let word = "";
746
+ while (i < command.length && command[i] !== " " && command[i] !== "\t") {
747
+ const ch = command[i++];
748
+ if (ch === "'" || ch === '"') {
749
+ const quote = ch;
750
+ let closed = false;
751
+ while (i < command.length) {
752
+ const c = command[i++];
753
+ if (c === quote) {
754
+ closed = true;
755
+ break;
756
+ }
757
+ if (quote === '"' && (c === "$" || c === "`"))
758
+ return null;
759
+ if (quote === '"' && c === "\\") {
760
+ const next = command[i++];
761
+ if (next !== '"' && next !== "\\")
762
+ return null;
763
+ word += next;
764
+ }
765
+ else
766
+ word += c;
767
+ }
768
+ if (!closed)
769
+ return null;
770
+ }
771
+ else if (ch === "\\" && command[i] === "'") {
772
+ word += command[i++];
773
+ }
774
+ else if (/^[a-zA-Z0-9_./:-]$/.test(ch))
775
+ word += ch;
776
+ else
777
+ return null;
778
+ }
779
+ words.push(word);
780
+ }
781
+ if (words.length !== 8 || words[0] !== "bash" || words[1] !== wrapperPath ||
782
+ words[2] !== "--kind" || !["signal", "entity"].includes(words[3]) ||
783
+ words[4] !== "--type" || !/^[a-z][a-z0-9_-]*$/.test(words[5]) ||
784
+ words[6] !== "--body" || !words[7] || words.some((w) => w.includes("\0")))
785
+ return null;
786
+ return words.slice(1);
787
+ }
788
+ /** True when the writer on disk is still the script this turn generated. */
789
+ function wrapperMatchesGenerated(wrapperPath, expected) {
790
+ try {
791
+ return fs.readFileSync(wrapperPath, "utf8") === expected;
792
+ }
793
+ catch {
794
+ return false;
795
+ }
796
+ }
797
+ /**
798
+ * Validate the whole batch before writing. Only the host executes the pinned
799
+ * writer. When `expectedWrapper` is set, the file is compared to that text
800
+ * immediately before each exec. Strict can write the turn directory, so a
801
+ * writer that no longer matches is not run.
802
+ */
803
+ export function executeGrokCandidates(text, wrapperPath, spawn, opts, expectedWrapper) {
804
+ let data;
805
+ try {
806
+ data = JSON.parse(text);
807
+ }
808
+ catch {
809
+ return "grok must return a JSON commands array";
810
+ }
811
+ if (!data || typeof data !== "object" || !("commands" in data) || !Array.isArray(data.commands) || data.commands.length > 8) {
812
+ return "grok must return at most 8 candidate commands";
813
+ }
814
+ const batch = [];
815
+ for (const command of data.commands) {
816
+ const argv = typeof command === "string" ? grokCandidateArgv(command, wrapperPath) : null;
817
+ if (!argv)
818
+ return "refused: command is not the pinned candidate wrapper";
819
+ batch.push(argv);
820
+ }
821
+ for (const argv of batch) {
822
+ if (expectedWrapper !== undefined && !wrapperMatchesGenerated(wrapperPath, expectedWrapper)) {
823
+ return "pinned candidate writer does not match the generated script";
824
+ }
825
+ const result = spawn("/bin/bash", argv, opts);
826
+ if (result.error || result.status !== 0)
827
+ return "pinned candidate writer failed";
828
+ }
829
+ return undefined;
830
+ }
831
+ /**
832
+ * Read denies for the grok login. Grok matches a `~` tool path literally and
833
+ * expands `~` only after that check, so the absolute temp home is not enough.
834
+ * `realHomes` is every home the original login might live under (the process
835
+ * HOME we copied from, and os.homedir() when that differs).
836
+ */
837
+ export function grokAuthReadDenies(tempHome, realHomes) {
838
+ // `**` crosses `/`. The unrooted pattern matches auth.json under any
839
+ // directory, including a spelling the three homes do not list. The exact
840
+ // `~/.grok/auth.json` is the path the model can name without the temp dir.
841
+ const spellings = ["~/.grok/**", "~/.grok/auth.json", "**/.grok/auth.json"];
842
+ const add = (home) => {
843
+ for (const suffix of [".grok/**", path.join(".grok", "auth.json")]) {
844
+ const spelling = path.join(home, suffix);
845
+ if (!spellings.includes(spelling))
846
+ spellings.push(spelling);
847
+ }
848
+ try {
849
+ const real = fs.realpathSync(home);
850
+ if (real !== home)
851
+ add(real);
852
+ }
853
+ catch {
854
+ // The home may be created and removed around the turn. The path we were
855
+ // given is still denied above.
856
+ }
857
+ };
858
+ add(tempHome);
859
+ for (const home of realHomes)
860
+ add(home);
861
+ return spellings.map((p) => `Read(${p})`);
862
+ }
863
+ /** Deny rules of a grok turn: every other tool class, the login file, and the read-only shell list. */
864
+ export function grokDenyRules(tempHome, realHomes) {
865
+ return [
866
+ "Bash",
867
+ "MCPTool",
868
+ "WebFetch",
869
+ "WebSearch",
870
+ "Edit",
871
+ "Write",
872
+ "Grep",
873
+ ...grokAuthReadDenies(tempHome, realHomes),
874
+ ...GROK_READ_ONLY_COMMANDS.map((c) => `Bash(${c})`),
875
+ ];
876
+ }
877
+ export function grokTurnArgs(prompt, scope, maxTurns, tempHome, realHomes) {
878
+ return [
879
+ "-p",
880
+ prompt,
881
+ "--output-format",
882
+ "streaming-json",
883
+ "--cwd",
884
+ scope.turnDir,
885
+ "--permission-mode",
886
+ "dontAsk",
887
+ "--tools",
888
+ "read_file",
889
+ "--disallowed-tools",
890
+ "search_tool,use_tool,run_terminal_cmd",
891
+ "--disable-web-search",
892
+ "--no-subagents",
893
+ "--max-turns",
894
+ String(maxTurns),
895
+ "--sandbox",
896
+ GROK_SANDBOX_PROFILE,
897
+ ...grokAllowRules(scope.channelDir).flatMap((r) => ["--allow", r]),
898
+ ...grokDenyRules(tempHome, realHomes).flatMap((r) => ["--deny", r]),
899
+ ];
900
+ }
901
+ /** Parent env keys copied into a grok turn. Everything else, including credentials, stays out. */
902
+ export const GROK_ENV_ALLOW = [
903
+ "PATH", "HOME", "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "LC_CTYPE",
904
+ "USER", "LOGNAME", "SHELL", "SystemRoot", "COMSPEC", "PATHEXT", "WINDIR",
905
+ "TERM", "TZ", "HQ_ROOT",
906
+ ];
907
+ /** The turn's environment for grok: an allowlist, no sandbox or config overrides, no Claude or Cursor configuration scans. */
908
+ export function grokTurnEnv(base) {
909
+ const env = {};
910
+ for (const k of GROK_ENV_ALLOW)
911
+ if (base[k] !== undefined)
912
+ env[k] = base[k];
913
+ for (const k of GROK_ENV_DROP)
914
+ delete env[k];
915
+ for (const k of GROK_COMPAT_SCANS)
916
+ env[k] = "0";
917
+ return env;
918
+ }
919
+ /** Whether `grok --help` lists every flag a locked-down turn needs, and streaming-json output. */
920
+ export function grokExtractSupportFromHelp(helpText) {
921
+ const missing = [];
922
+ for (const flag of GROK_EXTRACT_FLAGS) {
923
+ if (!new RegExp(`(^|\\s)${flag}(\\s|$|<|=)`).test(helpText))
924
+ missing.push(flag);
925
+ }
926
+ if (!missing.includes("--output-format") && !/\bstreaming-json\b/.test(helpText))
927
+ missing.push("--output-format streaming-json");
928
+ return missing.length ? { ok: false, missing } : { ok: true };
929
+ }
930
+ const cachedGrokSupport = new Map();
931
+ export function resetGrokExtractProbeCache() {
932
+ cachedGrokSupport.clear();
933
+ }
934
+ /** Probe `grok --help` once per grok binary path (empty or failed output counts as every flag missing). */
935
+ export function probeGrokExtractSupport(grokBin, readHelp) {
936
+ const hit = cachedGrokSupport.get(grokBin);
937
+ if (hit)
938
+ return hit;
939
+ let help;
940
+ try {
941
+ help = readHelp();
942
+ }
943
+ catch {
944
+ help = "";
945
+ }
946
+ const support = grokExtractSupportFromHelp(help);
947
+ cachedGrokSupport.set(grokBin, support);
948
+ return support;
949
+ }
950
+ /**
951
+ * Which runtime runs the turns. The main bot's runtime, except that a grok
952
+ * that is missing or cannot be locked down is never run: the step uses
953
+ * claude, then codex, when that tool is installed and signed in, and
954
+ * otherwise fails. The claude and codex checks run only when needed.
955
+ */
956
+ export function chooseExtractRuntime(main, avail, platform = process.platform) {
957
+ if (main !== "grok")
958
+ return { runtime: main };
959
+ if (platform !== "linux") {
960
+ const reason = `grok only blocks child-process network on linux, so extract will not use it on ${platform}`;
961
+ for (const other of ["claude", "codex"]) {
962
+ const t = avail[other]();
963
+ if (t.installed && t.signedIn === true)
964
+ return { runtime: other, fallback: `${reason}; using ${other}` };
965
+ }
966
+ return { error: `${reason}; claude and codex are not installed or not signed in. Install grok ${GROK_MIN_VERSION} or newer on linux, or sign in to claude or codex, then run again.` };
967
+ }
968
+ const grok = avail.grok();
969
+ if (grok.installed && grok.support.ok)
970
+ return { runtime: "grok" };
971
+ const reason = !grok.installed
972
+ ? "the main bot runs on grok but grok is not installed"
973
+ : `the installed grok lacks ${grok.support.ok ? "" : grok.support.missing.join(", ")} (extract needs grok ${GROK_MIN_VERSION} or newer)`;
974
+ for (const other of ["claude", "codex"]) {
975
+ const t = avail[other]();
976
+ if (t.installed && t.signedIn === true)
977
+ return { runtime: other, fallback: `${reason}; using ${other}` };
978
+ }
979
+ return { error: `${reason}; claude and codex are not installed or not signed in. Install grok ${GROK_MIN_VERSION} or newer, or sign in to claude or codex, then run again.` };
980
+ }
981
+ /** Installed-and-signed-in check for a fallback tool, through the step's spawn. */
982
+ function toolAvailability(ctx, bin, statusArgs, parse) {
983
+ if (!resolveOnPath(bin, process.env.PATH))
984
+ return { installed: false, signedIn: null };
985
+ const res = ctx.spawn(bin, statusArgs, { env: { ...process.env, HQ_NO_ENSURE_HQ_DESKTOP: "1" }, timeoutMs: SIGN_IN_CHECK_TIMEOUT_MS });
986
+ if (res.error)
987
+ return { installed: true, signedIn: null };
988
+ return { installed: true, signedIn: parse({ code: res.status, signal: null, stdout: res.stdout, stderr: res.stderr }) };
989
+ }
585
990
  export function claudeTurnArgs(prompt, scope, maxTurns, budgetUsd) {
586
991
  return [
587
992
  "-p",
@@ -635,11 +1040,49 @@ export function codexTurnArgs(prompt, scope, codexBin, envPath) {
635
1040
  }
636
1041
  function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
637
1042
  const cwd = scope.turnDir;
638
- const cmd = runtime === "claude" ? opts.claudeBin : opts.codexBin;
639
- const args = runtime === "claude"
1043
+ const cmd = runtime === "claude" ? opts.claudeBin : runtime === "grok" ? opts.grokBin : opts.codexBin;
1044
+ let args = runtime === "claude"
640
1045
  ? claudeTurnArgs(prompt, scope, ctx.maxTurns, budgetUsd)
641
- : codexTurnArgs(prompt, scope, opts.codexBin, process.env.PATH);
642
- const res = ctx.spawn(cmd, args, { cwd, env: { ...process.env, HQ_ROOT: ctx.hqRoot }, timeoutMs: opts.turnTimeoutMs });
1046
+ : runtime === "codex"
1047
+ ? codexTurnArgs(prompt, scope, opts.codexBin, process.env.PATH)
1048
+ : [];
1049
+ let env = { ...process.env, HQ_ROOT: ctx.hqRoot };
1050
+ let grokHome;
1051
+ let res;
1052
+ try {
1053
+ if (runtime === "grok") {
1054
+ const sourceHome = env.HOME ?? os.homedir();
1055
+ const realHomes = [...new Set([sourceHome, os.homedir()])];
1056
+ const sourceAuth = path.join(sourceHome, ".grok", "auth.json");
1057
+ grokHome = fs.mkdtempSync(path.join(os.tmpdir(), "hq-grok-home-"));
1058
+ // Preserve login without inheriting configuration, hooks, or permissions.
1059
+ const authDir = path.join(grokHome, ".grok");
1060
+ fs.mkdirSync(authDir, { mode: 0o700 });
1061
+ if (fs.existsSync(sourceAuth)) {
1062
+ const authCopy = path.join(authDir, "auth.json");
1063
+ fs.copyFileSync(sourceAuth, authCopy, fs.constants.COPYFILE_EXCL);
1064
+ fs.chmodSync(authCopy, 0o600);
1065
+ }
1066
+ // The profile named by --sandbox; grok refuses to start without it.
1067
+ const profile = path.join(scope.turnDir, GROK_SANDBOX_FILE);
1068
+ fs.mkdirSync(path.dirname(profile), { recursive: true });
1069
+ fs.writeFileSync(profile, grokSandboxProfile(scope, process.env.PATH), { mode: 0o600 });
1070
+ env = grokTurnEnv(env);
1071
+ env.HOME = grokHome;
1072
+ env.XDG_CONFIG_HOME = path.join(grokHome, "xdg");
1073
+ env.XDG_DATA_HOME = path.join(grokHome, "xdg-data");
1074
+ env.CLAUDE_CONFIG_DIR = path.join(grokHome, "claude");
1075
+ env.HQ_ROOT = ctx.hqRoot;
1076
+ for (const dir of [env.XDG_CONFIG_HOME, env.XDG_DATA_HOME, env.CLAUDE_CONFIG_DIR])
1077
+ fs.mkdirSync(dir, { recursive: true });
1078
+ args = grokTurnArgs(prompt, scope, ctx.maxTurns, grokHome, realHomes);
1079
+ }
1080
+ res = ctx.spawn(cmd, args, { cwd, env, timeoutMs: opts.turnTimeoutMs });
1081
+ }
1082
+ finally {
1083
+ if (grokHome)
1084
+ fs.rmSync(grokHome, { recursive: true, force: true });
1085
+ }
643
1086
  const parsed = parseTurnOutput(res.stdout);
644
1087
  const all = `${res.stderr}\n${res.stdout}`;
645
1088
  if (res.error) {
@@ -656,9 +1099,22 @@ function runTurn(ctx, runtime, prompt, scope, budgetUsd, opts) {
656
1099
  return { ok: false, error: `${runtime} printed no result event`, errorKind: "other", turns: 0, costUsd: 0 };
657
1100
  if (parsed.result.is_error === true || (typeof parsed.result.subtype === "string" && parsed.result.subtype !== "success")) {
658
1101
  const text = typeof parsed.result.result === "string" ? parsed.result.result : String(parsed.result.subtype ?? "");
659
- const c = classifyFailure(text, `${runtime} turn failed: ${text.slice(0, 200) || "error result"}`);
1102
+ // grok names the refused command on stderr, not in the stream.
1103
+ const refused = runtime === "grok" ? /^permission required: .*$/m.exec(res.stderr)?.[0] : undefined;
1104
+ const detail = refused ? `${text} (${refused})` : text;
1105
+ const c = classifyFailure(detail, `${runtime} turn failed: ${detail.slice(0, 300) || "error result"}`);
660
1106
  return { ok: false, ...c, turns: parsed.turns, costUsd: parsed.costUsd };
661
1107
  }
1108
+ if (runtime === "grok") {
1109
+ if (scope.wrapperBody === undefined) {
1110
+ return { ok: false, error: "pinned candidate writer is missing", errorKind: "other", turns: parsed.turns, costUsd: parsed.costUsd };
1111
+ }
1112
+ const error = executeGrokCandidates(String(parsed.result.result ?? ""), scope.wrapperPath, ctx.spawn, {
1113
+ cwd, env: grokTurnEnv({ ...process.env, HQ_ROOT: ctx.hqRoot }), timeoutMs: SCRIPT_TIMEOUT_MS,
1114
+ }, scope.wrapperBody);
1115
+ if (error)
1116
+ return { ok: false, error, errorKind: "other", turns: parsed.turns, costUsd: parsed.costUsd };
1117
+ }
662
1118
  return { ok: true, turns: parsed.turns, costUsd: parsed.costUsd };
663
1119
  }
664
1120
  export async function extractPartialDocument(ctx, doc, prior) {
@@ -695,17 +1151,34 @@ export function createExtractStep(options = {}) {
695
1151
  if (channels.length === 0 && unrunRedo.length === 0) {
696
1152
  return { status: "skipped", itemsIn: 0, itemsOut: 0, skippedReason: "no-sources", ...empty };
697
1153
  }
698
- const runtime = (options.resolveBotRuntime ?? defaultResolveBotRuntime)() ?? options.runtime ?? "claude";
699
- if (runtime === "grok") {
700
- return {
701
- status: "failed",
702
- itemsIn: 0,
703
- itemsOut: 0,
704
- error: "grok has no restricted tool mode; extract needs claude or codex",
705
- errorKind: "other",
706
- ...empty,
707
- };
1154
+ const turnOpts = {
1155
+ claudeBin: options.claudeBin ?? "claude",
1156
+ codexBin: options.codexBin ?? "codex",
1157
+ grokBin: options.grokBin ?? "grok",
1158
+ turnTimeoutMs: options.turnTimeoutMs ?? DEFAULT_TURN_TIMEOUT_MS,
1159
+ };
1160
+ const mainRuntime = (options.resolveBotRuntime ?? defaultResolveBotRuntime)() ?? options.runtime ?? "claude";
1161
+ const choice = chooseExtractRuntime(mainRuntime, {
1162
+ grok: () => {
1163
+ const resolved = resolveOnPath(turnOpts.grokBin, process.env.PATH);
1164
+ if (!resolved)
1165
+ return { installed: false };
1166
+ turnOpts.grokBin = fs.realpathSync(resolved);
1167
+ const support = probeGrokExtractSupport(turnOpts.grokBin, () => {
1168
+ const r = ctx.spawn(turnOpts.grokBin, ["--help"], { env: grokTurnEnv(process.env), timeoutMs: SIGN_IN_CHECK_TIMEOUT_MS });
1169
+ if (r.error)
1170
+ throw r.error;
1171
+ return `${r.stdout}\n${r.stderr}`;
1172
+ });
1173
+ return { installed: true, support };
1174
+ },
1175
+ claude: () => toolAvailability(ctx, turnOpts.claudeBin, ["auth", "status", "--json"], parseClaudeAuthStatus),
1176
+ codex: () => toolAvailability(ctx, turnOpts.codexBin, ["login", "status"], parseCodexLoginStatus),
1177
+ }, options.platform ?? process.platform);
1178
+ if ("error" in choice) {
1179
+ return { status: "failed", itemsIn: 0, itemsOut: 0, error: choice.error, errorKind: "config", ...empty };
708
1180
  }
1181
+ const runtime = choice.runtime;
709
1182
  const scripts = path.join(ctx.hqRoot, "core", "scripts");
710
1183
  const worklist = path.join(scripts, "ontology-source-worklist.sh");
711
1184
  const skillPath = path.join(ctx.hqRoot, "core", "workers", "public", "ontology", "skills", "process-source.md");
@@ -713,11 +1186,6 @@ export function createExtractStep(options = {}) {
713
1186
  return { status: "skipped", itemsIn: 0, itemsOut: 0, skippedReason: "ontology-worker-missing", ...empty };
714
1187
  }
715
1188
  const skillText = fs.readFileSync(skillPath, "utf8");
716
- const turnOpts = {
717
- claudeBin: options.claudeBin ?? "claude",
718
- codexBin: options.codexBin ?? "codex",
719
- turnTimeoutMs: options.turnTimeoutMs ?? DEFAULT_TURN_TIMEOUT_MS,
720
- };
721
1189
  const env = { ...process.env, HQ_ROOT: ctx.hqRoot };
722
1190
  const limit = options.worklistLimit ?? DEFAULT_WORKLIST_LIMIT;
723
1191
  let itemsIn = 0;
@@ -764,7 +1232,7 @@ export function createExtractStep(options = {}) {
764
1232
  errorKind = "other";
765
1233
  continue;
766
1234
  }
767
- if (runtime === "codex") {
1235
+ if (runtime === "codex" || runtime === "grok") {
768
1236
  try {
769
1237
  candidateDirs = ["signals", "ontology"].map((store) => {
770
1238
  const dir = assertAllowedPath(ctx.hqRoot, `companies/${ctx.company}/${store}/_candidates`, { company: ctx.company });
@@ -842,8 +1310,9 @@ export function createExtractStep(options = {}) {
842
1310
  const before = allCandidateFiles(ctx.hqRoot);
843
1311
  let turn;
844
1312
  try {
845
- fs.writeFileSync(wrapperPath, buildCandidateWrapper({ hqRoot: ctx.hqRoot, company: ctx.company, audience: (item.audience ?? []).join(","), sourceRef }), { mode: 0o700 });
846
- const scope = { hqRoot: ctx.hqRoot, company: ctx.company, channelDir, turnDir, wrapperPath, candidateDirs };
1313
+ const wrapperBody = buildCandidateWrapper({ hqRoot: ctx.hqRoot, company: ctx.company, audience: (item.audience ?? []).join(","), sourceRef });
1314
+ fs.writeFileSync(wrapperPath, wrapperBody, { mode: 0o700 });
1315
+ const scope = { hqRoot: ctx.hqRoot, company: ctx.company, channelDir, turnDir, wrapperPath, candidateDirs, wrapperBody };
847
1316
  const prompt = buildExtractPrompt({
848
1317
  skillText,
849
1318
  sourceRef,
@@ -853,7 +1322,7 @@ export function createExtractStep(options = {}) {
853
1322
  item,
854
1323
  itemPath: path.join(channelDir, path.basename(item.file)),
855
1324
  wrapperPath,
856
- runtime: runtime === "codex" ? "codex" : "claude",
1325
+ runtime,
857
1326
  });
858
1327
  turn = runTurn(ctx, runtime, prompt, scope, Math.max(0, remaining), turnOpts);
859
1328
  }
@@ -914,7 +1383,7 @@ export function createExtractStep(options = {}) {
914
1383
  ...(failures.length ? { failures } : {}),
915
1384
  ...(skippedItems.length ? { skippedItems } : {}),
916
1385
  ...(rejected ? { rejectedCandidates: rejected } : {}),
917
- detail: { new: itemsOut, updated, skipped },
1386
+ detail: { new: itemsOut, updated, skipped, runtime, ...(choice.fallback ? { fallback: choice.fallback } : {}) },
918
1387
  };
919
1388
  if (budgetStop) {
920
1389
  result.status = "partial";