@testsprite/testsprite-cli 0.2.0 → 0.4.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 (68) hide show
  1. package/README.md +35 -26
  2. package/dist/commands/agent.d.ts +43 -0
  3. package/dist/commands/agent.js +200 -18
  4. package/dist/commands/auth.d.ts +5 -0
  5. package/dist/commands/auth.js +38 -27
  6. package/dist/commands/doctor.d.ts +49 -0
  7. package/dist/commands/doctor.js +233 -0
  8. package/dist/commands/init.d.ts +1 -1
  9. package/dist/commands/init.js +24 -14
  10. package/dist/commands/project.d.ts +75 -2
  11. package/dist/commands/project.js +326 -47
  12. package/dist/commands/test.d.ts +281 -2
  13. package/dist/commands/test.js +1658 -177
  14. package/dist/commands/usage.js +13 -12
  15. package/dist/index.js +71 -3
  16. package/dist/lib/agent-targets.d.ts +72 -6
  17. package/dist/lib/agent-targets.js +188 -6
  18. package/dist/lib/bundle.d.ts +34 -0
  19. package/dist/lib/bundle.js +63 -11
  20. package/dist/lib/client-factory.d.ts +31 -0
  21. package/dist/lib/client-factory.js +63 -0
  22. package/dist/lib/config.d.ts +2 -0
  23. package/dist/lib/config.js +11 -2
  24. package/dist/lib/credentials.js +10 -1
  25. package/dist/lib/dry-run/samples.d.ts +5 -0
  26. package/dist/lib/dry-run/samples.js +64 -0
  27. package/dist/lib/errors.d.ts +28 -1
  28. package/dist/lib/errors.js +40 -0
  29. package/dist/lib/failing-fe-resolver.d.ts +15 -0
  30. package/dist/lib/failing-fe-resolver.js +49 -1
  31. package/dist/lib/flaky.d.ts +80 -0
  32. package/dist/lib/flaky.js +76 -0
  33. package/dist/lib/http.d.ts +73 -1
  34. package/dist/lib/http.js +327 -135
  35. package/dist/lib/interrupt.d.ts +116 -0
  36. package/dist/lib/interrupt.js +182 -0
  37. package/dist/lib/junit-report.d.ts +58 -0
  38. package/dist/lib/junit-report.js +210 -0
  39. package/dist/lib/output.d.ts +16 -1
  40. package/dist/lib/output.js +24 -2
  41. package/dist/lib/pagination.d.ts +4 -3
  42. package/dist/lib/pagination.js +34 -6
  43. package/dist/lib/poll.d.ts +11 -0
  44. package/dist/lib/poll.js +70 -5
  45. package/dist/lib/prompt.js +52 -8
  46. package/dist/lib/proxy.d.ts +29 -0
  47. package/dist/lib/proxy.js +30 -0
  48. package/dist/lib/render-error.js +3 -1
  49. package/dist/lib/runs.types.d.ts +9 -0
  50. package/dist/lib/skill-nudge.d.ts +2 -2
  51. package/dist/lib/skill-nudge.js +13 -4
  52. package/dist/lib/target-url.js +8 -1
  53. package/dist/lib/ticker.d.ts +11 -1
  54. package/dist/lib/ticker.js +33 -1
  55. package/dist/lib/update-check.d.ts +67 -0
  56. package/dist/lib/update-check.js +246 -0
  57. package/dist/lib/v3-advisory.d.ts +13 -0
  58. package/dist/lib/v3-advisory.js +24 -0
  59. package/dist/lib/version-notice.d.ts +37 -0
  60. package/dist/lib/version-notice.js +87 -0
  61. package/dist/version-guard.d.ts +33 -0
  62. package/dist/version-guard.js +39 -0
  63. package/dist/version.d.ts +1 -1
  64. package/dist/version.js +1 -1
  65. package/package.json +3 -2
  66. package/skills/testsprite-onboard.skill.md +21 -0
  67. package/skills/testsprite-verify.codex.md +6 -0
  68. package/skills/testsprite-verify.skill.md +48 -4
package/dist/lib/http.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { ApiError, RequestTimeoutError, TransportError } from './errors.js';
2
+ import { ApiError, InterruptError, RequestTimeoutError, TransportError } from './errors.js';
3
3
  import { VERSION } from '../version.js';
4
4
  /**
5
5
  * Default per-request timeout (120s). Comfortably covers every metadata/read
@@ -47,17 +47,41 @@ export class HttpClient {
47
47
  random;
48
48
  onDebug;
49
49
  onTransition;
50
+ onServerVersion;
50
51
  requestTimeoutMs;
52
+ shutdownSignal;
51
53
  constructor(options) {
52
54
  this.baseUrl = trimTrailingSlash(options.baseUrl);
53
55
  this.apiKey = options.apiKey;
56
+ this.shutdownSignal = options.shutdownSignal;
54
57
  this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
55
58
  this.sleep = options.sleep ?? defaultSleep;
56
59
  this.random = options.random ?? Math.random;
57
60
  this.onDebug = options.onDebug;
58
61
  this.onTransition = options.onTransition;
62
+ this.onServerVersion = options.onServerVersion;
59
63
  this.requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_DEFAULT_MS;
60
64
  }
65
+ /**
66
+ * Read the backend's supported-floor header off a response and forward it to
67
+ * `onServerVersion` when present. Never throws — a bad header must not break
68
+ * the request. Called on every response (success or error) so the advisory
69
+ * covers all paths. (The backend advertises only the floor; "latest" is
70
+ * resolved client-side via the npm update-notice.)
71
+ */
72
+ captureServerVersion(response) {
73
+ if (!this.onServerVersion)
74
+ return;
75
+ try {
76
+ const minVersion = response.headers.get('x-testsprite-cli-min-version') ?? undefined;
77
+ if (minVersion !== undefined) {
78
+ this.onServerVersion({ minVersion });
79
+ }
80
+ }
81
+ catch {
82
+ // Header parsing is best-effort; never let it affect the request.
83
+ }
84
+ }
61
85
  async get(path, options = {}) {
62
86
  return this.requestWithMeta('GET', path, options).then(r => r.body);
63
87
  }
@@ -226,6 +250,23 @@ export class HttpClient {
226
250
  signal: options?.signal,
227
251
  });
228
252
  }
253
+ /**
254
+ * POST /api/cli/v1/runs/{runId}/cancel
255
+ * User-initiated cancel of a queued/running run (DEV-331 piece 3). No
256
+ * body, no `Idempotency-Key` — the endpoint is naturally idempotent (D10):
257
+ * re-cancel → 200 `alreadyCancelled: true`; already-terminal (passed/
258
+ * failed/blocked) → 409 CONFLICT; unknown/cross-tenant runId → 404.
259
+ *
260
+ * `retryOnConflict: false` — same rationale as `triggerRun`: a 409 here is
261
+ * a truthful terminal answer ("already finished"), not a transient
262
+ * snapshot conflict to paper over with a retry.
263
+ */
264
+ async cancelRun(runId, options) {
265
+ return this.post(`/runs/${encodeURIComponent(runId)}/cancel`, {
266
+ signal: options?.signal,
267
+ retryOnConflict: false,
268
+ });
269
+ }
229
270
  /**
230
271
  * Classify an error thrown while issuing OR reading a request. When it is an
231
272
  * abort/timeout and our per-request timeout signal fired (and the caller had
@@ -234,9 +275,21 @@ export class HttpClient {
234
275
  * unmodified. Returns normally when `err` is not an abort, so the caller can
235
276
  * continue its own error handling (transport retry / envelope parse).
236
277
  */
237
- rethrowIfAbort(err, timeoutSignal, callerSignal, requestId) {
278
+ rethrowIfAbort(err, timeoutSignal, callerSignal, requestId, effectiveSignal = timeoutSignal) {
279
+ // A user interrupt (DEV-331) outranks every other classification: once the
280
+ // shutdown signal fired, whatever error surfaced from the aborted fetch or
281
+ // body read is the interrupt. Throw its InterruptError reason so the wait
282
+ // paths can render the honest detach UX — never a RequestTimeoutError, and
283
+ // never fall through to the transport retry loop.
284
+ if (this.shutdownSignal?.aborted) {
285
+ throw this.shutdownSignal.reason;
286
+ }
238
287
  if (isAbortError(err) || isTimeoutError(err)) {
239
- if (timeoutSignal.aborted && (callerSignal == null || !callerSignal.aborted)) {
288
+ const timeoutWon = timeoutSignal.aborted &&
289
+ (callerSignal == null ||
290
+ !callerSignal.aborted ||
291
+ effectiveSignal.reason === timeoutSignal.reason);
292
+ if (timeoutWon) {
240
293
  throw new RequestTimeoutError(this.requestTimeoutMs, requestId);
241
294
  }
242
295
  throw err;
@@ -249,6 +302,11 @@ export class HttpClient {
249
302
  const requestId = options.requestId ?? newRequestId();
250
303
  let attempt = 0;
251
304
  while (true) {
305
+ // Bail before issuing (or re-issuing after a retry sleep) a request the
306
+ // user has already interrupted; the composed signal below would abort it
307
+ // immediately anyway, this just skips the wasted dispatch.
308
+ if (this.shutdownSignal?.aborted)
309
+ throw this.shutdownSignal.reason;
252
310
  attempt += 1;
253
311
  this.debug({ kind: 'request', method, url, attempt, requestId });
254
312
  const startedAt = Date.now();
@@ -260,164 +318,207 @@ export class HttpClient {
260
318
  // signal. The polling path supplies its own deadline-aware signal per
261
319
  // iteration — this timeout (120s default) is safely larger than any single
262
320
  // long-poll window (<=25s via ?waitSeconds), so it never bites polling.
263
- const timeoutSignal = AbortSignal.timeout(this.requestTimeoutMs);
264
- const effectiveSignal = options.signal != null ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
321
+ const requestTimeout = createRequestTimeout(this.requestTimeoutMs);
322
+ const timeoutSignal = requestTimeout.signal;
323
+ const composedSignals = [timeoutSignal];
324
+ if (options.signal != null)
325
+ composedSignals.push(options.signal);
326
+ // Shutdown composition (DEV-331): an armed SIGINT/SIGTERM aborts the
327
+ // in-flight fetch immediately (reason: InterruptError) instead of
328
+ // letting a long-poll drain its window before the interrupt surfaces.
329
+ if (this.shutdownSignal != null)
330
+ composedSignals.push(this.shutdownSignal);
331
+ const effectiveSignal = composedSignals.length > 1 ? AbortSignal.any(composedSignals) : timeoutSignal;
265
332
  try {
266
- response = await this.fetchImpl(url, {
267
- method,
268
- headers: this.buildHeaders(requestId, options),
269
- body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
270
- signal: effectiveSignal,
271
- });
272
- }
273
- catch (err) {
274
- // Distinguish a client-side request timeout from a caller-supplied abort.
275
- //
276
- // Node 22 `AbortSignal.timeout()` throws a `DOMException` with
277
- // `name === 'TimeoutError'` (not 'AbortError') when the signal fires.
278
- // A caller-supplied abort sets `name === 'AbortError'`.
279
- // We treat both abort variants together: if the timeout signal fired and
280
- // the caller hadn't already aborted, surface a clear RequestTimeoutError.
281
- // A timeout/abort during the fetch itself: classify it (RequestTimeoutError
282
- // when our deadline fired; otherwise rethrow the caller's abort unmodified).
283
- this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId);
284
- // If a RequestTimeoutError already propagated from somewhere (e.g. from a
285
- // nested call or from a test-injected fetchImpl), pass it through unchanged
286
- // rather than re-wrapping it as a TransportError.
287
- if (err instanceof RequestTimeoutError)
288
- throw err;
289
- const message = err instanceof Error ? err.message : String(err);
290
- this.debug({
291
- kind: 'error',
292
- method,
293
- url,
294
- attempt,
295
- requestId,
296
- errorCode: 'TRANSPORT',
297
- durationMs: Date.now() - startedAt,
298
- });
299
- const decision = transportRetryDecision(attempt, this.random);
300
- if (!decision.retry)
301
- throw new TransportError(message, requestId);
302
- this.transition(`Network error on ${shortPath(path)} — retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
303
- this.debug({
304
- kind: 'retry',
305
- method,
306
- url,
307
- attempt,
308
- requestId,
309
- errorCode: 'TRANSPORT',
310
- delayMs: decision.delayMs,
311
- });
312
- await this.sleep(decision.delayMs);
313
- continue;
314
- }
315
- const durationMs = Date.now() - startedAt;
316
- if (response.ok) {
317
- this.debug({
318
- kind: 'response',
319
- method,
320
- url,
321
- attempt,
322
- status: response.status,
323
- requestId,
324
- durationMs,
325
- });
326
333
  try {
327
- return { body: (await response.json()), requestId, status: response.status };
334
+ response = await this.fetchImpl(url, {
335
+ method,
336
+ headers: this.buildHeaders(requestId, options),
337
+ body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
338
+ signal: effectiveSignal,
339
+ });
328
340
  }
329
341
  catch (err) {
330
- // A timeout/abort can fire mid-body-read (headers received, stream stalls).
331
- this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId);
342
+ // Distinguish a client-side request timeout from a caller-supplied abort.
343
+ //
344
+ // The request-timeout controller aborts with an Error/DOMException whose
345
+ // `name === 'TimeoutError'` (not 'AbortError') when the signal fires.
346
+ // A caller-supplied abort sets `name === 'AbortError'`.
347
+ // We treat both abort variants together: if the timeout signal fired and
348
+ // the caller hadn't already aborted, surface a clear RequestTimeoutError.
349
+ // A user interrupt is never retried and never re-wrapped as a
350
+ // TransportError (same passthrough discipline as RequestTimeoutError).
351
+ // The instanceof check matters even without `this.shutdownSignal`:
352
+ // the polling path composes the shutdown signal into its per-
353
+ // iteration caller signal, so the fetch can reject with the
354
+ // InterruptError reason directly (DEV-331).
355
+ if (err instanceof InterruptError)
356
+ throw err;
357
+ // A timeout/abort during the fetch itself: classify it (RequestTimeoutError
358
+ // when our deadline fired; otherwise rethrow the caller's abort unmodified).
359
+ this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
360
+ // If a RequestTimeoutError already propagated from somewhere (e.g. from a
361
+ // nested call or from a test-injected fetchImpl), pass it through unchanged
362
+ // rather than re-wrapping it as a TransportError.
363
+ if (err instanceof RequestTimeoutError)
364
+ throw err;
365
+ const message = err instanceof Error ? err.message : String(err);
366
+ this.debug({
367
+ kind: 'error',
368
+ method,
369
+ url,
370
+ attempt,
371
+ requestId,
372
+ errorCode: 'TRANSPORT',
373
+ durationMs: Date.now() - startedAt,
374
+ });
375
+ const decision = transportRetryDecision(attempt, this.random);
376
+ if (!decision.retry)
377
+ throw new TransportError(message, requestId);
378
+ this.transition(`Network error on ${shortPath(path)} — retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
379
+ this.debug({
380
+ kind: 'retry',
381
+ method,
382
+ url,
383
+ attempt,
384
+ requestId,
385
+ errorCode: 'TRANSPORT',
386
+ delayMs: decision.delayMs,
387
+ });
388
+ requestTimeout.clear();
389
+ await this.sleepBeforeRetry(decision.delayMs);
390
+ continue;
391
+ }
392
+ const durationMs = Date.now() - startedAt;
393
+ // Surface the backend version-compatibility headers on every response
394
+ // (success or error) before branching, so the caller's advisory covers
395
+ // all paths.
396
+ this.captureServerVersion(response);
397
+ if (response.ok) {
398
+ this.debug({
399
+ kind: 'response',
400
+ method,
401
+ url,
402
+ attempt,
403
+ status: response.status,
404
+ requestId,
405
+ durationMs,
406
+ });
407
+ try {
408
+ return { body: (await response.json()), requestId, status: response.status };
409
+ }
410
+ catch (err) {
411
+ // Interrupt passthrough (see the fetch catch above).
412
+ if (err instanceof InterruptError)
413
+ throw err;
414
+ // A timeout/abort can fire mid-body-read (headers received, stream stalls).
415
+ this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
416
+ // Otherwise the successful response body was not valid JSON — a
417
+ // misconfigured endpoint, a proxy / captive-portal / login page that
418
+ // returns HTML with a 200 status, or an empty body. Surface a typed
419
+ // error carrying the requestId instead of letting the raw SyntaxError
420
+ // escape to index.ts, where it would print a bare `{"error":"..."}`
421
+ // and break the --output json envelope contract.
422
+ throw malformedResponseError(response, requestId, err);
423
+ }
424
+ }
425
+ let rawBody;
426
+ try {
427
+ rawBody = await safeReadJson(response);
428
+ }
429
+ catch (err) {
430
+ // Interrupt passthrough (see the fetch catch above).
431
+ if (err instanceof InterruptError)
432
+ throw err;
433
+ // safeReadJson rethrows aborts/timeouts (it swallows only non-abort parse
434
+ // errors), so a timeout fired mid-body-read on a non-OK response lands here.
435
+ this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
332
436
  throw err;
333
437
  }
334
- }
335
- let rawBody;
336
- try {
337
- rawBody = await safeReadJson(response);
338
- }
339
- catch (err) {
340
- // safeReadJson rethrows aborts/timeouts (it swallows only non-abort parse
341
- // errors), so a timeout fired mid-body-read on a non-OK response lands here.
342
- this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId);
343
- throw err;
344
- }
345
- // Edge proxies / load balancers return 408/502/504 without our error
346
- // envelope on transient outages. Per the CLI error spec §7 these are
347
- // transport-level retries, not facade errors — fold them in here so
348
- // we get the bounded backoff budget instead of a single INTERNAL bail.
349
- if (rawBody === null && isTransportEdgeStatus(response.status)) {
438
+ // Edge proxies / load balancers return 408/502/504 without our error
439
+ // envelope on transient outages. These are transport-level retries,
440
+ // not facade errors — fold them in here so we get the bounded backoff
441
+ // budget instead of a single INTERNAL bail.
442
+ if (rawBody === null && isTransportEdgeStatus(response.status)) {
443
+ this.debug({
444
+ kind: 'error',
445
+ method,
446
+ url,
447
+ attempt,
448
+ status: response.status,
449
+ requestId,
450
+ errorCode: 'TRANSPORT',
451
+ durationMs,
452
+ });
453
+ const decision = transportRetryDecision(attempt, this.random);
454
+ if (!decision.retry) {
455
+ throw new TransportError(`HTTP ${response.status} from ${url}`, requestId);
456
+ }
457
+ this.transition(`HTTP ${response.status} from ${shortPath(path)} — transport error, retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
458
+ this.debug({
459
+ kind: 'retry',
460
+ method,
461
+ url,
462
+ attempt,
463
+ requestId,
464
+ errorCode: 'TRANSPORT',
465
+ delayMs: decision.delayMs,
466
+ });
467
+ requestTimeout.clear();
468
+ await this.sleepBeforeRetry(decision.delayMs);
469
+ continue;
470
+ }
471
+ const retryAfterSec = parseRetryAfter(response.headers.get('retry-after'));
472
+ // Clamp server-directed Retry-After to [1s, 300s] and surface on the
473
+ // thrown error so outer callers (e.g. runBatchRun outer retry loop)
474
+ // can honor it without re-reading the now-consumed HTTP response.
475
+ const retryAfterMsForError = retryAfterSec !== undefined
476
+ ? Math.min(Math.max(retryAfterSec, 1), 300) * 1000
477
+ : undefined;
478
+ const apiError = ApiError.fromEnvelope(rawBody, response.status, retryAfterMsForError,
479
+ // Lets synthesized nextAction text (e.g. INSUFFICIENT_CREDITS billing
480
+ // links) resolve the environment-correct portal domain.
481
+ this.baseUrl);
350
482
  this.debug({
351
483
  kind: 'error',
352
484
  method,
353
485
  url,
354
486
  attempt,
355
487
  status: response.status,
488
+ errorCode: apiError.code,
356
489
  requestId,
357
- errorCode: 'TRANSPORT',
358
490
  durationMs,
359
491
  });
360
- const decision = transportRetryDecision(attempt, this.random);
361
- if (!decision.retry) {
362
- throw new TransportError(`HTTP ${response.status} from ${url}`, requestId);
492
+ const retryOnConflict = options.retryOnConflict !== false;
493
+ const retryOnRateLimit = options.retryOnRateLimit !== false;
494
+ const decision = apiRetryDecision(apiError.code, attempt, retryAfterSec, this.random, retryOnConflict, retryOnRateLimit);
495
+ if (!decision.retry)
496
+ throw apiError;
497
+ const delaySec = Math.round(decision.delayMs / 1000);
498
+ if (apiError.code === 'RATE_LIMITED') {
499
+ this.transition(`Rate limited (HTTP 429) — waiting ${delaySec}s before retry (attempt ${attempt})`);
500
+ }
501
+ else if (apiError.code === 'INTERNAL') {
502
+ this.transition(`Server error (HTTP 5xx, requestId: ${requestId}) — retrying in ${delaySec}s (attempt ${attempt})`);
503
+ }
504
+ else if (apiError.code === 'UNAVAILABLE') {
505
+ this.transition(`Service unavailable (HTTP 503) — retrying in ${delaySec}s (attempt ${attempt})`);
363
506
  }
364
- this.transition(`HTTP ${response.status} from ${shortPath(path)} — transport error, retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
365
507
  this.debug({
366
508
  kind: 'retry',
367
509
  method,
368
510
  url,
369
511
  attempt,
370
512
  requestId,
371
- errorCode: 'TRANSPORT',
513
+ errorCode: apiError.code,
372
514
  delayMs: decision.delayMs,
373
515
  });
374
- await this.sleep(decision.delayMs);
375
- continue;
376
- }
377
- const retryAfterSec = parseRetryAfter(response.headers.get('retry-after'));
378
- // Clamp server-directed Retry-After to [1s, 300s] and surface on the
379
- // thrown error so outer callers (e.g. runBatchRun outer retry loop)
380
- // can honor it without re-reading the now-consumed HTTP response.
381
- const retryAfterMsForError = retryAfterSec !== undefined ? Math.min(Math.max(retryAfterSec, 1), 300) * 1000 : undefined;
382
- const apiError = ApiError.fromEnvelope(rawBody, response.status, retryAfterMsForError,
383
- // Lets synthesized nextAction text (e.g. INSUFFICIENT_CREDITS billing
384
- // links) resolve the environment-correct portal domain.
385
- this.baseUrl);
386
- this.debug({
387
- kind: 'error',
388
- method,
389
- url,
390
- attempt,
391
- status: response.status,
392
- errorCode: apiError.code,
393
- requestId,
394
- durationMs,
395
- });
396
- const retryOnConflict = options.retryOnConflict !== false;
397
- const retryOnRateLimit = options.retryOnRateLimit !== false;
398
- const decision = apiRetryDecision(apiError.code, attempt, retryAfterSec, this.random, retryOnConflict, retryOnRateLimit);
399
- if (!decision.retry)
400
- throw apiError;
401
- const delaySec = Math.round(decision.delayMs / 1000);
402
- if (apiError.code === 'RATE_LIMITED') {
403
- this.transition(`Rate limited (HTTP 429) — waiting ${delaySec}s before retry (attempt ${attempt})`);
516
+ requestTimeout.clear();
517
+ await this.sleepBeforeRetry(decision.delayMs);
404
518
  }
405
- else if (apiError.code === 'INTERNAL') {
406
- this.transition(`Server error (HTTP 5xx, requestId: ${requestId}) — retrying in ${delaySec}s (attempt ${attempt})`);
519
+ finally {
520
+ requestTimeout.clear();
407
521
  }
408
- else if (apiError.code === 'UNAVAILABLE') {
409
- this.transition(`Service unavailable (HTTP 503) — retrying in ${delaySec}s (attempt ${attempt})`);
410
- }
411
- this.debug({
412
- kind: 'retry',
413
- method,
414
- url,
415
- attempt,
416
- requestId,
417
- errorCode: apiError.code,
418
- delayMs: decision.delayMs,
419
- });
420
- await this.sleep(decision.delayMs);
421
522
  }
422
523
  }
423
524
  buildHeaders(requestId, options) {
@@ -442,6 +543,31 @@ export class HttpClient {
442
543
  }
443
544
  return headers;
444
545
  }
546
+ /**
547
+ * Retry-delay sleep that bails the moment the shutdown signal fires
548
+ * (DEV-331, codex finding 1): a RATE_LIMITED `Retry-After: 60` or a
549
+ * transport backoff must not delay the honest-detach exit by up to a
550
+ * minute — reject with the InterruptError reason immediately. Mirrors
551
+ * poll.ts::sleepUnlessInterrupted.
552
+ */
553
+ sleepBeforeRetry(ms) {
554
+ const signal = this.shutdownSignal;
555
+ if (signal == null)
556
+ return this.sleep(ms);
557
+ if (signal.aborted)
558
+ return Promise.reject(signal.reason);
559
+ return new Promise((resolve, reject) => {
560
+ const onAbort = () => reject(signal.reason);
561
+ signal.addEventListener('abort', onAbort, { once: true });
562
+ this.sleep(ms).then(() => {
563
+ signal.removeEventListener('abort', onAbort);
564
+ resolve();
565
+ }, err => {
566
+ signal.removeEventListener('abort', onAbort);
567
+ reject(err instanceof Error ? err : new Error(String(err)));
568
+ });
569
+ });
570
+ }
445
571
  debug(event) {
446
572
  if (this.onDebug)
447
573
  this.onDebug(event);
@@ -486,6 +612,32 @@ export function buildUrl(baseUrl, path, query) {
486
612
  function newRequestId() {
487
613
  return `cli_${randomUUID()}`;
488
614
  }
615
+ function createRequestTimeout(timeoutMs) {
616
+ const controller = new AbortController();
617
+ const timer = setTimeout(() => {
618
+ controller.abort(makeTimeoutReason());
619
+ }, timeoutMs);
620
+ unrefTimer(timer);
621
+ return {
622
+ signal: controller.signal,
623
+ clear: () => clearTimeout(timer),
624
+ };
625
+ }
626
+ function makeTimeoutReason() {
627
+ if (typeof DOMException !== 'undefined') {
628
+ return new DOMException('The operation timed out.', 'TimeoutError');
629
+ }
630
+ const err = new Error('The operation timed out.');
631
+ err.name = 'TimeoutError';
632
+ return err;
633
+ }
634
+ function unrefTimer(timer) {
635
+ if (typeof timer !== 'object' || timer === null || !('unref' in timer))
636
+ return;
637
+ const unref = timer.unref;
638
+ if (typeof unref === 'function')
639
+ unref.call(timer);
640
+ }
489
641
  async function safeReadJson(response) {
490
642
  try {
491
643
  return await response.json();
@@ -498,6 +650,43 @@ async function safeReadJson(response) {
498
650
  return null;
499
651
  }
500
652
  }
653
+ /**
654
+ * Build a typed error for a successful response whose body could not be parsed
655
+ * as JSON.
656
+ *
657
+ * The CLI expects every API response to be a JSON envelope. When a `200 OK`
658
+ * carries a non-JSON body — a misconfigured endpoint, a proxy / captive-portal
659
+ * / SSO login page returning HTML with a success status, or an empty body —
660
+ * `response.json()` throws a raw `SyntaxError`. Left unhandled it escapes to
661
+ * the top-level handler in `index.ts`, which prints a bare
662
+ * `{"error":"<parse message>"}` under `--output json` (breaking the
663
+ * typed-envelope contract every other error honors) and gives the operator no
664
+ * actionable context.
665
+ *
666
+ * This wraps it in a typed `INTERNAL` `ApiError` (exit 1, unchanged) that
667
+ * carries the `requestId`, names the likely cause, and points the operator at
668
+ * their endpoint configuration. `details` includes the HTTP status, the
669
+ * response `content-type` (when present), and the underlying parse message.
670
+ */
671
+ export function malformedResponseError(response, requestId, cause) {
672
+ const contentType = response.headers.get('content-type') ?? undefined;
673
+ const parseError = cause instanceof Error ? cause.message : String(cause);
674
+ const contentTypeNote = contentType ? ` (content-type: ${contentType})` : '';
675
+ return new ApiError({
676
+ code: 'INTERNAL',
677
+ message: `The server returned a non-JSON response${contentTypeNote} for an HTTP ${response.status}. ` +
678
+ `This usually means the endpoint is not the TestSprite API — a proxy, captive portal, or ` +
679
+ `login page can return HTML with a success status.`,
680
+ nextAction: 'Check that --endpoint-url / TESTSPRITE_API_URL points at the TestSprite API ' +
681
+ '(default https://api.testsprite.com), then retry.',
682
+ requestId,
683
+ details: {
684
+ httpStatus: response.status,
685
+ ...(contentType ? { contentType } : {}),
686
+ parseError,
687
+ },
688
+ }, response.status);
689
+ }
501
690
  export function parseRetryAfter(headerValue) {
502
691
  if (!headerValue)
503
692
  return undefined;
@@ -548,6 +737,9 @@ function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict
548
737
  case 'UNSUPPORTED':
549
738
  case 'INSUFFICIENT_CREDITS':
550
739
  case 'FEATURE_GATED':
740
+ case 'CLIENT_TOO_OLD':
741
+ // CLIENT_TOO_OLD: retrying re-sends the same too-old client — it can only
742
+ // self-heal by upgrading, so fail fast with the upgrade guidance.
551
743
  return { retry: false, delayMs: 0 };
552
744
  case 'CONFLICT':
553
745
  // Read paths (e.g. GET /failure) retry once: 409 = mid-mutation snapshot.