@testsprite/testsprite-cli 0.3.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.
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
@@ -235,6 +276,14 @@ export class HttpClient {
235
276
  * continue its own error handling (transport retry / envelope parse).
236
277
  */
237
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
288
  const timeoutWon = timeoutSignal.aborted &&
240
289
  (callerSignal == null ||
@@ -253,6 +302,11 @@ export class HttpClient {
253
302
  const requestId = options.requestId ?? newRequestId();
254
303
  let attempt = 0;
255
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;
256
310
  attempt += 1;
257
311
  this.debug({ kind: 'request', method, url, attempt, requestId });
258
312
  const startedAt = Date.now();
@@ -266,7 +320,15 @@ export class HttpClient {
266
320
  // long-poll window (<=25s via ?waitSeconds), so it never bites polling.
267
321
  const requestTimeout = createRequestTimeout(this.requestTimeoutMs);
268
322
  const timeoutSignal = requestTimeout.signal;
269
- const effectiveSignal = options.signal != null ? AbortSignal.any([timeoutSignal, options.signal]) : timeoutSignal;
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;
270
332
  try {
271
333
  try {
272
334
  response = await this.fetchImpl(url, {
@@ -284,6 +346,14 @@ export class HttpClient {
284
346
  // A caller-supplied abort sets `name === 'AbortError'`.
285
347
  // We treat both abort variants together: if the timeout signal fired and
286
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;
287
357
  // A timeout/abort during the fetch itself: classify it (RequestTimeoutError
288
358
  // when our deadline fired; otherwise rethrow the caller's abort unmodified).
289
359
  this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
@@ -316,10 +386,14 @@ export class HttpClient {
316
386
  delayMs: decision.delayMs,
317
387
  });
318
388
  requestTimeout.clear();
319
- await this.sleep(decision.delayMs);
389
+ await this.sleepBeforeRetry(decision.delayMs);
320
390
  continue;
321
391
  }
322
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);
323
397
  if (response.ok) {
324
398
  this.debug({
325
399
  kind: 'response',
@@ -334,6 +408,9 @@ export class HttpClient {
334
408
  return { body: (await response.json()), requestId, status: response.status };
335
409
  }
336
410
  catch (err) {
411
+ // Interrupt passthrough (see the fetch catch above).
412
+ if (err instanceof InterruptError)
413
+ throw err;
337
414
  // A timeout/abort can fire mid-body-read (headers received, stream stalls).
338
415
  this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
339
416
  // Otherwise the successful response body was not valid JSON — a
@@ -350,6 +427,9 @@ export class HttpClient {
350
427
  rawBody = await safeReadJson(response);
351
428
  }
352
429
  catch (err) {
430
+ // Interrupt passthrough (see the fetch catch above).
431
+ if (err instanceof InterruptError)
432
+ throw err;
353
433
  // safeReadJson rethrows aborts/timeouts (it swallows only non-abort parse
354
434
  // errors), so a timeout fired mid-body-read on a non-OK response lands here.
355
435
  this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
@@ -385,7 +465,7 @@ export class HttpClient {
385
465
  delayMs: decision.delayMs,
386
466
  });
387
467
  requestTimeout.clear();
388
- await this.sleep(decision.delayMs);
468
+ await this.sleepBeforeRetry(decision.delayMs);
389
469
  continue;
390
470
  }
391
471
  const retryAfterSec = parseRetryAfter(response.headers.get('retry-after'));
@@ -434,7 +514,7 @@ export class HttpClient {
434
514
  delayMs: decision.delayMs,
435
515
  });
436
516
  requestTimeout.clear();
437
- await this.sleep(decision.delayMs);
517
+ await this.sleepBeforeRetry(decision.delayMs);
438
518
  }
439
519
  finally {
440
520
  requestTimeout.clear();
@@ -463,6 +543,31 @@ export class HttpClient {
463
543
  }
464
544
  return headers;
465
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
+ }
466
571
  debug(event) {
467
572
  if (this.onDebug)
468
573
  this.onDebug(event);
@@ -632,6 +737,9 @@ function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict
632
737
  case 'UNSUPPORTED':
633
738
  case 'INSUFFICIENT_CREDITS':
634
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.
635
743
  return { retry: false, delayMs: 0 };
636
744
  case 'CONFLICT':
637
745
  // Read paths (e.g. GET /failure) retry once: 409 = mid-mutation snapshot.
@@ -18,18 +18,65 @@
18
18
  * `process` and the streams are injectable so the wiring is unit-testable
19
19
  * without spawning a subprocess or sending a real signal.
20
20
  */
21
- /**
22
- * Termination signals handled, mapped to their conventional `128 + signum`
23
- * exit code. sourceRef: POSIX signal numbers (SIGHUP=1, SIGINT=2, SIGTERM=15).
24
- */
25
- export declare const TERMINATION_EXIT_CODES: {
26
- readonly SIGINT: 130;
27
- readonly SIGTERM: 143;
28
- readonly SIGHUP: 129;
29
- };
30
- export type TerminationSignal = keyof typeof TERMINATION_EXIT_CODES;
21
+ import { type TerminationSignal } from './errors.js';
22
+ export { TERMINATION_EXIT_CODES, type TerminationSignal } from './errors.js';
31
23
  /** Back-compat alias: SIGINT's conventional exit code. */
32
24
  export declare const SIGINT_EXIT_CODE: 130;
25
+ /**
26
+ * Structural view of {@link ShutdownController} threaded through the DI
27
+ * surfaces (`TestDeps`, `PollOptions`) — commands and the polling loop need
28
+ * only these members, and tests can supply a lightweight fake.
29
+ */
30
+ export interface ShutdownHandle {
31
+ /** Aborts (reason: `InterruptError`) when a termination signal arrives while armed. */
32
+ readonly signal: AbortSignal;
33
+ /** Enter a graceful-detach scope. Returns the disposer that leaves it. */
34
+ arm(): () => void;
35
+ }
36
+ /**
37
+ * Process-lifetime coordinator between the signal handler and the `--wait`
38
+ * polling paths (DEV-331 piece 1).
39
+ *
40
+ * Two modes, chosen by whether a graceful-detach scope is armed when the
41
+ * signal arrives:
42
+ *
43
+ * - **Armed** (inside `pollRunUntilTerminal`): the handler only aborts
44
+ * `signal` with an `InterruptError` — no I/O, no exit. The in-flight fetch
45
+ * and every backoff sleep bail immediately; the `--wait` catch blocks own
46
+ * the cleanup (finalize the ticker, print the honest partial envelope +
47
+ * re-attach hint, rethrow to `index.ts` → exit 130/143/129).
48
+ * - **Disarmed** (no wait in progress — prompts, one-shot commands, local
49
+ * FS work): the handler prints the generic explanation and exits
50
+ * immediately, preserving the pre-DEV-331 behavior. An abort nobody
51
+ * observes must never leave the process hanging at e.g. a readline prompt.
52
+ *
53
+ * A second signal while the armed cleanup is in flight is the documented
54
+ * escape hatch: immediate hard exit.
55
+ */
56
+ export declare class ShutdownController {
57
+ private readonly controller;
58
+ private armedCount;
59
+ private receivedSignal;
60
+ constructor();
61
+ get signal(): AbortSignal;
62
+ /** The first termination signal received, or null if none yet. */
63
+ get received(): TerminationSignal | null;
64
+ get isArmed(): boolean;
65
+ /**
66
+ * Enter a graceful-detach scope (re-entrant: fan-out members overlap).
67
+ * Returns an idempotent disposer.
68
+ */
69
+ arm(): () => void;
70
+ /** Record the signal and abort with an `InterruptError` carrying it. */
71
+ interrupt(signal: TerminationSignal): void;
72
+ }
73
+ /**
74
+ * The process-wide instance: `index.ts` hands it to `installSignalHandlers`,
75
+ * and it is the default `shutdown` for `TestDeps` / `PollOptions` /
76
+ * `ClientFactoryDeps`, so production wiring is automatic. Tests inject their
77
+ * own `ShutdownController` (or a `ShutdownHandle` fake) instead.
78
+ */
79
+ export declare const globalShutdown: ShutdownController;
33
80
  export declare function formatInterruptMessage(signal?: TerminationSignal): string;
34
81
  export interface InterruptDeps {
35
82
  /** Signal registrar. Defaults to `process.on`. */
@@ -38,10 +85,18 @@ export interface InterruptDeps {
38
85
  stderr?: (line: string) => void;
39
86
  /** Process exit. Defaults to `process.exit`. */
40
87
  exit?: (code: number) => void;
88
+ /** Shutdown coordinator. Defaults to {@link globalShutdown}. */
89
+ shutdown?: ShutdownController;
41
90
  }
42
91
  /**
43
92
  * Register handlers for SIGINT, SIGTERM and SIGHUP. Idempotent enough for a
44
93
  * single top-level call in `index.ts`; not designed to be installed twice.
94
+ *
95
+ * First signal, armed scope: abort-only — the `--wait` catch paths own the
96
+ * honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
97
+ * First signal, disarmed: print the generic explanation + exit `128+signum`.
98
+ * Second signal (any mode): immediate hard exit — the escape hatch when the
99
+ * graceful cleanup itself wedges.
45
100
  */
46
101
  export declare function installSignalHandlers(deps?: InterruptDeps): void;
47
102
  export interface BrokenPipeDeps {
@@ -18,18 +18,79 @@
18
18
  * `process` and the streams are injectable so the wiring is unit-testable
19
19
  * without spawning a subprocess or sending a real signal.
20
20
  */
21
+ import { setMaxListeners } from 'node:events';
21
22
  import { writeSync } from 'node:fs';
22
- /**
23
- * Termination signals handled, mapped to their conventional `128 + signum`
24
- * exit code. sourceRef: POSIX signal numbers (SIGHUP=1, SIGINT=2, SIGTERM=15).
25
- */
26
- export const TERMINATION_EXIT_CODES = {
27
- SIGINT: 130, // 128 + 2
28
- SIGTERM: 143, // 128 + 15
29
- SIGHUP: 129, // 128 + 1
30
- };
23
+ import { InterruptError, TERMINATION_EXIT_CODES } from './errors.js';
24
+ export { TERMINATION_EXIT_CODES } from './errors.js';
31
25
  /** Back-compat alias: SIGINT's conventional exit code. */
32
26
  export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
27
+ /**
28
+ * Process-lifetime coordinator between the signal handler and the `--wait`
29
+ * polling paths (DEV-331 piece 1).
30
+ *
31
+ * Two modes, chosen by whether a graceful-detach scope is armed when the
32
+ * signal arrives:
33
+ *
34
+ * - **Armed** (inside `pollRunUntilTerminal`): the handler only aborts
35
+ * `signal` with an `InterruptError` — no I/O, no exit. The in-flight fetch
36
+ * and every backoff sleep bail immediately; the `--wait` catch blocks own
37
+ * the cleanup (finalize the ticker, print the honest partial envelope +
38
+ * re-attach hint, rethrow to `index.ts` → exit 130/143/129).
39
+ * - **Disarmed** (no wait in progress — prompts, one-shot commands, local
40
+ * FS work): the handler prints the generic explanation and exits
41
+ * immediately, preserving the pre-DEV-331 behavior. An abort nobody
42
+ * observes must never leave the process hanging at e.g. a readline prompt.
43
+ *
44
+ * A second signal while the armed cleanup is in flight is the documented
45
+ * escape hatch: immediate hard exit.
46
+ */
47
+ export class ShutdownController {
48
+ controller = new AbortController();
49
+ armedCount = 0;
50
+ receivedSignal = null;
51
+ constructor() {
52
+ // Every fetch and every poll iteration composes this signal via
53
+ // AbortSignal.any — a 50-run batch fan-out legitimately holds >10
54
+ // concurrent listeners, so silence Node's MaxListeners warning.
55
+ setMaxListeners(0, this.controller.signal);
56
+ }
57
+ get signal() {
58
+ return this.controller.signal;
59
+ }
60
+ /** The first termination signal received, or null if none yet. */
61
+ get received() {
62
+ return this.receivedSignal;
63
+ }
64
+ get isArmed() {
65
+ return this.armedCount > 0;
66
+ }
67
+ /**
68
+ * Enter a graceful-detach scope (re-entrant: fan-out members overlap).
69
+ * Returns an idempotent disposer.
70
+ */
71
+ arm() {
72
+ this.armedCount += 1;
73
+ let disposed = false;
74
+ return () => {
75
+ if (disposed)
76
+ return;
77
+ disposed = true;
78
+ this.armedCount -= 1;
79
+ };
80
+ }
81
+ /** Record the signal and abort with an `InterruptError` carrying it. */
82
+ interrupt(signal) {
83
+ this.receivedSignal = signal;
84
+ this.controller.abort(new InterruptError(signal));
85
+ }
86
+ }
87
+ /**
88
+ * The process-wide instance: `index.ts` hands it to `installSignalHandlers`,
89
+ * and it is the default `shutdown` for `TestDeps` / `PollOptions` /
90
+ * `ClientFactoryDeps`, so production wiring is automatic. Tests inject their
91
+ * own `ShutdownController` (or a `ShutdownHandle` fake) instead.
92
+ */
93
+ export const globalShutdown = new ShutdownController();
33
94
  export function formatInterruptMessage(signal = 'SIGINT') {
34
95
  return (`Interrupted (${signal}). Any run already started keeps executing on the server; ` +
35
96
  'check it with `testsprite test list` or `testsprite test wait <runId>`.');
@@ -37,6 +98,12 @@ export function formatInterruptMessage(signal = 'SIGINT') {
37
98
  /**
38
99
  * Register handlers for SIGINT, SIGTERM and SIGHUP. Idempotent enough for a
39
100
  * single top-level call in `index.ts`; not designed to be installed twice.
101
+ *
102
+ * First signal, armed scope: abort-only — the `--wait` catch paths own the
103
+ * honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
104
+ * First signal, disarmed: print the generic explanation + exit `128+signum`.
105
+ * Second signal (any mode): immediate hard exit — the escape hatch when the
106
+ * graceful cleanup itself wedges.
40
107
  */
41
108
  export function installSignalHandlers(deps = {}) {
42
109
  const on = deps.on ??
@@ -56,8 +123,26 @@ export function installSignalHandlers(deps = {}) {
56
123
  }
57
124
  });
58
125
  const exit = deps.exit ?? ((code) => process.exit(code));
126
+ const shutdown = deps.shutdown ?? globalShutdown;
59
127
  for (const signal of Object.keys(TERMINATION_EXIT_CODES)) {
60
128
  on(signal, () => {
129
+ if (shutdown.received !== null) {
130
+ // Second signal while graceful cleanup is in flight: hard exit now.
131
+ exit(TERMINATION_EXIT_CODES[signal]);
132
+ return;
133
+ }
134
+ if (shutdown.isArmed) {
135
+ // Graceful detach: abort only (sync, signal-safe — no I/O here so a
136
+ // pending stdout `drain` wait can settle); the armed catch paths
137
+ // finalize the ticker, print the partial + re-attach hint, and exit
138
+ // via index.ts with this signal's code.
139
+ shutdown.interrupt(signal);
140
+ return;
141
+ }
142
+ // Disarmed (no --wait in progress): legacy immediate exit. Record the
143
+ // signal first so a second one takes the hard-exit branch even when
144
+ // `exit` is injected and does not terminate (unit tests).
145
+ shutdown.interrupt(signal);
61
146
  // Blank line first so the message starts on its own row rather than
62
147
  // trailing the progress ticker's in-place line.
63
148
  stderr('');
@@ -20,6 +20,7 @@
20
20
  * 5xx → single retry honoring Retry-After, second 5xx throws (exit 9).
21
21
  * Deadline exceeded → throw `TimeoutError`.
22
22
  */
23
+ import type { ShutdownHandle } from './interrupt.js';
23
24
  import type { RunResponse } from './runs.types.js';
24
25
  /**
25
26
  * Minimal interface that `pollRunUntilTerminal` requires from the HTTP client.
@@ -75,6 +76,16 @@ export interface PollOptions {
75
76
  * user's deadline (the per-request HTTP timeout is much larger).
76
77
  */
77
78
  resolveAlternate?: (run: RunResponse, elapsedMs: number, signal: AbortSignal) => Promise<RunResponse | null>;
79
+ /**
80
+ * Graceful-detach coordinator (DEV-331 piece 1). While the poll runs, the
81
+ * scope is armed: a SIGINT/SIGTERM aborts `shutdown.signal` with an
82
+ * `InterruptError` instead of killing the process, and this loop surfaces
83
+ * it immediately — the in-flight long-poll fetch aborts (composed into the
84
+ * per-iteration signal) and every backoff/retry sleep bails early. The
85
+ * caller's catch block renders the honest partial + re-attach hint.
86
+ * Absent (tests, non-wait callers): behavior is unchanged.
87
+ */
88
+ shutdown?: ShutdownHandle;
78
89
  }
79
90
  /**
80
91
  * Poll `GET /api/cli/v1/runs/{runId}` until the run reaches a terminal
package/dist/lib/poll.js CHANGED
@@ -20,7 +20,7 @@
20
20
  * 5xx → single retry honoring Retry-After, second 5xx throws (exit 9).
21
21
  * Deadline exceeded → throw `TimeoutError`.
22
22
  */
23
- import { ApiError } from './errors.js';
23
+ import { ApiError, InterruptError } from './errors.js';
24
24
  import { isTerminalStatus } from './runs.types.js';
25
25
  /** Thrown when the polling deadline is hit. */
26
26
  export class TimeoutError extends Error {
@@ -44,8 +44,25 @@ const BACKOFF_SCHEDULE_MS = [2000, 4000, 8000, 15000];
44
44
  * and unrecoverable server errors.
45
45
  */
46
46
  export async function pollRunUntilTerminal(client, runId, options) {
47
+ // Arm the graceful-detach scope for the duration of the poll (DEV-331):
48
+ // while armed, a termination signal aborts instead of hard-killing the
49
+ // process, and the wait-path catch blocks own the honest detach UX.
50
+ const disarm = options.shutdown?.arm();
51
+ try {
52
+ return await pollLoop(client, runId, options);
53
+ }
54
+ finally {
55
+ disarm?.();
56
+ }
57
+ }
58
+ async function pollLoop(client, runId, options) {
47
59
  const { timeoutSeconds, onTick, onTransition, resolveAlternate } = options;
48
- const sleep = options.sleep ?? defaultSleep;
60
+ const shutdownSignal = options.shutdown?.signal;
61
+ const rawSleep = options.sleep ?? defaultSleep;
62
+ // Every sleep site (retryAfterSeconds, backoff schedule, not_yet_visible,
63
+ // 5xx retry) bails immediately on interrupt — a Ctrl-C must not sit out a
64
+ // 15s backoff before it is noticed.
65
+ const sleep = (ms) => sleepUnlessInterrupted(rawSleep, ms, shutdownSignal);
49
66
  const startMs = Date.now();
50
67
  const deadlineMs = startMs + timeoutSeconds * 1000;
51
68
  // Track whether the server supports ?waitSeconds. Start optimistic.
@@ -55,6 +72,10 @@ export async function pollRunUntilTerminal(client, runId, options) {
55
72
  // 404 not_yet_visible retry budget (one soft retry per event).
56
73
  let notYetVisibleRetries = 0;
57
74
  while (true) {
75
+ // Interrupt outranks the deadline: a Ctrl-C that raced the timeout must
76
+ // surface as the honest detach, not as a generic TimeoutError.
77
+ if (shutdownSignal?.aborted)
78
+ throw shutdownSignal.reason;
58
79
  const now = Date.now();
59
80
  if (now >= deadlineMs) {
60
81
  throw new TimeoutError(runId, timeoutSeconds);
@@ -69,14 +90,21 @@ export async function pollRunUntilTerminal(client, runId, options) {
69
90
  const abortTimer = setTimeout(() => {
70
91
  abortController.abort();
71
92
  }, remainingMs + TRANSPORT_CUSHION_MS);
93
+ // Compose the interrupt into the per-iteration signal: a `--wait` can sit
94
+ // inside one <=25s long-poll fetch (and the auto-raised per-request
95
+ // timeout means even longer for slow backends) — checking the flag
96
+ // between iterations is not enough, the in-flight fetch must abort.
97
+ const iterationSignal = shutdownSignal != null
98
+ ? AbortSignal.any([abortController.signal, shutdownSignal])
99
+ : abortController.signal;
72
100
  let run;
73
101
  try {
74
102
  if (useBackoff) {
75
- run = await client.getRun(runId, { signal: abortController.signal });
103
+ run = await client.getRun(runId, { signal: iterationSignal });
76
104
  }
77
105
  else {
78
106
  const waitSeconds = Math.min(remainingSeconds, LONG_POLL_WAIT_SECONDS);
79
- run = await client.getRun(runId, { waitSeconds, signal: abortController.signal });
107
+ run = await client.getRun(runId, { waitSeconds, signal: iterationSignal });
80
108
  }
81
109
  // Successful GET resets the consecutive-error counter.
82
110
  consecutiveErrors = 0;
@@ -84,6 +112,13 @@ export async function pollRunUntilTerminal(client, runId, options) {
84
112
  }
85
113
  catch (err) {
86
114
  clearTimeout(abortTimer);
115
+ // Interrupt classification precedes the timeout mapping: the composed
116
+ // signal makes the fetch reject on Ctrl-C, and that abort must surface
117
+ // as the InterruptError — not as a spurious TimeoutError.
118
+ if (err instanceof InterruptError)
119
+ throw err;
120
+ if (shutdownSignal?.aborted)
121
+ throw shutdownSignal.reason;
87
122
  // An AbortError from our per-iteration controller means the deadline
88
123
  // passed while the fetch was in flight — surface as TimeoutError.
89
124
  if (isAbortError(err)) {
@@ -155,9 +190,15 @@ export async function pollRunUntilTerminal(client, runId, options) {
155
190
  }
156
191
  const altAbort = new AbortController();
157
192
  const altTimer = setTimeout(() => altAbort.abort(), altRemainingMs);
193
+ // The alternate lookup aborts on interrupt too; its errors are swallowed
194
+ // by the fallback (best-effort), so the loop-top interrupt check above
195
+ // surfaces the InterruptError on the next iteration.
196
+ const altSignal = shutdownSignal != null
197
+ ? AbortSignal.any([altAbort.signal, shutdownSignal])
198
+ : altAbort.signal;
158
199
  let alternate = null;
159
200
  try {
160
- alternate = await resolveAlternate(run, elapsedMs, altAbort.signal);
201
+ alternate = await resolveAlternate(run, elapsedMs, altSignal);
161
202
  }
162
203
  finally {
163
204
  clearTimeout(altTimer);
@@ -205,6 +246,30 @@ function backoffScheduleDelay(index) {
205
246
  function defaultSleep(ms) {
206
247
  return new Promise(resolve => setTimeout(resolve, ms));
207
248
  }
249
+ /**
250
+ * Race a sleep against the shutdown signal: rejects with the signal's
251
+ * `InterruptError` reason the moment it fires, so no backoff/retry wait can
252
+ * delay the honest-detach UX. Wraps the injected `sleep` (tests keep their
253
+ * deterministic fakes); the underlying timer is left to fire harmlessly —
254
+ * the interrupt path exits the process long before it matters.
255
+ */
256
+ function sleepUnlessInterrupted(sleep, ms, signal) {
257
+ if (signal == null)
258
+ return sleep(ms);
259
+ if (signal.aborted)
260
+ return Promise.reject(signal.reason);
261
+ return new Promise((resolve, reject) => {
262
+ const onAbort = () => reject(signal.reason);
263
+ signal.addEventListener('abort', onAbort, { once: true });
264
+ sleep(ms).then(() => {
265
+ signal.removeEventListener('abort', onAbort);
266
+ resolve();
267
+ }, err => {
268
+ signal.removeEventListener('abort', onAbort);
269
+ reject(err instanceof Error ? err : new Error(String(err)));
270
+ });
271
+ });
272
+ }
208
273
  /**
209
274
  * Detects an AbortError thrown when an AbortSignal fires.
210
275
  * Works for native fetch AbortErrors as well as `AbortController.abort()`
@@ -203,6 +203,15 @@ export interface RunResponse {
203
203
  */
204
204
  steps?: RunStepDto[] | null;
205
205
  }
206
+ /**
207
+ * Response from `POST /api/cli/v1/runs/{runId}/cancel`.
208
+ * Same shape as `GET /runs/{runId}` (`status: "cancelled"`, verdict
209
+ * untouched) plus `alreadyCancelled` distinguishing a fresh cancel
210
+ * (naturally idempotent) from a no-op re-cancel.
211
+ */
212
+ export interface CancelRunResponse extends RunResponse {
213
+ alreadyCancelled: boolean;
214
+ }
206
215
  /** Terminal states from the RunStatus union. */
207
216
  export declare const TERMINAL_RUN_STATUSES: ReadonlySet<RunStatus>;
208
217
  export declare function isTerminalStatus(status: RunStatus): boolean;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Shared V3-routing text surfaces for `auth status` and `doctor`.
3
+ *
4
+ * `v3Enabled` on the `/me` response is the authoritative routing bit. When it
5
+ * is on, some commands behave differently while the V3 gaps stay open — the
6
+ * advisory names them. Copy lives here so both commands stay in sync.
7
+ */
8
+ /** One-word routing label for the text card. */
9
+ export declare function routingLabel(v3Enabled: boolean): 'v3' | 'v2';
10
+ /** Consolidated advisory (stderr) emitted when V3 routing is on. */
11
+ export declare const V3_ROUTING_ADVISORY: string[];
12
+ /** Write the advisory to a stderr sink, one line per call. */
13
+ export declare function emitV3RoutingAdvisory(stderr: (line: string) => void): void;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Shared V3-routing text surfaces for `auth status` and `doctor`.
3
+ *
4
+ * `v3Enabled` on the `/me` response is the authoritative routing bit. When it
5
+ * is on, some commands behave differently while the V3 gaps stay open — the
6
+ * advisory names them. Copy lives here so both commands stay in sync.
7
+ */
8
+ /** One-word routing label for the text card. */
9
+ export function routingLabel(v3Enabled) {
10
+ return v3Enabled ? 'v3' : 'v2';
11
+ }
12
+ /** Consolidated advisory (stderr) emitted when V3 routing is on. */
13
+ export const V3_ROUTING_ADVISORY = [
14
+ '[advisory] V3 routing is on for this account. While these gaps are open:',
15
+ ' - `test cancel` may return 404',
16
+ ' - `test delete` may leave a zombie run',
17
+ ' - `--target-url` is ignored on frontend runs',
18
+ ];
19
+ /** Write the advisory to a stderr sink, one line per call. */
20
+ export function emitV3RoutingAdvisory(stderr) {
21
+ for (const line of V3_ROUTING_ADVISORY)
22
+ stderr(line);
23
+ }
24
+ //# sourceMappingURL=v3-advisory.js.map