@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/index.js CHANGED
@@ -7,7 +7,7 @@ import { createDeprecatedInitCommand, createSetupCommand, runConfigureViaSetup,
7
7
  import { createProjectCommand } from './commands/project.js';
8
8
  import { createTestCommand } from './commands/test.js';
9
9
  import { createUsageCommand } from './commands/usage.js';
10
- import { ApiError, CLIError, RequestTimeoutError } from './lib/errors.js';
10
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError } from './lib/errors.js';
11
11
  import { installBrokenPipeGuard, installSignalHandlers } from './lib/interrupt.js';
12
12
  import { Output, isOutputMode } from './lib/output.js';
13
13
  import { maybeInstallProxyAgent } from './lib/proxy.js';
@@ -125,9 +125,12 @@ program.hook('preAction', (_thisCommand, actionCommand) => {
125
125
  void maybeNotifyUpdate();
126
126
  }
127
127
  });
128
- // Clean process lifecycle: a clear message + conventional exit code on SIGINT /
129
- // SIGTERM / SIGHUP (instead of Node's silent abrupt kill) so an interrupted
130
- // `test run --wait` explains the run continues server-side; plus an EPIPE guard
128
+ // Clean process lifecycle (DEV-331 piece 1, errors.md §8.1): during a `--wait`
129
+ // poll the scope is armed — the first SIGINT/SIGTERM/SIGHUP aborts gracefully
130
+ // and the wait path prints an honest partial (the run KEEPS executing and
131
+ // billing server-side) + re-attach hint before exiting 128+signum; a second
132
+ // signal hard-exits. Outside an armed scope: a clear one-line message +
133
+ // immediate exit (instead of Node's silent abrupt kill). Plus an EPIPE guard
131
134
  // so piping to a reader that closes early (`| head`) exits cleanly instead of
132
135
  // dumping a raw `write EPIPE` stack.
133
136
  installSignalHandlers();
@@ -171,10 +174,44 @@ catch (err) {
171
174
  process.stderr.write(` granted: ${granted.join(', ')}\n`);
172
175
  }
173
176
  }
177
+ // Surface the version gap on CLIENT_TOO_OLD so the user sees exactly what
178
+ // moved without parsing the message string. (No "latest" line — the npm
179
+ // update-notice is the single source of truth for the newest release.)
180
+ if (err.code === 'CLIENT_TOO_OLD') {
181
+ const your = err.getDetail('yourVersion');
182
+ const min = err.getDetail('minVersion');
183
+ if (typeof your === 'string' && typeof min === 'string') {
184
+ process.stderr.write(` your version: ${your}, minimum supported: ${min}\n`);
185
+ }
186
+ }
174
187
  }
175
188
  process.exit(err.exitCode);
176
189
  }
177
190
  const output = new Output(mode);
191
+ if (err instanceof InterruptError) {
192
+ // Graceful detach (DEV-331 piece 1, errors.md §8.1): the wait-path catch
193
+ // block already printed the honest partial + re-attach hint. Exit with
194
+ // the conventional 128+signum code; `INTERRUPTED` is deliberately outside
195
+ // the error catalog. Note: Ctrl-C does NOT cancel the server-side run.
196
+ if (mode === 'json') {
197
+ const envelope = {
198
+ error: {
199
+ code: 'INTERRUPTED',
200
+ message: err.message,
201
+ nextAction: 'The server-side run (if any) keeps executing and billing. ' +
202
+ 'Re-attach with: testsprite test wait <runId>, or stop it with: testsprite test cancel <runId> ' +
203
+ '(runId is in the partial JSON on stdout).',
204
+ requestId: 'local',
205
+ details: { signal: err.signal },
206
+ },
207
+ };
208
+ process.stderr.write(`${JSON.stringify(envelope, null, 2)}\n`);
209
+ }
210
+ else {
211
+ process.stderr.write(`Error: ${err.message}\n`);
212
+ }
213
+ process.exit(err.exitCode);
214
+ }
178
215
  if (err instanceof RequestTimeoutError) {
179
216
  // Structured rendering for per-request timeouts: JSON mode emits a
180
217
  // machine-readable envelope; text mode emits the message with a hint.
@@ -169,6 +169,24 @@ export function applyFailedOnly(ctx) {
169
169
  failure: { ...ctx.failure, evidence: filteredEvidence },
170
170
  };
171
171
  }
172
+ /**
173
+ * Strip trailing path separators, tolerating both `/` and `\` since a
174
+ * native Windows `--out` value (typed or pasted from Explorer) commonly
175
+ * ends in a backslash. Preserves a bare drive root (`C:\`) — stripping
176
+ * its separator would turn it into `C:`, which Windows resolves as
177
+ * "current directory on drive C", not the drive root.
178
+ */
179
+ function stripTrailingSeparators(rawPath) {
180
+ if (rawPath.length <= 1)
181
+ return rawPath;
182
+ let end = rawPath.length;
183
+ while (end > 1 && (rawPath[end - 1] === '/' || rawPath[end - 1] === '\\')) {
184
+ if (end === 3 && rawPath[1] === ':' && /[A-Za-z]/.test(rawPath[0]))
185
+ break;
186
+ end--;
187
+ }
188
+ return rawPath.slice(0, end);
189
+ }
172
190
  /**
173
191
  * Resolve the user-supplied `--out` path into an absolute directory.
174
192
  * Empty strings are rejected with `VALIDATION_ERROR` for consistency
@@ -188,7 +206,7 @@ export function resolveBundleDir(rawPath) {
188
206
  },
189
207
  });
190
208
  }
191
- const trimmed = rawPath.endsWith('/') ? rawPath.slice(0, -1) : rawPath;
209
+ const trimmed = stripTrailingSeparators(rawPath);
192
210
  return isAbsolute(trimmed) ? trimmed : resolve(process.cwd(), trimmed);
193
211
  }
194
212
  /**
@@ -41,6 +41,12 @@ export interface ClientFactoryDeps {
41
41
  credentialsPath?: string;
42
42
  fetchImpl?: FetchImpl;
43
43
  stderr?: (line: string) => void;
44
+ /**
45
+ * Shutdown signal composed into every outgoing fetch (DEV-331 piece 1).
46
+ * Defaults to `globalShutdown.signal` so an armed SIGINT/SIGTERM aborts an
47
+ * in-flight request; tests inject their own controller's signal.
48
+ */
49
+ shutdownSignal?: AbortSignal;
44
50
  }
45
51
  /**
46
52
  * The fake API key used in dry-run. Never sent — the dry-run fetch
@@ -18,7 +18,10 @@ import { defaultCredentialsPath } from './credentials.js';
18
18
  import { ApiError, localValidationError } from './errors.js';
19
19
  import { facadeBaseUrl } from './facade.js';
20
20
  import { HttpClient, REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, REQUEST_TIMEOUT_MIN_MS, } from './http.js';
21
+ import { globalShutdown } from './interrupt.js';
21
22
  import { createDryRunFetch } from './dry-run/fetch.js';
23
+ import { noteServerVersion } from './version-notice.js';
24
+ import { VERSION } from '../version.js';
22
25
  /**
23
26
  * The fake API key used in dry-run. Never sent — the dry-run fetch
24
27
  * impl ignores headers and returns a canned sample. Documented in the
@@ -173,6 +176,7 @@ export function makeHttpClient(opts, deps = {}) {
173
176
  onDebug: opts.debug ? (event) => stderr(formatDryRunDebug(event)) : undefined,
174
177
  onTransition: opts.verbose ? (msg) => stderr(`[verbose] ${msg}`) : undefined,
175
178
  requestTimeoutMs,
179
+ shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
176
180
  });
177
181
  }
178
182
  const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
@@ -195,7 +199,19 @@ export function makeHttpClient(opts, deps = {}) {
195
199
  fetchImpl: deps.fetchImpl,
196
200
  onDebug: opts.debug ? (event) => stderr(formatDebug(event)) : undefined,
197
201
  onTransition: opts.verbose ? (msg) => stderr(`[verbose] ${msg}`) : undefined,
202
+ // Warn once if the backend advertises a minimum supported version above
203
+ // this binary's. Gating (opt-out env, TTY, output mode, dry-run) lives in
204
+ // noteServerVersion; the client just forwards the observed headers.
205
+ onServerVersion: info => noteServerVersion(info, {
206
+ currentVersion: VERSION,
207
+ env,
208
+ isTTY: process.stderr.isTTY === true,
209
+ outputMode: opts.output,
210
+ dryRun: opts.dryRun,
211
+ stderr,
212
+ }),
198
213
  requestTimeoutMs,
214
+ shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
199
215
  });
200
216
  }
201
217
  function formatDebug(event) {
@@ -58,6 +58,7 @@ const me = {
58
58
  keyId: SAMPLE_KEY_ID,
59
59
  scopes: ['read:projects', 'read:tests', 'write:tests', 'run:tests'],
60
60
  env: 'development',
61
+ v3Enabled: true,
61
62
  };
62
63
  const projects = [
63
64
  {
@@ -304,6 +305,11 @@ const ENTRIES = [
304
305
  updatedFields: ['name'],
305
306
  updatedAt: '2026-05-16T00:00:00.000Z',
306
307
  }),
308
+ // DELETE /projects/{id} (cascade delete project + tests + fixtures).
309
+ entry('deleteProject', 'DELETE', '/projects/{projectId}', {
310
+ projectId: SAMPLE_PROJECT_ID,
311
+ deletedAt: '2026-05-16T00:00:00.000Z',
312
+ }),
307
313
  entry('listTests', 'GET', '/tests', pageOf(tests)),
308
314
  entry('getTestCode', 'GET', '/tests/{testId}/code', testCode),
309
315
  entry('listTestSteps', 'GET', '/tests/{testId}/steps', pageOf(testSteps)),
@@ -654,6 +660,36 @@ const ENTRIES = [
654
660
  },
655
661
  ],
656
662
  }),
663
+ // DEV-331 piece 3 — POST /runs/{runId}/cancel. Method-guarded in
664
+ // `findSample` (POST vs `getRun`'s GET), so this can't be shadowed by the
665
+ // broader `/runs/{runId}` pattern above despite sharing its path prefix.
666
+ // `alreadyCancelled: false` — a fresh cancel is the more instructive shape
667
+ // for a dry-run learner than the idempotent no-op.
668
+ entry('cancelRun', 'POST', '/runs/{runId}/cancel', {
669
+ runId: SAMPLE_RUN_ID,
670
+ testId: SAMPLE_TEST_ID_PASSED,
671
+ projectId: SAMPLE_PROJECT_ID,
672
+ userId: SAMPLE_USER_ID,
673
+ status: 'cancelled',
674
+ source: 'cli',
675
+ createdAt: '2026-05-15T19:32:00.000Z',
676
+ startedAt: '2026-05-15T19:32:05.000Z',
677
+ finishedAt: '2026-05-15T19:33:12.000Z',
678
+ codeVersion: 'v1',
679
+ targetUrl: SAMPLE_TARGET_URL,
680
+ createdFrom: null,
681
+ failedStepIndex: null,
682
+ failureKind: null,
683
+ error: null,
684
+ videoUrl: null,
685
+ stepSummary: {
686
+ total: 8,
687
+ completed: 3,
688
+ passedCount: 3,
689
+ failedCount: 0,
690
+ },
691
+ alreadyCancelled: false,
692
+ }),
657
693
  ];
658
694
  function entry(operationId, method, pathTemplate, body) {
659
695
  // Convert `/tests/{testId}/code` → /^\/tests\/[^/]+\/code$/
@@ -2,7 +2,7 @@
2
2
  * Error codes shared with the backend facade and the MCP plugin.
3
3
  * Must stay in sync across all three.
4
4
  */
5
- export declare const ERROR_CODES: readonly ["AUTH_REQUIRED", "AUTH_INVALID", "AUTH_FORBIDDEN", "NOT_FOUND", "VALIDATION_ERROR", "PAYLOAD_TOO_LARGE", "CONFLICT", "PRECONDITION_FAILED", "IDEMPOTENCY_BODY_MISMATCH", "RATE_LIMITED", "INSUFFICIENT_CREDITS", "FEATURE_GATED", "UNSUPPORTED", "INTERNAL", "UNAVAILABLE"];
5
+ export declare const ERROR_CODES: readonly ["AUTH_REQUIRED", "AUTH_INVALID", "AUTH_FORBIDDEN", "NOT_FOUND", "VALIDATION_ERROR", "PAYLOAD_TOO_LARGE", "CONFLICT", "PRECONDITION_FAILED", "IDEMPOTENCY_BODY_MISMATCH", "RATE_LIMITED", "INSUFFICIENT_CREDITS", "FEATURE_GATED", "UNSUPPORTED", "CLIENT_TOO_OLD", "INTERNAL", "UNAVAILABLE"];
6
6
  export type ErrorCode = (typeof ERROR_CODES)[number];
7
7
  export declare function isErrorCode(value: unknown): value is ErrorCode;
8
8
  /**
@@ -15,6 +15,33 @@ export declare class CLIError extends Error {
15
15
  readonly exitCode: number;
16
16
  constructor(message: string, exitCode?: number);
17
17
  }
18
+ /**
19
+ * Termination signals with graceful handling, mapped to their conventional
20
+ * `128 + signum` exit code. sourceRef: POSIX signal numbers (SIGHUP=1,
21
+ * SIGINT=2, SIGTERM=15). Lives here (not interrupt.ts) so `InterruptError`
22
+ * needs no import cycle; `interrupt.ts` re-exports for back-compat.
23
+ */
24
+ export declare const TERMINATION_EXIT_CODES: {
25
+ readonly SIGINT: 130;
26
+ readonly SIGTERM: 143;
27
+ readonly SIGHUP: 129;
28
+ };
29
+ export type TerminationSignal = keyof typeof TERMINATION_EXIT_CODES;
30
+ /**
31
+ * User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed while a
32
+ * graceful-detach scope (the `--wait` polling window) was armed — see
33
+ * `interrupt.ts::ShutdownController`. The `--wait` catch blocks render the
34
+ * honest partial envelope + re-attach hint, then rethrow to `index.ts`.
35
+ *
36
+ * Deliberately NOT in `ERROR_CODES` — on a signal the CLI
37
+ * exits 130/143 without consulting the error catalog. The JSON-mode stderr
38
+ * envelope uses the out-of-catalog code `"INTERRUPTED"`. Same client-local
39
+ * synthetic category as `RequestTimeoutError`.
40
+ */
41
+ export declare class InterruptError extends CLIError {
42
+ readonly signal: TerminationSignal;
43
+ constructor(signal: TerminationSignal);
44
+ }
18
45
  export declare class NotImplementedError extends CLIError {
19
46
  constructor(commandPath: string);
20
47
  }
@@ -44,6 +44,12 @@ export const ERROR_CODES = [
44
44
  // so the CLI can drop the client-side detection heuristic.
45
45
  'FEATURE_GATED',
46
46
  'UNSUPPORTED',
47
+ // The running CLI is older than the backend's minimum supported version.
48
+ // Backend emits this as HTTP 426 when version enforcement is enabled. Exit
49
+ // 14, non-retriable — a too-old client cannot self-heal by retrying; the
50
+ // user must upgrade. `nextAction` carries the upgrade instruction and
51
+ // `details` echoes { minVersion, latestVersion, yourVersion }.
52
+ 'CLIENT_TOO_OLD',
47
53
  'INTERNAL',
48
54
  'UNAVAILABLE',
49
55
  ];
@@ -72,6 +78,8 @@ export function exitCodeFor(code) {
72
78
  return 6;
73
79
  case 'UNSUPPORTED':
74
80
  return 7;
81
+ case 'CLIENT_TOO_OLD':
82
+ return 14;
75
83
  case 'UNAVAILABLE':
76
84
  return 10;
77
85
  case 'RATE_LIMITED':
@@ -92,6 +100,36 @@ export class CLIError extends Error {
92
100
  this.exitCode = exitCode;
93
101
  }
94
102
  }
103
+ /**
104
+ * Termination signals with graceful handling, mapped to their conventional
105
+ * `128 + signum` exit code. sourceRef: POSIX signal numbers (SIGHUP=1,
106
+ * SIGINT=2, SIGTERM=15). Lives here (not interrupt.ts) so `InterruptError`
107
+ * needs no import cycle; `interrupt.ts` re-exports for back-compat.
108
+ */
109
+ export const TERMINATION_EXIT_CODES = {
110
+ SIGINT: 130, // 128 + 2
111
+ SIGTERM: 143, // 128 + 15
112
+ SIGHUP: 129, // 128 + 1
113
+ };
114
+ /**
115
+ * User-initiated interrupt (SIGINT/SIGTERM/SIGHUP) observed while a
116
+ * graceful-detach scope (the `--wait` polling window) was armed — see
117
+ * `interrupt.ts::ShutdownController`. The `--wait` catch blocks render the
118
+ * honest partial envelope + re-attach hint, then rethrow to `index.ts`.
119
+ *
120
+ * Deliberately NOT in `ERROR_CODES` — on a signal the CLI
121
+ * exits 130/143 without consulting the error catalog. The JSON-mode stderr
122
+ * envelope uses the out-of-catalog code `"INTERRUPTED"`. Same client-local
123
+ * synthetic category as `RequestTimeoutError`.
124
+ */
125
+ export class InterruptError extends CLIError {
126
+ signal;
127
+ constructor(signal) {
128
+ super(`Interrupted by ${signal}.`, TERMINATION_EXIT_CODES[signal]);
129
+ this.name = 'InterruptError';
130
+ this.signal = signal;
131
+ }
132
+ }
95
133
  export class NotImplementedError extends CLIError {
96
134
  constructor(commandPath) {
97
135
  super(`Command not yet implemented: ${commandPath}`, 2);
@@ -270,6 +308,8 @@ function codeFromHttpStatus(status) {
270
308
  return 'PRECONDITION_FAILED';
271
309
  case 413:
272
310
  return 'PAYLOAD_TOO_LARGE';
311
+ case 426:
312
+ return 'CLIENT_TOO_OLD';
273
313
  case 429:
274
314
  return 'RATE_LIMITED';
275
315
  case 501:
@@ -43,6 +43,21 @@ export interface ResolverOptions {
43
43
  * Each page uses pageSize=50, so 5 pages = 250 tests scanned.
44
44
  */
45
45
  maxPages?: number;
46
+ /**
47
+ * DEV-393: the operator's pinned `failingFrontendTestId` (the static value
48
+ * from fixtures.local.json). "Freshest failed" alone is fragile in a shared
49
+ * project: any OTHER FE test that fails more recently than a dedicated,
50
+ * permanently-red fixture silently steals the slot (live-reproduced
51
+ * 2026-07-16 — a `passingFrontendTestId` fresh-run flip immediately
52
+ * outranked the dedicated fixture on `updatedAt`). When set, the pinned id
53
+ * is probed directly first (one GET /tests/{id} — immune to the maxPages
54
+ * list-scan cap); if it is currently `status:failed` it wins outright,
55
+ * regardless of timestamp. If the probe errors, the list scan below still
56
+ * prefers the pinned id when it appears among the candidates. Falls through
57
+ * to the existing freshest-wins behavior when unset or no longer failing —
58
+ * fully backward compatible.
59
+ */
60
+ preferredId?: string;
46
61
  }
47
62
  export interface ResolverResult {
48
63
  /** The resolved failing frontend test id, or null if none found. */
@@ -24,8 +24,44 @@
24
24
  * when no Failed test exists — never throws.
25
25
  */
26
26
  export async function resolveFailingFrontendTestId(opts) {
27
- const { baseUrl, apiKey, projectId, maxPages = 5 } = opts;
27
+ const { baseUrl, apiKey, projectId, maxPages = 5, preferredId } = opts;
28
28
  const fetchImpl = opts.fetchImpl ?? fetch;
29
+ // DEV-393 (codex F3): probe the pinned fixture directly first, so the
30
+ // preference cannot be defeated by the maxPages list-scan cap (a pinned
31
+ // fixture beyond page `maxPages` would otherwise silently lose the slot to
32
+ // an incidental fresher failure). Any probe error or non-failed status
33
+ // falls through to the list scan; the in-candidates preference there
34
+ // remains as a second chance after a transient probe failure.
35
+ if (preferredId) {
36
+ try {
37
+ const resp = await fetchImpl(`${baseUrl}/tests/${encodeURIComponent(preferredId)}`, {
38
+ headers: {
39
+ 'x-api-key': apiKey,
40
+ 'x-request-id': `dev-e2e-resolver-preferred-${Date.now()}`,
41
+ accept: 'application/json',
42
+ },
43
+ signal: AbortSignal.timeout(10_000),
44
+ });
45
+ if (resp.ok) {
46
+ const test = (await resp.json());
47
+ // The probe must honor the resolver's project scope (codex round 2):
48
+ // the list path filters by projectId server-side, so a pin that
49
+ // points at a failed FE test in a DIFFERENT project must not win
50
+ // here either. A response without a matching projectId (absent or
51
+ // mismatched) falls through to the project-scoped list scan.
52
+ if (test.type === 'frontend' && test.status === 'failed' && test.projectId === projectId) {
53
+ return {
54
+ testId: preferredId,
55
+ reason: `Preferred pinned failingFrontendTestId (${preferredId}) confirmed status:failed ` +
56
+ `via direct GET (updatedAt=${test.updatedAt ?? 'unknown'}); list scan skipped`,
57
+ };
58
+ }
59
+ }
60
+ }
61
+ catch {
62
+ // Transient probe failure — fall through to the list scan below.
63
+ }
64
+ }
29
65
  const candidates = [];
30
66
  let cursor;
31
67
  let pagesFetched = 0;
@@ -82,6 +118,18 @@ export async function resolveFailingFrontendTestId(opts) {
82
118
  reason: 'No frontend tests with status=failed found in project; falling back to static fixture',
83
119
  };
84
120
  }
121
+ // DEV-393: a pinned, dedicated "always red" fixture wins over freshest
122
+ // whenever it is still in the failed set — see the doc comment on
123
+ // ResolverOptions.preferredId for why "freshest" alone is not enough.
124
+ if (preferredId) {
125
+ const pinned = candidates.find(c => c.id === preferredId);
126
+ if (pinned) {
127
+ return {
128
+ testId: pinned.id,
129
+ reason: `Preferred pinned failingFrontendTestId (${pinned.id}) is still status:failed (updatedAt=${pinned.updatedAt}); took priority over freshest-updatedAt candidate`,
130
+ };
131
+ }
132
+ }
85
133
  // Pick the most recently updated candidate — freshest failure is the
86
134
  // most likely to have a valid failure bundle attached.
87
135
  candidates.sort((a, b) => {
@@ -1,6 +1,6 @@
1
1
  import type { ErrorCode } from './errors.js';
2
2
  import { ApiError } from './errors.js';
3
- import type { TriggerRunBody, TriggerRunResponse, RunResponse, RerunRequest, RerunResponse, BatchRerunRequest, BatchRerunResponse, BatchRunFreshRequest, BatchRunFreshResponse, ListRunsQuery, ListRunsResponse } from './runs.types.js';
3
+ import type { TriggerRunBody, TriggerRunResponse, RunResponse, RerunRequest, RerunResponse, BatchRerunRequest, BatchRerunResponse, BatchRunFreshRequest, BatchRunFreshResponse, ListRunsQuery, ListRunsResponse, CancelRunResponse } from './runs.types.js';
4
4
  export type FetchImpl = typeof globalThis.fetch;
5
5
  export type DebugEventKind = 'request' | 'response' | 'retry' | 'error';
6
6
  export interface DebugEvent {
@@ -53,6 +53,16 @@ export interface HttpClientOptions {
53
53
  * Stays silent when absent; wired to stderr at `--verbose` level.
54
54
  */
55
55
  onTransition?: (msg: string) => void;
56
+ /**
57
+ * Optional callback fired with the backend's supported-floor header
58
+ * (`X-TestSprite-CLI-Min-Version`) when present on a response. Fires on both
59
+ * success and error responses. The client forwards the value verbatim — it
60
+ * applies no policy itself; the caller (client-factory) decides whether to
61
+ * warn the user.
62
+ */
63
+ onServerVersion?: (info: {
64
+ minVersion?: string;
65
+ }) => void;
56
66
  /**
57
67
  * Per-request wall-clock timeout in milliseconds applied to every outgoing
58
68
  * fetch. The signal fires independently of any caller-supplied signal — the
@@ -66,6 +76,16 @@ export interface HttpClientOptions {
66
76
  * request is well within the 120s default.
67
77
  */
68
78
  requestTimeoutMs?: number;
79
+ /**
80
+ * Process-lifetime shutdown signal (DEV-331 piece 1). Composed into every
81
+ * outgoing fetch so an armed SIGINT/SIGTERM aborts an in-flight request
82
+ * (a `--wait` long-poll can sit inside a single fetch for minutes) instead
83
+ * of waiting out its window. Aborts with an `InterruptError` reason, which
84
+ * is classified before the timeout-vs-caller logic and is never retried or
85
+ * re-wrapped as `TransportError`. Defaults off; production wiring passes
86
+ * `globalShutdown.signal` via the client factory.
87
+ */
88
+ shutdownSignal?: AbortSignal;
69
89
  }
70
90
  export interface RequestOptions {
71
91
  query?: Record<string, string | number | boolean | undefined>;
@@ -126,8 +146,18 @@ export declare class HttpClient {
126
146
  private readonly random;
127
147
  private readonly onDebug?;
128
148
  private readonly onTransition?;
149
+ private readonly onServerVersion?;
129
150
  private readonly requestTimeoutMs;
151
+ private readonly shutdownSignal?;
130
152
  constructor(options: HttpClientOptions);
153
+ /**
154
+ * Read the backend's supported-floor header off a response and forward it to
155
+ * `onServerVersion` when present. Never throws — a bad header must not break
156
+ * the request. Called on every response (success or error) so the advisory
157
+ * covers all paths. (The backend advertises only the floor; "latest" is
158
+ * resolved client-side via the npm update-notice.)
159
+ */
160
+ private captureServerVersion;
131
161
  get<T>(path: string, options?: RequestOptions): Promise<T>;
132
162
  post<T>(path: string, options?: RequestOptions): Promise<T>;
133
163
  put<T>(path: string, options?: RequestOptions): Promise<T>;
@@ -232,6 +262,20 @@ export declare class HttpClient {
232
262
  includeSteps?: boolean;
233
263
  signal?: AbortSignal;
234
264
  }): Promise<RunResponse>;
265
+ /**
266
+ * POST /api/cli/v1/runs/{runId}/cancel
267
+ * User-initiated cancel of a queued/running run (DEV-331 piece 3). No
268
+ * body, no `Idempotency-Key` — the endpoint is naturally idempotent (D10):
269
+ * re-cancel → 200 `alreadyCancelled: true`; already-terminal (passed/
270
+ * failed/blocked) → 409 CONFLICT; unknown/cross-tenant runId → 404.
271
+ *
272
+ * `retryOnConflict: false` — same rationale as `triggerRun`: a 409 here is
273
+ * a truthful terminal answer ("already finished"), not a transient
274
+ * snapshot conflict to paper over with a retry.
275
+ */
276
+ cancelRun(runId: string, options?: {
277
+ signal?: AbortSignal;
278
+ }): Promise<CancelRunResponse>;
235
279
  /**
236
280
  * Classify an error thrown while issuing OR reading a request. When it is an
237
281
  * abort/timeout and our per-request timeout signal fired (and the caller had
@@ -243,6 +287,14 @@ export declare class HttpClient {
243
287
  private rethrowIfAbort;
244
288
  requestWithMeta<T>(method: string, path: string, options?: RequestOptions): Promise<RequestResult<T>>;
245
289
  private buildHeaders;
290
+ /**
291
+ * Retry-delay sleep that bails the moment the shutdown signal fires
292
+ * (DEV-331, codex finding 1): a RATE_LIMITED `Retry-After: 60` or a
293
+ * transport backoff must not delay the honest-detach exit by up to a
294
+ * minute — reject with the InterruptError reason immediately. Mirrors
295
+ * poll.ts::sleepUnlessInterrupted.
296
+ */
297
+ private sleepBeforeRetry;
246
298
  private debug;
247
299
  private transition;
248
300
  /**