@indigoai-us/hq-cli 5.59.0 → 5.61.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.
package/src/main.ts ADDED
@@ -0,0 +1,283 @@
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 { registerGroupGrantsCommand } from "./commands/group-grants.js";
39
+ import { registerFilesCommand } from "./commands/files.js";
40
+ import { registerFilesBrowseCommands } from "./commands/files-browse.js";
41
+ import { registerMembersCommand } from "./commands/members.js";
42
+ import { registerPeopleCommand } from "./commands/people.js";
43
+ import { registerDmCommand } from "./commands/dm.js";
44
+ import { registerChannelsCommand } from "./commands/channels.js";
45
+ import { registerFeedbackCommand } from "./commands/feedback.js";
46
+ import { registerMeetingsCommand } from "./commands/meetings.js";
47
+ import { registerSourcesCommand } from "./commands/sources.js";
48
+ import { registerSignalsCommand } from "./commands/signals.js";
49
+ import { registerReindexCommand } from "./commands/reindex.js";
50
+ import { registerRescueCommand } from "./commands/rescue.js";
51
+ import { registerMcpCommand } from "./commands/mcp-status.js";
52
+ import { registerCrmCommand } from "./commands/crm.js";
53
+ import { registerCompanyCommand } from "./commands/company.js";
54
+ import { sanitizeArgv } from "./utils/feedback-diagnostics.js";
55
+ import { environmentalFsErrorMessage } from "./utils/environmental-error.js";
56
+ import { isEpipe } from "./utils/epipe.js";
57
+ import { isInterceptedProcessExit } from "./utils/intercepted-process-exit.js";
58
+ import {
59
+ maybeWarnNewVersion,
60
+ refreshVersionCache,
61
+ } from "./utils/version-check.js";
62
+ import {
63
+ enforceVersionGate,
64
+ shouldSkipGate,
65
+ } from "./utils/version-gate.js";
66
+ import { CLI_VERSION } from "./cli-version.js";
67
+
68
+ // Swallow EPIPE when a downstream reader (e.g. `source <(…)`, `| head`) closes
69
+ // the pipe early. This covers the ASYNC path — an 'error' event emitted on the
70
+ // stream. The SYNCHRONOUS path (a `write EPIPE` thrown straight out of
71
+ // console.log inside a command) is handled in the top-level catch below; both
72
+ // share `isEpipe` (HQ-6B).
73
+ const onPipeError = (err: NodeJS.ErrnoException): void => {
74
+ if (isEpipe(err)) {
75
+ process.exit(0);
76
+ }
77
+ throw err;
78
+ };
79
+ process.stdout.on("error", onPipeError);
80
+ process.stderr.on("error", onPipeError);
81
+
82
+ initSentry();
83
+ maybeWarnNewVersion();
84
+
85
+ const program = new Command();
86
+
87
+ program
88
+ .name("hq")
89
+ .description("HQ management CLI — modules, packages, and cloud sync")
90
+ .version(CLI_VERSION);
91
+
92
+ // Module management subcommand group
93
+ const modulesCmd = program
94
+ .command("modules")
95
+ .description("Module management commands");
96
+
97
+ registerAddCommand(modulesCmd);
98
+ registerSyncCommand(modulesCmd);
99
+ registerListCommand(modulesCmd);
100
+ registerUpdateCommand(modulesCmd);
101
+
102
+ // Package management subcommand group
103
+ const packagesCmd = program
104
+ .command("packages")
105
+ .description("Package management commands");
106
+
107
+ registerPackageInstallCommand(packagesCmd);
108
+ registerPackageRemoveCommand(packagesCmd);
109
+ registerPackageUpdateCommand(packagesCmd);
110
+ registerPackageListCommand(packagesCmd);
111
+
112
+ // Content-pack lifecycle (core/packages/hq-pack-*). Distinct from the registry
113
+ // `packages` system above. Available as both `hq packages packs …` (grouped)
114
+ // and `hq packs …` (top-level convenience).
115
+ registerPacksCommand(packagesCmd);
116
+ registerPacksCommand(program);
117
+
118
+ // Top-level shortcuts for package commands
119
+ // "hq install <slug>" = "hq packages install <slug>"
120
+ // "hq remove <slug>" = "hq packages remove <slug>"
121
+ registerPackageInstallCommand(program);
122
+ registerPackageRemoveCommand(program);
123
+
124
+ // Marketplace publish (top-level — packer + authenticated upload, US-004)
125
+ // "hq publish <skill-or-worker-path>" packages and submits a pack to the
126
+ // marketplace via POST /v1/listings.
127
+ registerPublishCommand(program);
128
+ // `hq creators apply` — request verified-creator access (required to publish).
129
+ registerCreatorsCommand(program);
130
+
131
+ // Cloud sync subcommand group
132
+ const syncCmd = program
133
+ .command("sync")
134
+ .description("Cloud sync commands — sync HQ to S3 for mobile access");
135
+
136
+ registerCloudCommands(syncCmd);
137
+ registerSyncModeCommand(syncCmd);
138
+ registerSyncNarrowCommand(syncCmd);
139
+
140
+ // Cloud provisioning subcommand group (entity + bucket + initial sync)
141
+ // Distinct from `hq sync` which assumes provisioning has already happened.
142
+ const cloudCmd = program
143
+ .command("cloud")
144
+ .description(
145
+ "Cloud commands — provision entities and manage cloud-backed companies",
146
+ );
147
+
148
+ registerCloudProvisionCommands(cloudCmd);
149
+ registerCloudDemoteCommands(cloudCmd);
150
+
151
+ // Team commands (top-level)
152
+ registerTeamSyncCommand(program);
153
+
154
+ // Auth commands (top-level — Cognito OAuth)
155
+ registerLoginCommand(program);
156
+ registerLogoutCommand(program);
157
+ registerWhoamiCommand(program);
158
+ registerAuthCommands(program);
159
+
160
+ // Secrets management (subcommand group — hq secrets set|get|list|delete|exec|generate-link|cache)
161
+ registerSecretsCommand(program);
162
+
163
+ // API key management (subcommand group — hq api-keys create|list|revoke)
164
+ registerApiKeysCommand(program);
165
+
166
+ // Schema-driven dev runner — hq run [options] -- <cmd>
167
+ registerRunCommand(program);
168
+
169
+ // Groups management (subcommand group — hq groups create|delete|add|remove|list|members)
170
+ registerGroupsCommand(program);
171
+
172
+ // Cross-company group grants (subcommand group —
173
+ // hq group-grants grant|revoke|outbound|inbound)
174
+ registerGroupGrantsCommand(program);
175
+
176
+ // Files ACL management (subcommand group — hq files share|unshare|acl)
177
+ // `registerFilesCommand` returns the `files` group so we can attach the
178
+ // browse-vs-sync subcommands (`hq files browse`/`cat`) onto the same group.
179
+ const filesCmd = registerFilesCommand(program);
180
+ registerFilesBrowseCommands(filesCmd);
181
+
182
+ // Membership management (subcommand group — hq members invite|list|revoke)
183
+ registerMembersCommand(program);
184
+ // People directory (subcommand group — hq people list|search|resolve), reading
185
+ // the local companies/<co>/people store scoped to one company.
186
+ registerPeopleCommand(program);
187
+ registerDmCommand(program);
188
+ registerChannelsCommand(program);
189
+
190
+ // Onboarding (top-level — Cognito + vault-service provisioning)
191
+ registerOnboardCommand(program);
192
+
193
+ // Feedback (subcommand group — hq feedback bug|feature)
194
+ registerFeedbackCommand(program);
195
+
196
+ // Meetings (subcommand group — hq meetings list|get|search|transcript|notes)
197
+ registerMeetingsCommand(program);
198
+
199
+ // Sources read surface (subcommand group — hq sources list|get|channels|entities)
200
+ registerSourcesCommand(program);
201
+
202
+ // Signals read surface (subcommand group — hq signals list|get|types|entities)
203
+ registerSignalsCommand(program);
204
+
205
+ // Skill/personal-overlay mirroring + workers-registry regen. Invoked by the
206
+ // hq-core reindex hook shim (Stop / PostToolUse) and by sync()/rescue() after
207
+ // they change on-disk sources. Keeps a `master-sync` alias for one release.
208
+ // Implementation lives in @indigoai-us/hq-cloud.
209
+ registerReindexCommand(program);
210
+
211
+ // Drift-preserving HQ-core re-sync (top-level — `hq rescue`). CLI sibling of
212
+ // the HQ Sync app's "Update / Restore" pill; drives the same replace-rescue.sh
213
+ // shipped from @indigoai-us/hq-cloud.
214
+ registerRescueCommand(program);
215
+
216
+ // MCP pack observability (subcommand group — `hq mcp status`). Read-only
217
+ // provenance-based status across BOTH Claude + Codex runtimes (reads `_hqPack`
218
+ // off the configs, NOT linkStatus), with secret-redacted output + `--json`.
219
+ registerMcpCommand(program);
220
+
221
+ // Native CRM entity upsert (subcommand group — `hq crm entity upsert`). Wraps
222
+ // POST /crm/entities (the ontology write gate) so an authenticated company
223
+ // member can create/update canonical CRM entities in the company vault.
224
+ registerCrmCommand(program);
225
+
226
+ // Company settings (subcommand group — `hq company settings set`). Owner-only
227
+ // toggles for crmEnabled / ontologyEnabled via PUT /company-settings.
228
+ registerCompanyCommand(program);
229
+
230
+ export async function runCli(): Promise<void> {
231
+ try {
232
+ Sentry.addBreadcrumb({
233
+ category: "command",
234
+ message: sanitizeArgv(process.argv.slice(2)).join(" "),
235
+ level: "info",
236
+ });
237
+ // Hard version gate: ask hq-pro whether this CLI is below the floor and
238
+ // auto-update if so (exits the process on update). Skipped for inspection
239
+ // flags (`--version`, `--help`) so users debugging a broken install can
240
+ // still introspect what they have. Silent on any failure — never blocks
241
+ // the CLI on a flaky network or hq-pro hiccup. See `utils/version-gate.ts`.
242
+ if (!shouldSkipGate(process.argv)) {
243
+ await enforceVersionGate();
244
+ }
245
+ await program.parseAsync();
246
+ } catch (err) {
247
+ // A broken pipe (EPIPE) means the reader of `hq`'s output closed it early
248
+ // (`hq … | head`, `source <(hq …)`, a parent that exited). That is normal
249
+ // Unix behavior with no user-facing degradation — exit cleanly (0) and
250
+ // skip Sentry capture instead of shipping a fatal (HQ-6B). A synchronous
251
+ // `write EPIPE` thrown out of console.log lands here rather than on the
252
+ // stream 'error' listener above.
253
+ if (isEpipe(err)) {
254
+ process.exitCode = 0;
255
+ } else if (isInterceptedProcessExit(err)) {
256
+ // A security/audit FUZZ harness replaced `process.exit` with a throw so it
257
+ // can keep exercising the binary. Commander calling `process.exit` for
258
+ // normal CLI control flow (e.g. an unknown command → exit 1) then surfaces
259
+ // here as that synthetic marker. It is a test-harness artifact, NOT an
260
+ // hq-cli defect — a real user's `process.exit` just exits, so nothing is
261
+ // thrown or captured. Skip Sentry capture (no signal, no user-facing
262
+ // degradation) and preserve the intended non-zero exit (HQ-CLI-3).
263
+ process.exitCode = 1;
264
+ } else {
265
+ // A full disk / exhausted quota / read-only filesystem is the user's
266
+ // machine, not an HQ code defect. Surface a clear, actionable message and
267
+ // skip Sentry capture so one full disk doesn't flood the tracker with
268
+ // identical, unfixable crash reports (HQ-CLI-2). Genuine errors still go
269
+ // to Sentry and still exit 1.
270
+ const envMsg = environmentalFsErrorMessage(err);
271
+ if (envMsg) {
272
+ process.stderr.write(`hq: ${envMsg}\n`);
273
+ } else {
274
+ Sentry.captureException(err);
275
+ }
276
+ process.exitCode = 1;
277
+ }
278
+ } finally {
279
+ // Release health: finalize the per-run session before the flush.
280
+ Sentry.endSession();
281
+ await Promise.allSettled([refreshVersionCache(), Sentry.flush(2000)]);
282
+ }
283
+ }
@@ -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
 
34
+ export interface SandboxRunnerRetryOptions {
35
+ maxAttempts?: number;
36
+ maxElapsedMs?: number;
37
+ baseDelayMs?: number;
38
+ maxDelayMs?: number;
39
+ }
40
+
32
41
  const DEFAULT_SANDBOX_RUNNER_URL = "https://hqapi.getindigo.ai/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);