@testsprite/testsprite-cli 0.11.0 → 0.12.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.
@@ -6,7 +6,8 @@ import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, } from '../lib/http
6
6
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
7
7
  import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
8
8
  import { emitCiArtifacts, summarizeAcceptedPayload } from '../lib/gh-output.js';
9
- import { describeConflict, summarizeConflicts } from '../lib/conflict-reason.js';
9
+ import { describeConflict, insufficientCreditsConflictError, isAllCreditsRefusal, summarizeConflicts, } from '../lib/conflict-reason.js';
10
+ import { recordBatchOutcome } from '../lib/telemetry.js';
10
11
  import { formatRunProgressLine } from '../lib/run-progress.js';
11
12
  import { createTicker } from '../lib/ticker.js';
12
13
  import { buildJUnitReport, parseJUnitReportFormat, writeJUnitReportFile, } from '../lib/junit-report.js';
@@ -339,6 +340,12 @@ export async function runTestlistRun(opts, deps = {}) {
339
340
  // flows through the tail below so its CI artifacts are still emitted.
340
341
  if (resp.accepted.length === 0 && resp.conflicts.length > 0) {
341
342
  out.print(resp, () => renderRunAcceptedText(resp));
343
+ recordBatchOutcome({
344
+ accepted: 0,
345
+ conflicts: resp.conflicts,
346
+ deferred: resp.deferred.length,
347
+ skipped: 0,
348
+ });
342
349
  // Surface the exit-6 in CI too (only under --wait, the CI-artifact contract):
343
350
  // an all-conflict re-run — every targeted case already in flight — otherwise
344
351
  // exits 6 with no ::error:: annotation and no summary file. The conflicts fold
@@ -360,6 +367,12 @@ export async function runTestlistRun(opts, deps = {}) {
360
367
  stderr: stderrFn,
361
368
  }, 'testlist run');
362
369
  }
370
+ // Every case refused for credits → exit 12, the same INSUFFICIENT_CREDITS
371
+ // envelope the single-run route answers (a rate-deferred remainder is exit 7
372
+ // below; `isAllCreditsRefusal` requires an empty deferred set).
373
+ if (isAllCreditsRefusal(resp)) {
374
+ throw insufficientCreditsConflictError(resp.conflicts, client.resolvedBaseUrl);
375
+ }
363
376
  const pollIds = resp.conflicts
364
377
  .map(c => c.currentRunId)
365
378
  .filter((id) => Boolean(id));
@@ -376,6 +389,12 @@ export async function runTestlistRun(opts, deps = {}) {
376
389
  out.print(resp, () => resp.accepted.length > 0
377
390
  ? renderRunAcceptedText(resp)
378
391
  : `No runs dispatched${resp.reason ? ` (${resp.reason})` : ''}.`);
392
+ recordBatchOutcome({
393
+ accepted: resp.accepted.length,
394
+ conflicts: resp.conflicts,
395
+ deferred: resp.deferred.length,
396
+ skipped: 0,
397
+ });
379
398
  assertNoDeferred(resp);
380
399
  assertNoNotFound(resp);
381
400
  return resp;
@@ -531,6 +550,13 @@ export async function runTestlistRun(opts, deps = {}) {
531
550
  await writeJUnitReportFile(opts.reportFile, xml);
532
551
  }
533
552
  out.print(jsonPayload, () => results.map(r => `${r.runId} ${r.status}`).join('\n'));
553
+ recordBatchOutcome({
554
+ accepted: resp.accepted.length,
555
+ conflicts: resp.conflicts,
556
+ deferred: resp.deferred.length,
557
+ skipped: 0,
558
+ results,
559
+ });
534
560
  // CI-native output parity with `test run` (--gh-output / --summary-file):
535
561
  // auto-enable under GITHUB_ACTIONS. Emit BEFORE the exit-code gates below so a
536
562
  // failing/timed-out/deferred run still gets its ::error:: annotations + the
@@ -728,8 +754,8 @@ export function createTestListCommand(deps = {}) {
728
754
  .option('--report <format>', 'with --wait: write a JUnit XML sidecar after polling (accepted: junit)')
729
755
  .option('--report-file <path>', 'output path for --report (atomic write)')
730
756
  .option('--report-suite-name <name>', 'JUnit <testsuite name=...> override (default: testsprite:testlist:<listId>)')
731
- .option('--gh-output', 'with --wait: emit GitHub-native output (::error:: annotations per non-passed member; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
732
- .option('--summary-file <path>', 'with --wait: also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
757
+ .option('--gh-output', 'with --wait: emit GitHub-native output (::error:: annotations for failed/timed-out members, ::warning:: for never-dispatched ones; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
758
+ .option('--summary-file <path>', 'with --wait: also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
733
759
  .addHelpText('after', GLOBAL_OPTS_HINT)
734
760
  .action(async (listId, cmdOpts, command) => {
735
761
  const wait = cmdOpts.wait === true;
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ import { createTestCommand } from './commands/test.js';
13
13
  import { createTestListCommand } from './commands/testlist.js';
14
14
  import { createUsageCommand } from './commands/usage.js';
15
15
  import { TARGETS } from './lib/agent-targets.js';
16
- import { ApiError, CLIError, InterruptError, RequestTimeoutError } from './lib/errors.js';
16
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, extractNodeErrorCode, } from './lib/errors.js';
17
17
  import { installBrokenPipeGuard, installSignalHandlers } from './lib/interrupt.js';
18
18
  import { Output, isOutputMode } from './lib/output.js';
19
19
  import { maybeInstallProxyAgent } from './lib/proxy.js';
@@ -307,6 +307,8 @@ catch (err) {
307
307
  outcome: telemetryOutcome.outcome,
308
308
  exitCode: telemetryOutcome.exitCode,
309
309
  errorCode: telemetryOutcome.errorCode,
310
+ errorOrigin: telemetryOutcome.errorOrigin,
311
+ timeoutSeconds: telemetryOutcome.timeoutSeconds,
310
312
  ...waitTimeoutTelemetry,
311
313
  durationMs: Date.now() - telemetryStartedAt,
312
314
  ...telemetryGlobals(),
@@ -468,11 +470,19 @@ catch (err) {
468
470
  }
469
471
  }
470
472
  else if (err instanceof CLIError) {
471
- output.error(err.message);
473
+ // Same 5-key envelope shape as the ApiError/InterruptError/
474
+ // RequestTimeoutError branches above — `err.code` defaults to the
475
+ // out-of-catalog 'CLI_ERROR' bucket for a plain CLIError (see errors.ts).
476
+ output.error({ code: err.code, message: err.message });
472
477
  await flushThenSetExitCode(err.exitCode);
473
478
  }
474
479
  else {
475
- output.error(err instanceof Error ? err.message : String(err));
480
+ // Genuinely uncaught, non-CLIError exception. Prefer a real Node error
481
+ // code (ENOENT, ECONNREFUSED, …) when one is present; otherwise fall
482
+ // back to the same 'UNCAUGHT_EXCEPTION' bucket classifyCliError() uses,
483
+ // so the JSON envelope's code and the telemetry errorCode always agree.
484
+ const message = err instanceof Error ? err.message : String(err);
485
+ output.error({ code: extractNodeErrorCode(err) ?? 'UNCAUGHT_EXCEPTION', message });
476
486
  await flushThenSetExitCode(1);
477
487
  }
478
488
  }
@@ -215,6 +215,7 @@ function resolveHttpClientOptions(opts, deps) {
215
215
  fetchImpl: deps.fetchImpl ?? createDryRunFetch(),
216
216
  onDebug: opts.debug ? (event) => stderr(formatDryRunDebug(event)) : undefined,
217
217
  onTransition: opts.verbose ? (msg) => stderr(`[verbose] ${msg}`) : undefined,
218
+ env,
218
219
  requestTimeoutMs,
219
220
  shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
220
221
  };
@@ -250,6 +251,7 @@ function resolveHttpClientOptions(opts, deps) {
250
251
  dryRun: opts.dryRun,
251
252
  stderr,
252
253
  }),
254
+ env,
253
255
  requestTimeoutMs,
254
256
  shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
255
257
  };
@@ -0,0 +1,13 @@
1
+ /** Env var a wrapper (e.g. the GitHub Action) sets to identify itself. */
2
+ export declare const CLIENT_TAG_ENV = "TESTSPRITE_CLIENT";
3
+ /**
4
+ * The validated client tag from `env`, or undefined when unset or invalid.
5
+ * Pure — reads only the one variable it owns.
6
+ */
7
+ export declare function resolveClientTag(env: NodeJS.ProcessEnv): string | undefined;
8
+ /**
9
+ * The User-Agent every outgoing request (API + telemetry beacon) sends.
10
+ * `testsprite-cli/<version>`, with ` (<client>)` appended only for a valid
11
+ * {@link CLIENT_TAG_ENV} value.
12
+ */
13
+ export declare function buildUserAgent(env?: NodeJS.ProcessEnv): string;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Optional "client" identity a wrapper can stamp onto every request the CLI
3
+ * makes on its behalf — the GitHub Action sets `TESTSPRITE_CLIENT=github-action/<ref>`
4
+ * so the backend can tell an Action-driven run from a developer's shell without
5
+ * a second credential or a new header.
6
+ *
7
+ * Wire shape: the User-Agent becomes `testsprite-cli/<version> (<client>)`.
8
+ * Without the env var (or with an invalid value) the UA is byte-identical to
9
+ * what it has always been, `testsprite-cli/<version>`.
10
+ *
11
+ * The value is validated against a tight grammar — `<name>/<version>` where the
12
+ * name is lowercase alphanumeric plus `-` (≤32 chars) and the version is a
13
+ * short token of `[0-9A-Za-z._+-]` (≤40 chars) — so a caller can never smuggle
14
+ * header-breaking characters (spaces, parentheses, CR/LF) or free text into a
15
+ * request header. An invalid value is dropped silently and NEVER echoed: the
16
+ * tag rides on telemetry too, and a rejected value must not leak back into a
17
+ * log line either.
18
+ */
19
+ import { VERSION } from '../version.js';
20
+ /** Env var a wrapper (e.g. the GitHub Action) sets to identify itself. */
21
+ export const CLIENT_TAG_ENV = 'TESTSPRITE_CLIENT';
22
+ /** `<name>/<version>`: e.g. `github-action/v1`, `github-action/1.2.0`. */
23
+ const CLIENT_TAG_RE = /^[a-z0-9][a-z0-9-]{0,31}\/[0-9A-Za-z][0-9A-Za-z._+-]{0,39}$/;
24
+ /**
25
+ * The validated client tag from `env`, or undefined when unset or invalid.
26
+ * Pure — reads only the one variable it owns.
27
+ */
28
+ export function resolveClientTag(env) {
29
+ const raw = env[CLIENT_TAG_ENV];
30
+ if (typeof raw !== 'string')
31
+ return undefined;
32
+ return CLIENT_TAG_RE.test(raw) ? raw : undefined;
33
+ }
34
+ /**
35
+ * The User-Agent every outgoing request (API + telemetry beacon) sends.
36
+ * `testsprite-cli/<version>`, with ` (<client>)` appended only for a valid
37
+ * {@link CLIENT_TAG_ENV} value.
38
+ */
39
+ export function buildUserAgent(env = process.env) {
40
+ const base = `testsprite-cli/${VERSION}`;
41
+ const client = resolveClientTag(env);
42
+ return client === undefined ? base : `${base} (${client})`;
43
+ }
44
+ //# sourceMappingURL=client-tag.js.map
@@ -6,10 +6,18 @@
6
6
  *
7
7
  * Absent ⇒ a legacy / pre-discriminator backend: treated as `in_flight` (the
8
8
  * historical rendering) for backward compatibility.
9
+ *
10
+ * `insufficient_credits` / `billing_hold` are billing refusals the backend folds
11
+ * into `conflicts[]` for a MIXED batch (some cases dispatched, some refused). A
12
+ * batch where nothing dispatched and every refusal was credits comes back as a
13
+ * plain 402 `INSUFFICIENT_CREDITS` envelope instead — the same shape the
14
+ * single-run route answers — so both surfaces exit 12.
9
15
  */
10
- export type ConflictReason = 'in_flight' | 'mcp_view_only' | 'local_address' | 'not_found' | 'error';
16
+ import { ApiError } from './errors.js';
17
+ export type ConflictReason = 'in_flight' | 'mcp_view_only' | 'local_address' | 'not_found' | 'insufficient_credits' | 'billing_hold' | 'error';
11
18
  /** A conflict entry on a run response. `message` carries actionable detail for
12
- * `local_address` / `error` (the backend env guard's nextAction). */
19
+ * `local_address` / `insufficient_credits` / `billing_hold` / `error` (the
20
+ * backend's nextAction). */
13
21
  export interface RunConflict {
14
22
  testId: string;
15
23
  currentRunId?: string;
@@ -28,3 +36,36 @@ export declare function describeConflict(c: RunConflict): string;
28
36
  * must stand in for the whole `conflicts[]` (exit-message / advisory).
29
37
  */
30
38
  export declare function summarizeConflicts(conflicts: readonly RunConflict[]): string;
39
+ /**
40
+ * The most frequent conflict reason in a batch (ties → the one seen first), as
41
+ * the raw wire string so a reason this CLI version does not know yet still
42
+ * surfaces. Undefined for an empty set. Feeds the telemetry `conflictReason`
43
+ * field, which allowlists the value before it is sent.
44
+ */
45
+ export declare function dominantConflictReason(conflicts: readonly RunConflict[]): string | undefined;
46
+ /**
47
+ * True when the set is non-empty and EVERY entry carries `reason`. Absent
48
+ * reasons never match (they are `in_flight` by the legacy rule above), so an old
49
+ * backend can never be read as "all insufficient credits".
50
+ */
51
+ export declare function everyConflictIs(conflicts: readonly RunConflict[], reason: ConflictReason): boolean;
52
+ /**
53
+ * True for the one batch shape that is really a credits refusal: nothing was
54
+ * dispatched, nothing is rate-deferred (that is exit 7 first), and every
55
+ * conflict says `insufficient_credits`. A newer backend answers this case with
56
+ * a plain 402 envelope itself; this covers a backend that still folds it into
57
+ * `conflicts[]`, so both wire shapes land on the same exit 12.
58
+ */
59
+ export declare function isAllCreditsRefusal(resp: {
60
+ accepted: readonly unknown[];
61
+ deferred: readonly unknown[];
62
+ conflicts: readonly RunConflict[];
63
+ }): boolean;
64
+ /**
65
+ * The exit-12 refusal for an all-credits batch — the SAME `INSUFFICIENT_CREDITS`
66
+ * envelope the single-run route answers (code, exit code, billing `nextAction`),
67
+ * so `index.ts` renders it identically and automation sees one shape. The
68
+ * server's own message (carried on the conflicts) is preferred over the local
69
+ * wording; `apiUrl` resolves the environment-correct portal link.
70
+ */
71
+ export declare function insufficientCreditsConflictError(conflicts: readonly RunConflict[], apiUrl?: string): ApiError;
@@ -1,3 +1,19 @@
1
+ /**
2
+ * Why a case landed in a run response's `conflicts[]` instead of dispatching.
3
+ * The backend (`batchRunFresh` / `dispatchTestListGroups`) tags each conflict so
4
+ * the CLI stops rendering every non-dispatch as "already in flight" — which is
5
+ * wrong for a view-only mirror, an un-runnable environment, or an unknown id.
6
+ *
7
+ * Absent ⇒ a legacy / pre-discriminator backend: treated as `in_flight` (the
8
+ * historical rendering) for backward compatibility.
9
+ *
10
+ * `insufficient_credits` / `billing_hold` are billing refusals the backend folds
11
+ * into `conflicts[]` for a MIXED batch (some cases dispatched, some refused). A
12
+ * batch where nothing dispatched and every refusal was credits comes back as a
13
+ * plain 402 `INSUFFICIENT_CREDITS` envelope instead — the same shape the
14
+ * single-run route answers — so both surfaces exit 12.
15
+ */
16
+ import { ApiError, insufficientCreditsNextAction } from './errors.js';
1
17
  /**
2
18
  * Short human label for a conflict's cause — the reason a case did NOT dispatch.
3
19
  * Absent reason renders as the legacy "already in flight" so an old backend's
@@ -11,6 +27,10 @@ export function describeConflict(c) {
11
27
  return c.message || 'environment not runnable (local/private/unresolvable URL)';
12
28
  case 'not_found':
13
29
  return 'not found in this workspace';
30
+ case 'insufficient_credits':
31
+ return c.message || 'insufficient credits';
32
+ case 'billing_hold':
33
+ return c.message || 'billing hold';
14
34
  case 'error':
15
35
  return c.message || 'dispatch failed';
16
36
  case 'in_flight':
@@ -18,28 +38,94 @@ export function describeConflict(c) {
18
38
  return c.currentRunId ? `already in flight (run ${c.currentRunId})` : 'already in flight';
19
39
  }
20
40
  }
41
+ const CONFLICT_LABELS = {
42
+ in_flight: 'already in flight',
43
+ mcp_view_only: 'view-only (MCP) project',
44
+ local_address: 'environment not runnable',
45
+ not_found: 'not found',
46
+ insufficient_credits: 'insufficient credits',
47
+ billing_hold: 'billing hold',
48
+ error: 'dispatch error',
49
+ };
50
+ /** Per-reason occurrence counts, insertion-ordered; absent reason ⇒ `in_flight`. */
51
+ function countByReason(conflicts) {
52
+ const counts = new Map();
53
+ for (const c of conflicts) {
54
+ const reason = c.reason ?? 'in_flight';
55
+ counts.set(reason, (counts.get(reason) ?? 0) + 1);
56
+ }
57
+ return counts;
58
+ }
21
59
  /**
22
60
  * One-line summary of a conflict set grouped by reason, e.g.
23
61
  * `2 already in flight, 1 environment not runnable`. Used where a single line
24
62
  * must stand in for the whole `conflicts[]` (exit-message / advisory).
25
63
  */
26
64
  export function summarizeConflicts(conflicts) {
27
- const labels = {
28
- in_flight: 'already in flight',
29
- mcp_view_only: 'view-only (MCP) project',
30
- local_address: 'environment not runnable',
31
- not_found: 'not found',
32
- error: 'dispatch error',
33
- };
34
- const counts = new Map();
35
- for (const c of conflicts) {
36
- const reason = c.reason ?? 'in_flight';
37
- counts.set(reason, (counts.get(reason) ?? 0) + 1);
38
- }
39
65
  // A future/unknown reason the loose wire schema admits (describeConflict covers
40
66
  // it via its default arm) must not render as "N undefined" here.
41
- return [...counts.entries()]
42
- .map(([reason, n]) => `${n} ${labels[reason] ?? 'not dispatched'}`)
67
+ return [...countByReason(conflicts).entries()]
68
+ .map(([reason, n]) => `${n} ${CONFLICT_LABELS[reason] ?? 'not dispatched'}`)
43
69
  .join(', ');
44
70
  }
71
+ /**
72
+ * The most frequent conflict reason in a batch (ties → the one seen first), as
73
+ * the raw wire string so a reason this CLI version does not know yet still
74
+ * surfaces. Undefined for an empty set. Feeds the telemetry `conflictReason`
75
+ * field, which allowlists the value before it is sent.
76
+ */
77
+ export function dominantConflictReason(conflicts) {
78
+ let best;
79
+ let bestCount = 0;
80
+ for (const [reason, n] of countByReason(conflicts)) {
81
+ if (n > bestCount) {
82
+ best = reason;
83
+ bestCount = n;
84
+ }
85
+ }
86
+ return best;
87
+ }
88
+ /**
89
+ * True when the set is non-empty and EVERY entry carries `reason`. Absent
90
+ * reasons never match (they are `in_flight` by the legacy rule above), so an old
91
+ * backend can never be read as "all insufficient credits".
92
+ */
93
+ export function everyConflictIs(conflicts, reason) {
94
+ return conflicts.length > 0 && conflicts.every(c => c.reason === reason);
95
+ }
96
+ /**
97
+ * True for the one batch shape that is really a credits refusal: nothing was
98
+ * dispatched, nothing is rate-deferred (that is exit 7 first), and every
99
+ * conflict says `insufficient_credits`. A newer backend answers this case with
100
+ * a plain 402 envelope itself; this covers a backend that still folds it into
101
+ * `conflicts[]`, so both wire shapes land on the same exit 12.
102
+ */
103
+ export function isAllCreditsRefusal(resp) {
104
+ return (resp.accepted.length === 0 &&
105
+ resp.deferred.length === 0 &&
106
+ everyConflictIs(resp.conflicts, 'insufficient_credits'));
107
+ }
108
+ /**
109
+ * The exit-12 refusal for an all-credits batch — the SAME `INSUFFICIENT_CREDITS`
110
+ * envelope the single-run route answers (code, exit code, billing `nextAction`),
111
+ * so `index.ts` renders it identically and automation sees one shape. The
112
+ * server's own message (carried on the conflicts) is preferred over the local
113
+ * wording; `apiUrl` resolves the environment-correct portal link.
114
+ */
115
+ export function insufficientCreditsConflictError(conflicts, apiUrl) {
116
+ const serverMessage = conflicts
117
+ .map(c => c.message?.trim())
118
+ .find((m) => m !== undefined && m !== '');
119
+ const n = conflicts.length;
120
+ return ApiError.fromEnvelope({
121
+ error: {
122
+ code: 'INSUFFICIENT_CREDITS',
123
+ message: serverMessage ??
124
+ `Insufficient credits — nothing was queued (${n} test${n !== 1 ? 's' : ''} refused).`,
125
+ nextAction: insufficientCreditsNextAction(apiUrl),
126
+ requestId: 'local',
127
+ details: { reason: 'insufficient_credits', conflicts: conflicts.map(c => c.testId) },
128
+ },
129
+ });
130
+ }
45
131
  //# sourceMappingURL=conflict-reason.js.map
package/dist/lib/cron.js CHANGED
@@ -133,9 +133,16 @@ export function describeCron(cron) {
133
133
  const f = fields(cron);
134
134
  if (f.length !== FIELD_COUNT)
135
135
  return cron.trim();
136
- const [minute, hour, dayOfMonth, , dayOfWeek] = f;
136
+ const [minute, hour, dayOfMonth, month, dayOfWeek] = f;
137
137
  if (!isPinned(minute) || !isPinned(hour))
138
138
  return cron.trim();
139
+ // A restricted month makes every phrasing below wrong, because none of them
140
+ // can say "except in the months this cron skips": `0 3 * 6 *` is not "daily
141
+ // at 03:00", it is daily *during June*. runsPerMonth already divides by the
142
+ // month count, so describing it as daily contradicts the frequency printed
143
+ // beside it in the same sentence.
144
+ if (!isWildcard(month))
145
+ return cron.trim();
139
146
  const at = `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`;
140
147
  if (isWildcard(dayOfMonth) && isWildcard(dayOfWeek))
141
148
  return `daily at ${at}`;
@@ -22,8 +22,34 @@ export declare function exitCodeFor(code: ErrorCode): number;
22
22
  export declare function isAuthCode(code: string): boolean;
23
23
  export declare class CLIError extends Error {
24
24
  readonly exitCode: number;
25
- constructor(message: string, exitCode?: number);
25
+ /**
26
+ * Stable machine error code — mirrored into telemetry's `errorCode` field
27
+ * and into the `--output json` error envelope (`{error:{code,...}}`).
28
+ * Defaults to the generic, deliberately out-of-catalog `'CLI_ERROR'`
29
+ * bucket for a plain `CLIError` (same convention as `InterruptError`'s
30
+ * `'INTERRUPTED'` and `RequestTimeoutError`'s `'REQUEST_TIMEOUT'` below —
31
+ * none of these are backend-issued codes, so they don't belong in
32
+ * `ERROR_CODES`). `ApiError` overrides this with the real catalog
33
+ * `ErrorCode` parsed from the server envelope.
34
+ *
35
+ * Before this field existed, `classifyCliError()`'s plain-`CLIError`
36
+ * fallback branch had nothing to report and telemetry events landed with
37
+ * `errorCode=None` — the same silent gap the final uncaught-exception
38
+ * branch had.
39
+ */
40
+ readonly code: string;
41
+ constructor(message: string, exitCode?: number, code?: string);
26
42
  }
43
+ /**
44
+ * Best-effort extraction of a `.code` string off an arbitrary thrown value —
45
+ * covers Node built-in errors (`ENOENT`, `ECONNREFUSED`, …) that reach the
46
+ * top-level catch without ever being wrapped in a `CLIError`. Used by the
47
+ * genuinely-uncaught-exception fallback in both `classifyCliError()` and
48
+ * `index.ts`'s final catch branch, so a filesystem/network error reports its
49
+ * real code instead of falling into the generic `'UNCAUGHT_EXCEPTION'`
50
+ * bucket.
51
+ */
52
+ export declare function extractNodeErrorCode(err: unknown): string | undefined;
27
53
  /**
28
54
  * Termination signals with graceful handling, mapped to their conventional
29
55
  * `128 + signum` exit code. sourceRef: POSIX signal numbers (SIGHUP=1,
@@ -157,3 +183,20 @@ export declare class RequestTimeoutError extends CLIError {
157
183
  readonly timeoutMs: number;
158
184
  constructor(timeoutMs: number, requestId?: string);
159
185
  }
186
+ /**
187
+ * The synthesized `nextAction` for an INSUFFICIENT_CREDITS refusal when the
188
+ * backend supplied none (older backends; the CLI's own all-credits batch
189
+ * refusal). Portal links resolve per environment from the API endpoint (dev and
190
+ * prod portals live on different domains); an unknown host gets the route only —
191
+ * a hardcoded domain would point at the wrong environment.
192
+ *
193
+ * V3 API keys are membership-bound: a key minted for a team org spends THAT
194
+ * org's wallet, not the holder's personal one, and there is no request-scoped
195
+ * signal at this layer to tell which kind of key just failed. So the hint
196
+ * deliberately does NOT assert "top up your (personal) credits" as the only
197
+ * path — it offers the personal-key link (still correct for the common case)
198
+ * alongside an honest org-bound alternative, rather than guessing. The
199
+ * `testsprite usage` pointer is the CLI-native way to check the balance before
200
+ * a large run fan-out.
201
+ */
202
+ export declare function insufficientCreditsNextAction(apiUrl?: string): string;
@@ -115,12 +115,44 @@ export function isAuthCode(code) {
115
115
  }
116
116
  export class CLIError extends Error {
117
117
  exitCode;
118
- constructor(message, exitCode = 1) {
118
+ /**
119
+ * Stable machine error code — mirrored into telemetry's `errorCode` field
120
+ * and into the `--output json` error envelope (`{error:{code,...}}`).
121
+ * Defaults to the generic, deliberately out-of-catalog `'CLI_ERROR'`
122
+ * bucket for a plain `CLIError` (same convention as `InterruptError`'s
123
+ * `'INTERRUPTED'` and `RequestTimeoutError`'s `'REQUEST_TIMEOUT'` below —
124
+ * none of these are backend-issued codes, so they don't belong in
125
+ * `ERROR_CODES`). `ApiError` overrides this with the real catalog
126
+ * `ErrorCode` parsed from the server envelope.
127
+ *
128
+ * Before this field existed, `classifyCliError()`'s plain-`CLIError`
129
+ * fallback branch had nothing to report and telemetry events landed with
130
+ * `errorCode=None` — the same silent gap the final uncaught-exception
131
+ * branch had.
132
+ */
133
+ code;
134
+ constructor(message, exitCode = 1, code = 'CLI_ERROR') {
119
135
  super(message);
120
136
  this.name = 'CLIError';
121
137
  this.exitCode = exitCode;
138
+ this.code = code;
122
139
  }
123
140
  }
141
+ /**
142
+ * Best-effort extraction of a `.code` string off an arbitrary thrown value —
143
+ * covers Node built-in errors (`ENOENT`, `ECONNREFUSED`, …) that reach the
144
+ * top-level catch without ever being wrapped in a `CLIError`. Used by the
145
+ * genuinely-uncaught-exception fallback in both `classifyCliError()` and
146
+ * `index.ts`'s final catch branch, so a filesystem/network error reports its
147
+ * real code instead of falling into the generic `'UNCAUGHT_EXCEPTION'`
148
+ * bucket.
149
+ */
150
+ export function extractNodeErrorCode(err) {
151
+ if (typeof err !== 'object' || err === null || !('code' in err))
152
+ return undefined;
153
+ const code = err.code;
154
+ return typeof code === 'string' && code.length > 0 ? code : undefined;
155
+ }
124
156
  /**
125
157
  * Termination signals with graceful handling, mapped to their conventional
126
158
  * `128 + signum` exit code. sourceRef: POSIX signal numbers (SIGHUP=1,
@@ -146,14 +178,14 @@ export const TERMINATION_EXIT_CODES = {
146
178
  export class InterruptError extends CLIError {
147
179
  signal;
148
180
  constructor(signal) {
149
- super(`Interrupted by ${signal}.`, TERMINATION_EXIT_CODES[signal]);
181
+ super(`Interrupted by ${signal}.`, TERMINATION_EXIT_CODES[signal], 'INTERRUPTED');
150
182
  this.name = 'InterruptError';
151
183
  this.signal = signal;
152
184
  }
153
185
  }
154
186
  export class NotImplementedError extends CLIError {
155
187
  constructor(commandPath) {
156
- super(`Command not yet implemented: ${commandPath}`, 2);
188
+ super(`Command not yet implemented: ${commandPath}`, 2, 'NOT_IMPLEMENTED');
157
189
  this.name = 'NotImplementedError';
158
190
  }
159
191
  }
@@ -165,6 +197,15 @@ export class NotImplementedError extends CLIError {
165
197
  * wording across paths).
166
198
  */
167
199
  export class ApiError extends CLIError {
200
+ // `override`: CLIError now declares its own `code: string` (defaulting
201
+ // 'CLI_ERROR'), so `noImplicitOverride` requires this modifier on the
202
+ // narrowed redeclaration. Under useDefineForClassFields (the default at
203
+ // this tsconfig's ES2022 target) this field IS re-initialized to
204
+ // `undefined` right after `super(...)` returns — but the constructor body
205
+ // below unconditionally reassigns `this.code = envelope.code` afterward,
206
+ // so the final value is always the envelope's code, never the CLIError
207
+ // base default. See the pinned regression test in errors.test.ts
208
+ // ("ApiError.code overrides the CLIError base default").
168
209
  code;
169
210
  requestId;
170
211
  nextAction;
@@ -306,7 +347,7 @@ export class RequestTimeoutError extends CLIError {
306
347
  constructor(timeoutMs, requestId = 'local') {
307
348
  const timeoutSec = Math.round(timeoutMs / 1000);
308
349
  super(`Request timed out after ${timeoutSec}s (client-side). ` +
309
- `Use --request-timeout <seconds> or TESTSPRITE_REQUEST_TIMEOUT_MS to extend the deadline.`, 7);
350
+ `Use --request-timeout <seconds> or TESTSPRITE_REQUEST_TIMEOUT_MS to extend the deadline.`, 7, 'REQUEST_TIMEOUT');
310
351
  this.name = 'RequestTimeoutError';
311
352
  this.requestId = requestId;
312
353
  this.timeoutMs = timeoutMs;
@@ -372,6 +413,29 @@ function isInsufficientCredits(rawCode, message, details) {
372
413
  const hasCreditsMessage = /insufficient credits/i.test(message);
373
414
  return hasRequiredField || hasCreditsMessage;
374
415
  }
416
+ /**
417
+ * The synthesized `nextAction` for an INSUFFICIENT_CREDITS refusal when the
418
+ * backend supplied none (older backends; the CLI's own all-credits batch
419
+ * refusal). Portal links resolve per environment from the API endpoint (dev and
420
+ * prod portals live on different domains); an unknown host gets the route only —
421
+ * a hardcoded domain would point at the wrong environment.
422
+ *
423
+ * V3 API keys are membership-bound: a key minted for a team org spends THAT
424
+ * org's wallet, not the holder's personal one, and there is no request-scoped
425
+ * signal at this layer to tell which kind of key just failed. So the hint
426
+ * deliberately does NOT assert "top up your (personal) credits" as the only
427
+ * path — it offers the personal-key link (still correct for the common case)
428
+ * alongside an honest org-bound alternative, rather than guessing. The
429
+ * `testsprite usage` pointer is the CLI-native way to check the balance before
430
+ * a large run fan-out.
431
+ */
432
+ export function insufficientCreditsNextAction(apiUrl) {
433
+ const portalBase = apiUrl === undefined ? undefined : resolvePortalBase(apiUrl);
434
+ return ((portalBase !== undefined
435
+ ? `Top up credits at ${portalBase}/dashboard/settings/billing (personal keys) — ask an org admin if this key is organization-bound — or upgrade your plan at ${portalBase}/pricing.`
436
+ : 'Top up credits on the portal Billing page (/dashboard/settings/billing) if this is a personal key — ask an org admin if it is organization-bound — or upgrade your plan (/pricing).') +
437
+ ' Run `testsprite usage` to check your current balance before the next run.');
438
+ }
375
439
  /**
376
440
  * Detect the "ambiguous org" sub-case of a CONFLICT (409) envelope: a
377
441
  * membership-key caller's testId resolved to projects in more than one of
@@ -450,17 +514,10 @@ function parseEnvelopeBody(raw, httpStatus, apiUrl) {
450
514
  // (personal) credits" as the only path — it offers the personal-key
451
515
  // link (still correct for the common case) alongside an honest
452
516
  // org-bound alternative, rather than guessing.
453
- const portalBase = apiUrl === undefined ? undefined : resolvePortalBase(apiUrl);
454
- const billingNextAction = nextAction !== ''
455
- ? nextAction
456
- : (portalBase !== undefined
457
- ? `Top up credits at ${portalBase}/dashboard/settings/billing (personal keys) — ask an org admin if this key is organization-bound — or upgrade your plan at ${portalBase}/pricing.`
458
- : 'Top up credits on the portal Billing page (/dashboard/settings/billing) if this is a personal key — ask an org admin if it is organization-bound — or upgrade your plan (/pricing).') +
459
- ' Run `testsprite usage` to check your current balance before the next run.';
460
517
  return {
461
518
  code: 'INSUFFICIENT_CREDITS',
462
519
  message,
463
- nextAction: billingNextAction,
520
+ nextAction: nextAction !== '' ? nextAction : insufficientCreditsNextAction(apiUrl),
464
521
  requestId,
465
522
  details,
466
523
  };