@indigoai-us/hq-cli 5.60.0 → 5.62.0

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 (98) hide show
  1. package/dist/commands/agents.d.ts +109 -0
  2. package/dist/commands/agents.js +385 -0
  3. package/dist/commands/db-migrate.d.ts +6 -0
  4. package/dist/commands/db-migrate.js +42 -0
  5. package/dist/commands/db-provision.d.ts +15 -0
  6. package/dist/commands/db-provision.js +78 -0
  7. package/dist/commands/db-sql.d.ts +9 -0
  8. package/dist/commands/db-sql.js +81 -0
  9. package/dist/commands/db-status.d.ts +7 -0
  10. package/dist/commands/db-status.js +70 -0
  11. package/dist/commands/db.d.ts +9 -0
  12. package/dist/commands/db.js +23 -0
  13. package/dist/commands/integrations.d.ts +78 -0
  14. package/dist/commands/integrations.js +309 -0
  15. package/dist/commands/members.js +4 -4
  16. package/dist/commands/outposts.d.ts +60 -0
  17. package/dist/commands/outposts.js +255 -0
  18. package/dist/commands/pack-install.d.ts +7 -1
  19. package/dist/commands/pack-install.js +86 -15
  20. package/dist/commands/packs.d.ts +2 -1
  21. package/dist/commands/packs.js +13 -8
  22. package/dist/commands/secrets.d.ts +13 -0
  23. package/dist/commands/secrets.js +149 -10
  24. package/dist/commands/skill.d.ts +153 -0
  25. package/dist/commands/skill.js +593 -0
  26. package/dist/commands/workers.d.ts +48 -0
  27. package/dist/commands/workers.js +229 -0
  28. package/dist/index.d.ts +5 -3
  29. package/dist/index.js +14 -240
  30. package/dist/lib/db/control-plane.d.ts +45 -0
  31. package/dist/lib/db/control-plane.js +81 -0
  32. package/dist/lib/db/local.d.ts +49 -0
  33. package/dist/lib/db/local.js +106 -0
  34. package/dist/lib/db/migrate.d.ts +41 -0
  35. package/dist/lib/db/migrate.js +104 -0
  36. package/dist/lib/db/paths.d.ts +56 -0
  37. package/dist/lib/db/paths.js +103 -0
  38. package/dist/lib/db/remote-engine.d.ts +58 -0
  39. package/dist/lib/db/remote-engine.js +90 -0
  40. package/dist/lib/db/remote-sql.d.ts +22 -0
  41. package/dist/lib/db/remote-sql.js +39 -0
  42. package/dist/lib/db/sql.d.ts +49 -0
  43. package/dist/lib/db/sql.js +132 -0
  44. package/dist/main.d.ts +7 -0
  45. package/dist/main.js +272 -0
  46. package/dist/utils/cognito-session.js +3 -3
  47. package/dist/utils/sandbox-runner-client.d.ts +13 -0
  48. package/dist/utils/sandbox-runner-client.js +83 -6
  49. package/dist/utils/version-check.d.ts +6 -0
  50. package/dist/utils/version-check.js +78 -2
  51. package/package.json +9 -1
  52. package/pnpm-workspace.yaml +2 -0
  53. package/src/commands/agents.test.ts +297 -0
  54. package/src/commands/agents.ts +561 -0
  55. package/src/commands/db-migrate.ts +55 -0
  56. package/src/commands/db-provision.ts +102 -0
  57. package/src/commands/db-sql.ts +124 -0
  58. package/src/commands/db-status.ts +100 -0
  59. package/src/commands/db.ts +26 -0
  60. package/src/commands/integrations.test.ts +284 -0
  61. package/src/commands/integrations.ts +438 -0
  62. package/src/commands/members.ts +2 -2
  63. package/src/commands/outposts.test.ts +177 -0
  64. package/src/commands/outposts.ts +338 -0
  65. package/src/commands/pack-install.ts +115 -18
  66. package/src/commands/pack-update-cache.test.ts +149 -0
  67. package/src/commands/packs.ts +28 -7
  68. package/src/commands/secrets.parse-destination.test.ts +38 -0
  69. package/src/commands/secrets.test.ts +342 -0
  70. package/src/commands/secrets.ts +227 -13
  71. package/src/commands/skill.test.ts +770 -0
  72. package/src/commands/skill.ts +796 -0
  73. package/src/commands/workers.test.ts +158 -0
  74. package/src/commands/workers.ts +298 -0
  75. package/src/index.test.ts +32 -0
  76. package/src/index.ts +11 -274
  77. package/src/lib/db/control-plane.test.ts +59 -0
  78. package/src/lib/db/control-plane.ts +113 -0
  79. package/src/lib/db/local.test.ts +81 -0
  80. package/src/lib/db/local.ts +148 -0
  81. package/src/lib/db/migrate.test.ts +133 -0
  82. package/src/lib/db/migrate.ts +137 -0
  83. package/src/lib/db/paths.test.ts +112 -0
  84. package/src/lib/db/paths.ts +128 -0
  85. package/src/lib/db/remote-engine.test.ts +44 -0
  86. package/src/lib/db/remote-engine.ts +148 -0
  87. package/src/lib/db/remote-sql.test.ts +32 -0
  88. package/src/lib/db/remote-sql.ts +62 -0
  89. package/src/lib/db/sql.test.ts +106 -0
  90. package/src/lib/db/sql.ts +192 -0
  91. package/src/main.ts +314 -0
  92. package/src/utils/cognito-session.ts +1 -1
  93. package/src/utils/sandbox-runner-client.test.ts +128 -0
  94. package/src/utils/sandbox-runner-client.ts +100 -4
  95. package/src/utils/version-check.test.ts +30 -0
  96. package/src/utils/version-check.ts +72 -0
  97. package/test/commands/db-tenant-isolation.test.ts +94 -0
  98. package/test/commands/db.test.ts +85 -0
package/src/main.ts ADDED
@@ -0,0 +1,314 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * HQ CLI - Module management, package management, and cloud sync for HQ
5
+ */
6
+
7
+ // MUST be first: guard the Node version before any dependency that needs a
8
+ // Node 20+ API (e.g. util.styleText) or a newer native ABI is evaluated.
9
+ import "./node-preflight.js";
10
+ import { Command } from "commander";
11
+ import { initSentry, Sentry } from "./sentry.js";
12
+ import { registerAddCommand } from "./commands/add.js";
13
+ import { registerSyncCommand } from "./commands/sync.js";
14
+ import { registerListCommand } from "./commands/list.js";
15
+ import { registerUpdateCommand } from "./commands/update.js";
16
+ import { registerCloudCommands } from "./commands/cloud.js";
17
+ import { registerSyncModeCommand } from "./commands/sync-mode.js";
18
+ import { registerSyncNarrowCommand } from "./commands/sync-narrow.js";
19
+ import { registerCloudProvisionCommands } from "./commands/cloud-provision.js";
20
+ import { registerCloudDemoteCommands } from "./commands/cloud-demote.js";
21
+ import { registerLoginCommand } from "./commands/login.js";
22
+ import { registerLogoutCommand } from "./commands/logout.js";
23
+ import { registerWhoamiCommand } from "./commands/whoami.js";
24
+ import { registerOnboardCommand } from "./commands/onboard.js";
25
+ import { registerPackageInstallCommand } from "./commands/pkg-install.js";
26
+ import { registerPackageRemoveCommand } from "./commands/pkg-remove.js";
27
+ import { registerPackageUpdateCommand } from "./commands/pkg-update.js";
28
+ import { registerPackageListCommand } from "./commands/pkg-list.js";
29
+ import { registerPacksCommand } from "./commands/packs.js";
30
+ import { registerPublishCommand } from "./commands/publish.js";
31
+ import { registerCreatorsCommand } from "./commands/creators.js";
32
+ import { registerTeamSyncCommand } from "./commands/team-sync.js";
33
+ import { registerAuthCommands } from "./commands/auth.js";
34
+ import { registerApiKeysCommand } from "./commands/api-keys.js";
35
+ import { registerSecretsCommand } from "./commands/secrets.js";
36
+ import { registerRunCommand } from "./commands/run.js";
37
+ import { registerGroupsCommand } from "./commands/groups.js";
38
+ import { registerWorkersCommand } from "./commands/workers.js";
39
+ import { registerGroupGrantsCommand } from "./commands/group-grants.js";
40
+ import { registerFilesCommand } from "./commands/files.js";
41
+ import { registerFilesBrowseCommands } from "./commands/files-browse.js";
42
+ import { registerSkillCommand } from "./commands/skill.js";
43
+ import { registerMembersCommand } from "./commands/members.js";
44
+ import { registerPeopleCommand } from "./commands/people.js";
45
+ import { registerDmCommand } from "./commands/dm.js";
46
+ import { registerChannelsCommand } from "./commands/channels.js";
47
+ import { registerFeedbackCommand } from "./commands/feedback.js";
48
+ import { registerMeetingsCommand } from "./commands/meetings.js";
49
+ import { registerSourcesCommand } from "./commands/sources.js";
50
+ import { registerSignalsCommand } from "./commands/signals.js";
51
+ import { registerIntegrationsCommand } from "./commands/integrations.js";
52
+ import { registerReindexCommand } from "./commands/reindex.js";
53
+ import { registerRescueCommand } from "./commands/rescue.js";
54
+ import { registerMcpCommand } from "./commands/mcp-status.js";
55
+ import { registerCrmCommand } from "./commands/crm.js";
56
+ import { registerCompanyCommand } from "./commands/company.js";
57
+ import { registerAgentsCommand } from "./commands/agents.js";
58
+ import { registerOutpostsCommand } from "./commands/outposts.js";
59
+ import { registerDbCommand } from "./commands/db.js";
60
+ import { sanitizeArgv } from "./utils/feedback-diagnostics.js";
61
+ import { environmentalFsErrorMessage } from "./utils/environmental-error.js";
62
+ import { isEpipe } from "./utils/epipe.js";
63
+ import { isInterceptedProcessExit } from "./utils/intercepted-process-exit.js";
64
+ import {
65
+ maybeWarnNewVersion,
66
+ refreshVersionCache,
67
+ } from "./utils/version-check.js";
68
+ import {
69
+ enforceVersionGate,
70
+ shouldSkipGate,
71
+ } from "./utils/version-gate.js";
72
+ import { CLI_VERSION } from "./cli-version.js";
73
+
74
+ // Swallow EPIPE when a downstream reader (e.g. `source <(…)`, `| head`) closes
75
+ // the pipe early. This covers the ASYNC path — an 'error' event emitted on the
76
+ // stream. The SYNCHRONOUS path (a `write EPIPE` thrown straight out of
77
+ // console.log inside a command) is handled in the top-level catch below; both
78
+ // share `isEpipe` (HQ-6B).
79
+ const onPipeError = (err: NodeJS.ErrnoException): void => {
80
+ if (isEpipe(err)) {
81
+ process.exit(0);
82
+ }
83
+ throw err;
84
+ };
85
+ process.stdout.on("error", onPipeError);
86
+ process.stderr.on("error", onPipeError);
87
+
88
+ initSentry();
89
+ maybeWarnNewVersion();
90
+
91
+ const program = new Command();
92
+
93
+ program
94
+ .name("hq")
95
+ .description("HQ management CLI — modules, packages, and cloud sync")
96
+ .version(CLI_VERSION);
97
+
98
+ // Module management subcommand group
99
+ const modulesCmd = program
100
+ .command("modules")
101
+ .description("Module management commands");
102
+
103
+ registerAddCommand(modulesCmd);
104
+ registerSyncCommand(modulesCmd);
105
+ registerListCommand(modulesCmd);
106
+ registerUpdateCommand(modulesCmd);
107
+
108
+ // Package management subcommand group
109
+ const packagesCmd = program
110
+ .command("packages")
111
+ .description("Package management commands");
112
+
113
+ registerPackageInstallCommand(packagesCmd);
114
+ registerPackageRemoveCommand(packagesCmd);
115
+ registerPackageUpdateCommand(packagesCmd);
116
+ registerPackageListCommand(packagesCmd);
117
+
118
+ // Content-pack lifecycle (core/packages/hq-pack-*). Distinct from the registry
119
+ // `packages` system above. Available as both `hq packages packs …` (grouped)
120
+ // and `hq packs …` (top-level convenience).
121
+ registerPacksCommand(packagesCmd);
122
+ registerPacksCommand(program);
123
+
124
+ // Top-level shortcuts for package commands
125
+ // "hq install <slug>" = "hq packages install <slug>"
126
+ // "hq remove <slug>" = "hq packages remove <slug>"
127
+ registerPackageInstallCommand(program);
128
+ registerPackageRemoveCommand(program);
129
+
130
+ // Marketplace publish (top-level — packer + authenticated upload, US-004)
131
+ // "hq publish <skill-or-worker-path>" packages and submits a pack to the
132
+ // marketplace via POST /v1/listings.
133
+ registerPublishCommand(program);
134
+ // `hq creators apply` — request verified-creator access (required to publish).
135
+ registerCreatorsCommand(program);
136
+
137
+ // Cloud sync subcommand group
138
+ const syncCmd = program
139
+ .command("sync")
140
+ .description("Cloud sync commands — sync HQ to S3 for mobile access");
141
+
142
+ registerCloudCommands(syncCmd);
143
+ registerSyncModeCommand(syncCmd);
144
+ registerSyncNarrowCommand(syncCmd);
145
+
146
+ // Cloud provisioning subcommand group (entity + bucket + initial sync)
147
+ // Distinct from `hq sync` which assumes provisioning has already happened.
148
+ const cloudCmd = program
149
+ .command("cloud")
150
+ .description(
151
+ "Cloud commands — provision entities and manage cloud-backed companies",
152
+ );
153
+
154
+ registerCloudProvisionCommands(cloudCmd);
155
+ registerCloudDemoteCommands(cloudCmd);
156
+
157
+ // Team commands (top-level)
158
+ registerTeamSyncCommand(program);
159
+
160
+ // Auth commands (top-level — Cognito OAuth)
161
+ registerLoginCommand(program);
162
+ registerLogoutCommand(program);
163
+ registerWhoamiCommand(program);
164
+ registerAuthCommands(program);
165
+
166
+ // Secrets management (subcommand group — hq secrets set|get|list|delete|exec|generate-link|cache)
167
+ registerSecretsCommand(program);
168
+
169
+ // Vault databases (subcommand group — hq db status|sql|migrate|provision)
170
+ registerDbCommand(program);
171
+
172
+ // API key management (subcommand group — hq api-keys create|list|revoke)
173
+ registerApiKeysCommand(program);
174
+
175
+ // Schema-driven dev runner — hq run [options] -- <cmd>
176
+ registerRunCommand(program);
177
+
178
+ // Groups management (subcommand group — hq groups create|delete|add|remove|list|members)
179
+ registerGroupsCommand(program);
180
+
181
+ // Worker discovery + sharing (subcommand group — hq workers list|share)
182
+ registerWorkersCommand(program);
183
+
184
+ // Cross-company group grants (subcommand group —
185
+ // hq group-grants grant|revoke|outbound|inbound)
186
+ registerGroupGrantsCommand(program);
187
+
188
+ // Files ACL management (subcommand group — hq files share|unshare|acl)
189
+ // `registerFilesCommand` returns the `files` group so we can attach the
190
+ // browse-vs-sync subcommands (`hq files browse`/`cat`) onto the same group.
191
+ const filesCmd = registerFilesCommand(program);
192
+ registerFilesBrowseCommands(filesCmd);
193
+
194
+ // Skill collaboration loop (subcommand group — hq skill suggest|list-suggestions|review).
195
+ // A thin terminal front-end over the SAME wired hq-pro skill suggestion + merge
196
+ // routes the MCP (US-007) and console merge (US-009) surfaces use — no forked logic.
197
+ registerSkillCommand(program);
198
+
199
+ // Membership management (subcommand group — hq members invite|list|revoke)
200
+ registerMembersCommand(program);
201
+ // People directory (subcommand group — hq people list|search|resolve), reading
202
+ // the local companies/<co>/people store scoped to one company.
203
+ registerPeopleCommand(program);
204
+ registerDmCommand(program);
205
+ registerChannelsCommand(program);
206
+
207
+ // Onboarding (top-level — Cognito + vault-service provisioning)
208
+ registerOnboardCommand(program);
209
+
210
+ // Feedback (subcommand group — hq feedback bug|feature)
211
+ registerFeedbackCommand(program);
212
+
213
+ // Meetings (subcommand group — hq meetings list|get|search|transcript|notes)
214
+ registerMeetingsCommand(program);
215
+
216
+ // Sources read surface (subcommand group — hq sources list|get|channels|entities)
217
+ registerSourcesCommand(program);
218
+
219
+ // Signals read surface (subcommand group — hq signals list|get|types|entities)
220
+ registerSignalsCommand(program);
221
+
222
+ // Company-connected apps via the governed integration gateway
223
+ // (subcommand group — hq integrations list|tools|call|approve|reject)
224
+ registerIntegrationsCommand(program);
225
+
226
+ // Skill/personal-overlay mirroring + workers-registry regen. Invoked by the
227
+ // hq-core reindex hook shim (Stop / PostToolUse) and by sync()/rescue() after
228
+ // they change on-disk sources. Keeps a `master-sync` alias for one release.
229
+ // Implementation lives in @indigoai-us/hq-cloud.
230
+ registerReindexCommand(program);
231
+
232
+ // Drift-preserving HQ-core re-sync (top-level — `hq rescue`). CLI sibling of
233
+ // the HQ Sync app's "Update / Restore" pill; drives the same replace-rescue.sh
234
+ // shipped from @indigoai-us/hq-cloud.
235
+ registerRescueCommand(program);
236
+
237
+ // MCP pack observability (subcommand group — `hq mcp status`). Read-only
238
+ // provenance-based status across BOTH Claude + Codex runtimes (reads `_hqPack`
239
+ // off the configs, NOT linkStatus), with secret-redacted output + `--json`.
240
+ registerMcpCommand(program);
241
+
242
+ // Native CRM entity upsert (subcommand group — `hq crm entity upsert`). Wraps
243
+ // POST /crm/entities (the ontology write gate) so an authenticated company
244
+ // member can create/update canonical CRM entities in the company vault.
245
+ registerCrmCommand(program);
246
+
247
+ // Company settings (subcommand group — `hq company settings set`). Owner-only
248
+ // toggles for crmEnabled / ontologyEnabled via PUT /company-settings.
249
+ registerCompanyCommand(program);
250
+
251
+ // Cloud agent management (subcommand group — `hq agents …`). Rename, reconfigure,
252
+ // start/stop, and tear down a company's fleet agents via the hq-pro /v1/agents
253
+ // control plane — the same routes the web console's agents panel calls.
254
+ registerAgentsCommand(program);
255
+
256
+ // Personal Outpost management (subcommand group — `hq outposts …`). List, inspect,
257
+ // enable Codex on, refresh login for, and destroy your EC2 boxes via the hq-pro
258
+ // /outpost/* control plane.
259
+ registerOutpostsCommand(program);
260
+
261
+ export async function runCli(): Promise<void> {
262
+ try {
263
+ Sentry.addBreadcrumb({
264
+ category: "command",
265
+ message: sanitizeArgv(process.argv.slice(2)).join(" "),
266
+ level: "info",
267
+ });
268
+ // Hard version gate: ask hq-pro whether this CLI is below the floor and
269
+ // auto-update if so (exits the process on update). Skipped for inspection
270
+ // flags (`--version`, `--help`) so users debugging a broken install can
271
+ // still introspect what they have. Silent on any failure — never blocks
272
+ // the CLI on a flaky network or hq-pro hiccup. See `utils/version-gate.ts`.
273
+ if (!shouldSkipGate(process.argv)) {
274
+ await enforceVersionGate();
275
+ }
276
+ await program.parseAsync();
277
+ } catch (err) {
278
+ // A broken pipe (EPIPE) means the reader of `hq`'s output closed it early
279
+ // (`hq … | head`, `source <(hq …)`, a parent that exited). That is normal
280
+ // Unix behavior with no user-facing degradation — exit cleanly (0) and
281
+ // skip Sentry capture instead of shipping a fatal (HQ-6B). A synchronous
282
+ // `write EPIPE` thrown out of console.log lands here rather than on the
283
+ // stream 'error' listener above.
284
+ if (isEpipe(err)) {
285
+ process.exitCode = 0;
286
+ } else if (isInterceptedProcessExit(err)) {
287
+ // A security/audit FUZZ harness replaced `process.exit` with a throw so it
288
+ // can keep exercising the binary. Commander calling `process.exit` for
289
+ // normal CLI control flow (e.g. an unknown command → exit 1) then surfaces
290
+ // here as that synthetic marker. It is a test-harness artifact, NOT an
291
+ // hq-cli defect — a real user's `process.exit` just exits, so nothing is
292
+ // thrown or captured. Skip Sentry capture (no signal, no user-facing
293
+ // degradation) and preserve the intended non-zero exit (HQ-CLI-3).
294
+ process.exitCode = 1;
295
+ } else {
296
+ // A full disk / exhausted quota / read-only filesystem is the user's
297
+ // machine, not an HQ code defect. Surface a clear, actionable message and
298
+ // skip Sentry capture so one full disk doesn't flood the tracker with
299
+ // identical, unfixable crash reports (HQ-CLI-2). Genuine errors still go
300
+ // to Sentry and still exit 1.
301
+ const envMsg = environmentalFsErrorMessage(err);
302
+ if (envMsg) {
303
+ process.stderr.write(`hq: ${envMsg}\n`);
304
+ } else {
305
+ Sentry.captureException(err);
306
+ }
307
+ process.exitCode = 1;
308
+ }
309
+ } finally {
310
+ // Release health: finalize the per-run session before the flush.
311
+ Sentry.endSession();
312
+ await Promise.allSettled([refreshVersionCache(), Sentry.flush(2000)]);
313
+ }
314
+ }
@@ -57,7 +57,7 @@ export const DEFAULT_COGNITO: CognitoAuthConfig = {
57
57
  };
58
58
 
59
59
  export const DEFAULT_VAULT_API_URL =
60
- process.env.HQ_VAULT_API_URL ?? "https://hqapi.getindigo.ai";
60
+ process.env.HQ_VAULT_API_URL ?? "https://hqapi.hq.computer";
61
61
 
62
62
  /**
63
63
  * Resolve the HQ tree root for cloud-aware subcommands (`hq sync`, `hq onboard`,
@@ -39,6 +39,100 @@ describe("SandboxRunnerClient", () => {
39
39
  });
40
40
  });
41
41
 
42
+ it("retries startJob after fetch rejects twice then succeeds", async () => {
43
+ const fetchImpl = vi
44
+ .fn<typeof fetch>()
45
+ .mockRejectedValueOnce(new TypeError("fetch failed"))
46
+ .mockRejectedValueOnce(new Error("ECONNRESET"))
47
+ .mockResolvedValueOnce(jsonRes({ jobId: "job_1", status: "queued" }));
48
+ const sleep = vi.fn(async () => {});
49
+ const client = new SandboxRunnerClient({
50
+ baseUrl: "https://runner.example",
51
+ fetchImpl,
52
+ sleep,
53
+ });
54
+
55
+ await expect(
56
+ client.startJob("jwt-token", {
57
+ companyUid: "cmp_123",
58
+ secretNames: ["API_KEY"],
59
+ command: "node script.js",
60
+ }),
61
+ ).resolves.toEqual({ jobId: "job_1", status: "queued" });
62
+ expect(fetchImpl).toHaveBeenCalledTimes(3);
63
+ expect(sleep).toHaveBeenCalledTimes(2);
64
+ });
65
+
66
+ it("retries startJob after a retryable 503 response", async () => {
67
+ const fetchImpl = vi
68
+ .fn<typeof fetch>()
69
+ .mockResolvedValueOnce(jsonRes({ message: "warming up" }, 503))
70
+ .mockResolvedValueOnce(jsonRes({ jobId: "job_1", status: "queued" }));
71
+ const sleep = vi.fn(async () => {});
72
+ const client = new SandboxRunnerClient({
73
+ baseUrl: "https://runner.example",
74
+ fetchImpl,
75
+ sleep,
76
+ });
77
+
78
+ await expect(
79
+ client.startJob("jwt-token", {
80
+ companyUid: "cmp_123",
81
+ secretNames: ["API_KEY"],
82
+ command: "node script.js",
83
+ }),
84
+ ).resolves.toEqual({ jobId: "job_1", status: "queued" });
85
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
86
+ expect(sleep).toHaveBeenCalledTimes(1);
87
+ });
88
+
89
+ it.each([400, 401])("does not retry startJob on %i responses", async (status) => {
90
+ const fetchImpl = vi.fn<typeof fetch>(async () =>
91
+ jsonRes({ message: "bad request" }, status),
92
+ );
93
+ const sleep = vi.fn(async () => {});
94
+ const client = new SandboxRunnerClient({
95
+ baseUrl: "https://runner.example",
96
+ fetchImpl,
97
+ sleep,
98
+ });
99
+
100
+ await expect(
101
+ client.startJob("jwt-token", {
102
+ companyUid: "cmp_123",
103
+ secretNames: ["API_KEY"],
104
+ command: "node script.js",
105
+ }),
106
+ ).rejects.toThrow("Sandbox Runner rejected job: bad request");
107
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
108
+ expect(sleep).not.toHaveBeenCalled();
109
+ });
110
+
111
+ it("throws a clear exhaustion error after maxAttempts transient failures", async () => {
112
+ const fetchImpl = vi
113
+ .fn<typeof fetch>()
114
+ .mockRejectedValue(new TypeError("fetch failed"));
115
+ const sleep = vi.fn(async () => {});
116
+ const client = new SandboxRunnerClient({
117
+ baseUrl: "https://runner.example",
118
+ fetchImpl,
119
+ retry: { maxAttempts: 3 },
120
+ sleep,
121
+ });
122
+
123
+ await expect(
124
+ client.startJob("jwt-token", {
125
+ companyUid: "cmp_123",
126
+ secretNames: ["API_KEY"],
127
+ command: "node script.js",
128
+ }),
129
+ ).rejects.toThrow(
130
+ "Sandbox Runner did not respond after 3 attempts (cold start or transient network); last error: fetch failed",
131
+ );
132
+ expect(fetchImpl).toHaveBeenCalledTimes(3);
133
+ expect(sleep).toHaveBeenCalledTimes(2);
134
+ });
135
+
42
136
  it("polls queued and running states until succeeded", async () => {
43
137
  const fetchImpl = vi
44
138
  .fn<typeof fetch>()
@@ -77,6 +171,40 @@ describe("SandboxRunnerClient", () => {
77
171
  );
78
172
  });
79
173
 
174
+ it("tolerates one transient fetch rejection while polling", async () => {
175
+ const fetchImpl = vi
176
+ .fn<typeof fetch>()
177
+ .mockResolvedValueOnce(jsonRes({ jobId: "job_1", status: "queued" }))
178
+ .mockRejectedValueOnce(new TypeError("fetch failed"))
179
+ .mockResolvedValueOnce(jsonRes({ jobId: "job_1", status: "running" }))
180
+ .mockResolvedValueOnce(
181
+ jsonRes({
182
+ jobId: "job_1",
183
+ status: "succeeded",
184
+ output: "ok\n",
185
+ exitCode: 0,
186
+ success: true,
187
+ }),
188
+ );
189
+ const sleep = vi.fn(async () => {});
190
+ const client = new SandboxRunnerClient({
191
+ baseUrl: "https://runner.example",
192
+ fetchImpl,
193
+ sleep,
194
+ });
195
+
196
+ await expect(
197
+ client.pollJob("jwt-token", "job_1", { intervalMs: 0 }),
198
+ ).resolves.toMatchObject({
199
+ jobId: "job_1",
200
+ status: "succeeded",
201
+ output: "ok\n",
202
+ exitCode: 0,
203
+ success: true,
204
+ });
205
+ expect(fetchImpl).toHaveBeenCalledTimes(4);
206
+ });
207
+
80
208
  it("returns failed terminal jobs with error details", async () => {
81
209
  const fetchImpl = vi.fn<typeof fetch>(async () =>
82
210
  jsonRes({
@@ -22,6 +22,8 @@ export interface SandboxRunnerJob {
22
22
  export interface SandboxRunnerClientOptions {
23
23
  baseUrl?: string;
24
24
  fetchImpl?: typeof fetch;
25
+ retry?: SandboxRunnerRetryOptions;
26
+ sleep?: (ms: number) => Promise<void>;
25
27
  }
26
28
 
27
29
  export interface SandboxRunnerPollOptions {
@@ -29,7 +31,21 @@ export interface SandboxRunnerPollOptions {
29
31
  maxPolls?: number;
30
32
  }
31
33
 
32
- const DEFAULT_SANDBOX_RUNNER_URL = "https://hqapi.getindigo.ai/sandbox";
34
+ export interface SandboxRunnerRetryOptions {
35
+ maxAttempts?: number;
36
+ maxElapsedMs?: number;
37
+ baseDelayMs?: number;
38
+ maxDelayMs?: number;
39
+ }
40
+
41
+ const DEFAULT_SANDBOX_RUNNER_URL = "https://hqapi.hq.computer/sandbox";
42
+ const RETRYABLE_STATUS_CODES = new Set([408, 425, 429, 500, 502, 503, 504]);
43
+ const DEFAULT_RETRY_OPTIONS: Required<SandboxRunnerRetryOptions> = {
44
+ maxAttempts: 8,
45
+ maxElapsedMs: 90_000,
46
+ baseDelayMs: 500,
47
+ maxDelayMs: 5_000,
48
+ };
33
49
 
34
50
  function normalizeBaseUrl(baseUrl: string): string {
35
51
  return baseUrl.replace(/\/+$/, "");
@@ -82,20 +98,100 @@ function delay(ms: number): Promise<void> {
82
98
  return new Promise((resolve) => setTimeout(resolve, ms));
83
99
  }
84
100
 
101
+ function getErrorMessage(error: unknown): string {
102
+ if (error instanceof Error) {
103
+ return error.message;
104
+ }
105
+ if (typeof error === "string") {
106
+ return error;
107
+ }
108
+ return String(error);
109
+ }
110
+
111
+ function parseRetryAfterMs(value: string | null): number | undefined {
112
+ if (!value) return undefined;
113
+ const seconds = Number(value);
114
+ if (Number.isFinite(seconds) && seconds >= 0) {
115
+ return seconds * 1000;
116
+ }
117
+ const dateMs = Date.parse(value);
118
+ if (!Number.isNaN(dateMs)) {
119
+ return Math.max(0, dateMs - Date.now());
120
+ }
121
+ return undefined;
122
+ }
123
+
85
124
  export class SandboxRunnerClient {
86
125
  private readonly baseUrl: string;
87
126
  private readonly fetchImpl: typeof fetch;
127
+ private readonly retry: Required<SandboxRunnerRetryOptions>;
128
+ private readonly sleep: (ms: number) => Promise<void>;
88
129
 
89
130
  constructor(options: SandboxRunnerClientOptions = {}) {
90
131
  this.baseUrl = normalizeBaseUrl(options.baseUrl ?? getSandboxRunnerBaseUrl());
91
132
  this.fetchImpl = options.fetchImpl ?? fetch;
133
+ this.retry = { ...DEFAULT_RETRY_OPTIONS, ...options.retry };
134
+ this.sleep = options.sleep ?? delay;
135
+ }
136
+
137
+ private async fetchWithRetry(
138
+ url: string,
139
+ init: RequestInit,
140
+ ): Promise<Response> {
141
+ const startedAt = Date.now();
142
+ let lastError = "unknown error";
143
+ let attempts = 0;
144
+
145
+ for (let attempt = 1; attempt <= this.retry.maxAttempts; attempt += 1) {
146
+ attempts = attempt;
147
+ try {
148
+ const res = await this.fetchImpl(url, init);
149
+ if (!RETRYABLE_STATUS_CODES.has(res.status)) {
150
+ return res;
151
+ }
152
+ lastError = `HTTP ${res.status} ${res.statusText}`.trim();
153
+ if (!this.shouldRetry(attempt, startedAt)) {
154
+ break;
155
+ }
156
+ await this.sleep(this.nextDelayMs(attempt, res));
157
+ } catch (error) {
158
+ lastError = getErrorMessage(error);
159
+ if (!this.shouldRetry(attempt, startedAt)) {
160
+ break;
161
+ }
162
+ await this.sleep(this.nextDelayMs(attempt));
163
+ }
164
+ }
165
+
166
+ throw new Error(
167
+ `Sandbox Runner did not respond after ${attempts} attempts ` +
168
+ `(cold start or transient network); last error: ${lastError}`,
169
+ );
170
+ }
171
+
172
+ private shouldRetry(attempt: number, startedAt: number): boolean {
173
+ if (attempt >= this.retry.maxAttempts) {
174
+ return false;
175
+ }
176
+ return Date.now() - startedAt < this.retry.maxElapsedMs;
177
+ }
178
+
179
+ private nextDelayMs(attempt: number, res?: Response): number {
180
+ const retryAfterMs = parseRetryAfterMs(res?.headers.get("Retry-After") ?? null);
181
+ if (retryAfterMs !== undefined) {
182
+ return Math.min(retryAfterMs, this.retry.maxDelayMs);
183
+ }
184
+ const exponential = this.retry.baseDelayMs * 2 ** (attempt - 1);
185
+ const capped = Math.min(exponential, this.retry.maxDelayMs);
186
+ const jitter = Math.floor(Math.random() * Math.max(1, capped * 0.25));
187
+ return Math.min(capped + jitter, this.retry.maxDelayMs);
92
188
  }
93
189
 
94
190
  async startJob(
95
191
  token: string,
96
192
  request: SandboxRunnerStartRequest,
97
193
  ): Promise<SandboxRunnerStartResponse> {
98
- const res = await this.fetchImpl(`${this.baseUrl}/jobs`, {
194
+ const res = await this.fetchWithRetry(`${this.baseUrl}/jobs`, {
99
195
  method: "POST",
100
196
  headers: {
101
197
  Authorization: `Bearer ${token}`,
@@ -124,7 +220,7 @@ export class SandboxRunnerClient {
124
220
  }
125
221
 
126
222
  async getJob(token: string, jobId: string): Promise<SandboxRunnerJob> {
127
- const res = await this.fetchImpl(
223
+ const res = await this.fetchWithRetry(
128
224
  `${this.baseUrl}/jobs/${encodeURIComponent(jobId)}`,
129
225
  {
130
226
  headers: { Authorization: `Bearer ${token}` },
@@ -155,7 +251,7 @@ export class SandboxRunnerClient {
155
251
  if (job.status === "succeeded" || job.status === "failed") {
156
252
  return job;
157
253
  }
158
- await delay(intervalMs);
254
+ await this.sleep(intervalMs);
159
255
  }
160
256
  throw new Error(`Sandbox Runner job '${jobId}' did not finish before the poll limit.`);
161
257
  }
@@ -120,6 +120,36 @@ describe("refreshVersionCache", () => {
120
120
  expect(typeof written.fetchedAt).toBe("number");
121
121
  });
122
122
 
123
+ it("returns without fetching when the cached version is still within the TTL", async () => {
124
+ writeCache("5.99.0", 60 * 1000);
125
+ const fetchMock = vi.fn();
126
+ vi.stubGlobal("fetch", fetchMock);
127
+
128
+ const mod = await loadModule();
129
+ await mod.refreshVersionCache();
130
+
131
+ expect(fetchMock).not.toHaveBeenCalled();
132
+ const cachePath = path.join(tmpHome, ".hq", "version-check.json");
133
+ const written = JSON.parse(fs.readFileSync(cachePath, "utf-8"));
134
+ expect(written.latest).toBe("5.99.0");
135
+ });
136
+
137
+ it("skips passive refresh for noninteractive status probes", async () => {
138
+ const originalArgv = process.argv;
139
+ process.argv = ["node", "hq", "mcp", "status", "--json"];
140
+ const fetchMock = vi.fn();
141
+ vi.stubGlobal("fetch", fetchMock);
142
+
143
+ try {
144
+ const mod = await loadModule();
145
+ await mod.refreshVersionCache();
146
+ } finally {
147
+ process.argv = originalArgv;
148
+ }
149
+
150
+ expect(fetchMock).not.toHaveBeenCalled();
151
+ });
152
+
123
153
  it("does not throw or write a cache when fetch fails", async () => {
124
154
  const fetchMock = vi.fn().mockRejectedValue(new Error("network down"));
125
155
  vi.stubGlobal("fetch", fetchMock);