@testsprite/testsprite-cli 0.11.0 → 0.13.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 (99) hide show
  1. package/README.md +52 -44
  2. package/dist/commands/agent.js +16 -13
  3. package/dist/commands/auth.d.ts +19 -0
  4. package/dist/commands/auth.js +60 -24
  5. package/dist/commands/ci.d.ts +86 -1
  6. package/dist/commands/ci.js +470 -9
  7. package/dist/commands/doctor.d.ts +2 -0
  8. package/dist/commands/doctor.js +22 -9
  9. package/dist/commands/init.js +14 -11
  10. package/dist/commands/project-env.d.ts +90 -0
  11. package/dist/commands/project-env.js +486 -0
  12. package/dist/commands/project.d.ts +15 -5
  13. package/dist/commands/project.js +88 -92
  14. package/dist/commands/schedule.d.ts +2 -0
  15. package/dist/commands/schedule.js +18 -10
  16. package/dist/commands/test.d.ts +102 -30
  17. package/dist/commands/test.js +1949 -419
  18. package/dist/commands/testlist.js +77 -21
  19. package/dist/commands/tunnel.d.ts +26 -3
  20. package/dist/commands/tunnel.js +211 -14
  21. package/dist/commands/usage.d.ts +3 -0
  22. package/dist/commands/usage.js +12 -5
  23. package/dist/index.js +47 -23
  24. package/dist/lib/agent-targets.d.ts +3 -3
  25. package/dist/lib/agent-targets.js +2 -2
  26. package/dist/lib/billing-refusal.d.ts +43 -0
  27. package/dist/lib/billing-refusal.js +171 -0
  28. package/dist/lib/bundle.d.ts +5 -0
  29. package/dist/lib/bundle.js +43 -13
  30. package/dist/lib/ci-linkage.d.ts +90 -0
  31. package/dist/lib/ci-linkage.js +181 -0
  32. package/dist/lib/client-factory.d.ts +4 -1
  33. package/dist/lib/client-factory.js +25 -2
  34. package/dist/lib/client-tag.d.ts +13 -0
  35. package/dist/lib/client-tag.js +44 -0
  36. package/dist/lib/config.d.ts +17 -0
  37. package/dist/lib/config.js +20 -1
  38. package/dist/lib/conflict-reason.d.ts +67 -2
  39. package/dist/lib/conflict-reason.js +148 -13
  40. package/dist/lib/credentials.js +56 -14
  41. package/dist/lib/cron.js +8 -1
  42. package/dist/lib/dry-run/samples.d.ts +13 -1
  43. package/dist/lib/dry-run/samples.js +51 -7
  44. package/dist/lib/errors.d.ts +62 -12
  45. package/dist/lib/errors.js +180 -25
  46. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  47. package/dist/lib/failing-fe-resolver.js +3 -3
  48. package/dist/lib/gh-output.d.ts +26 -11
  49. package/dist/lib/gh-output.js +47 -15
  50. package/dist/lib/history-retention.d.ts +8 -0
  51. package/dist/lib/history-retention.js +24 -0
  52. package/dist/lib/http.d.ts +44 -19
  53. package/dist/lib/http.js +53 -26
  54. package/dist/lib/interrupt.d.ts +21 -13
  55. package/dist/lib/interrupt.js +32 -21
  56. package/dist/lib/junit-report.d.ts +11 -1
  57. package/dist/lib/junit-report.js +15 -3
  58. package/dist/lib/local-target.d.ts +33 -1
  59. package/dist/lib/local-target.js +78 -1
  60. package/dist/lib/output.d.ts +27 -1
  61. package/dist/lib/output.js +22 -3
  62. package/dist/lib/plan-poll.d.ts +11 -11
  63. package/dist/lib/plan-poll.js +12 -12
  64. package/dist/lib/plans.types.d.ts +9 -9
  65. package/dist/lib/plans.types.js +3 -3
  66. package/dist/lib/poll.d.ts +2 -2
  67. package/dist/lib/poll.js +9 -3
  68. package/dist/lib/render-error.d.ts +2 -0
  69. package/dist/lib/render-error.js +13 -0
  70. package/dist/lib/response-schemas.d.ts +54 -12
  71. package/dist/lib/response-schemas.js +106 -7
  72. package/dist/lib/runs.types.d.ts +92 -6
  73. package/dist/lib/secret-file.js +72 -14
  74. package/dist/lib/skill-nudge.d.ts +6 -1
  75. package/dist/lib/skill-nudge.js +32 -5
  76. package/dist/lib/target-url-preflight.d.ts +6 -4
  77. package/dist/lib/target-url-preflight.js +64 -51
  78. package/dist/lib/target-url.js +31 -12
  79. package/dist/lib/telemetry.d.ts +172 -3
  80. package/dist/lib/telemetry.js +276 -15
  81. package/dist/lib/ticker.js +93 -4
  82. package/dist/lib/tunnel-session.d.ts +13 -0
  83. package/dist/lib/tunnel-session.js +4 -1
  84. package/dist/lib/tunnel.types.d.ts +12 -2
  85. package/dist/lib/tunnel.types.js +2 -2
  86. package/dist/lib/version-notice.d.ts +20 -1
  87. package/dist/lib/version-notice.js +59 -12
  88. package/dist/lib/wait-exit.d.ts +8 -0
  89. package/dist/lib/wait-exit.js +76 -4
  90. package/dist/lib/workspace-status.d.ts +23 -0
  91. package/dist/lib/workspace-status.js +15 -0
  92. package/dist/version-guard.d.ts +7 -1
  93. package/dist/version-guard.js +19 -1
  94. package/dist/version.d.ts +1 -1
  95. package/dist/version.js +1 -1
  96. package/package.json +4 -4
  97. package/skills/testsprite-onboard.skill.md +4 -4
  98. package/skills/testsprite-verify.codex.md +59 -57
  99. package/skills/testsprite-verify.skill.md +53 -36
@@ -11,11 +11,13 @@
11
11
  * has no server-side source at all today).
12
12
  */
13
13
  import { Command } from 'commander';
14
+ import { formatWorkspaceStatus } from '../lib/workspace-status.js';
14
15
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
15
- import { loadConfig } from '../lib/config.js';
16
+ import { loadConfig, resolveProfileName } from '../lib/config.js';
16
17
  import { resolvePortalBase } from '../lib/facade.js';
17
18
  import { formatOrgBinding, formatOrgsSummary } from '../lib/org-render.js';
18
19
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
20
+ import { USAGE_RESPONSE_SCHEMA } from '../lib/response-schemas.js';
19
21
  /** Dry-run canned response — matches what the real /me + User lookup would return. */
20
22
  export const DRY_RUN_USAGE_SAMPLE = {
21
23
  userId: '11111111-1111-4111-8111-111111111111',
@@ -72,7 +74,7 @@ export async function runUsage(opts, deps = {}) {
72
74
  // /me is the only available source of credits/plan today. If the backend
73
75
  // adds a dedicated /usage endpoint later, this single get call is where
74
76
  // it would be swapped in — no other code change needed in the CLI.
75
- const me = await client.get('/me');
77
+ const me = await client.get('/me', { schema: USAGE_RESPONSE_SCHEMA });
76
78
  out.print(me, data => renderUsage(data, portalBase));
77
79
  // In text mode, emit a note when NO balance was shown at all — neither the
78
80
  // legacy per-user `credits` nor an org wallet. A V3-routed org account can
@@ -146,6 +148,11 @@ function renderUsage(u, portalBase) {
146
148
  lines.push('--- organization ---');
147
149
  lines.push(`org: ${org.name} (${org.role})`);
148
150
  lines.push(`plan: ${org.plan}`);
151
+ // A paused workspace cannot spend this balance at all; a payment-pending
152
+ // one keeps spending but gets no refill. Both are worth a line here.
153
+ const standing = formatWorkspaceStatus(org.workspace);
154
+ if (standing)
155
+ lines.push(`state: ${standing}`);
149
156
  // Labeled `balance:` (not `credits:`) — `--output json` exposes the
150
157
  // legacy per-user number under `.credits`, and giving the org wallet the
151
158
  // same label in text mode would make one word mean two different values.
@@ -250,14 +257,14 @@ export function createUsageCommand(deps = {}) {
250
257
  ' organization billing settings (ask an org admin) if this key is\n' +
251
258
  ' organization-bound.')
252
259
  .action(async (_cmdOpts, command) => {
253
- await runUsage(resolveCommonOptions(command), deps);
260
+ await runUsage(resolveCommonOptions(command, deps.env), deps);
254
261
  });
255
262
  return cmd;
256
263
  }
257
- function resolveCommonOptions(command) {
264
+ function resolveCommonOptions(command, env) {
258
265
  const globals = command.optsWithGlobals();
259
266
  return {
260
- profile: globals.profile ?? 'default',
267
+ profile: resolveProfileName(globals.profile, env),
261
268
  output: resolveOutputMode(globals.output),
262
269
  endpointUrl: globals.endpointUrl,
263
270
  debug: globals.debug ?? false,
package/dist/index.js CHANGED
@@ -12,23 +12,22 @@ import { createTunnelCommand } from './commands/tunnel.js';
12
12
  import { createTestCommand } from './commands/test.js';
13
13
  import { createTestListCommand } from './commands/testlist.js';
14
14
  import { createUsageCommand } from './commands/usage.js';
15
+ import { resolveProfileName } from './lib/config.js';
16
+ import { classifyBillingRefusal } from './lib/billing-refusal.js';
15
17
  import { TARGETS } from './lib/agent-targets.js';
16
- import { ApiError, CLIError, InterruptError, RequestTimeoutError } from './lib/errors.js';
17
- import { installBrokenPipeGuard, installSignalHandlers } from './lib/interrupt.js';
18
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, extractNodeErrorCode, } from './lib/errors.js';
19
+ import { armInterruptExitBackstop, installBrokenPipeGuard, installSignalHandlers, } from './lib/interrupt.js';
18
20
  import { Output, isOutputMode } from './lib/output.js';
19
21
  import { maybeInstallProxyAgent } from './lib/proxy.js';
20
- import { renderAmbiguousOrgCandidates, renderCommanderError, rephraseUnknownOption, } from './lib/render-error.js';
22
+ import { renderAmbiguousOrgCandidates, renderTunnelBindingLimitIds, renderCommanderError, rephraseUnknownOption, } from './lib/render-error.js';
21
23
  import { isPlanTemplateInvocation, maybeEmitSkillNudge } from './lib/skill-nudge.js';
22
24
  import { classifyCliError, isTelemetryOptedOut, recordOutcome, resolveTelemetryAuth, } from './lib/telemetry.js';
23
25
  import { maybeNotifyUpdate } from './lib/update-check.js';
24
26
  import { VERSION } from './version.js';
25
- import { SUPPORTED_NODE_RANGE, shouldRejectNodeVersion } from './version-guard.js';
27
+ import { rejectUnsupportedNodeVersion } from './version-guard.js';
26
28
  // Guard: exit early with a clear message on unsupported Node.js versions,
27
29
  // rather than failing later with a cryptic ESM/runtime error.
28
- if (shouldRejectNodeVersion(process.versions.node)) {
29
- process.stderr.write(`Error: testsprite requires Node.js ${SUPPORTED_NODE_RANGE} (found ${process.versions.node}).\nInstall a supported Node.js release from https://nodejs.org\n`);
30
- process.exit(1);
31
- }
30
+ rejectUnsupportedNodeVersion(process.versions.node);
32
31
  const program = new Command();
33
32
  // exitOverride() causes Commander to throw CommanderError instead of calling
34
33
  // process.exit() directly, giving our catch block a chance to remap error
@@ -231,9 +230,10 @@ program.hook('preAction', (_thisCommand, actionCommand) => {
231
230
  commandPath,
232
231
  output: isOutputMode(globals.output) ? globals.output : 'text',
233
232
  dryRun: globals.dryRun ?? false,
234
- profile: globals.profile ?? 'default',
233
+ profile: resolveProfileName(globals.profile),
235
234
  cwd: process.cwd(),
236
235
  env: process.env,
236
+ debug: globals.debug ?? false,
237
237
  });
238
238
  }
239
239
  // Best-effort update notice (see lib/update-check.ts): self-gates on the
@@ -251,12 +251,12 @@ program.hook('preAction', (_thisCommand, actionCommand) => {
251
251
  void maybeNotifyUpdate();
252
252
  }
253
253
  });
254
- // Clean process lifecycle (DEV-331 piece 1, errors.md §8.1): during a `--wait`
254
+ // Clean process lifecycle (errors.md §8.1): during a `--wait`
255
255
  // poll the scope is armed — the first SIGINT/SIGTERM/SIGHUP aborts gracefully
256
256
  // and the wait path prints an honest partial (the run KEEPS executing and
257
257
  // billing server-side) + re-attach hint before exiting 128+signum; a second
258
- // signal hard-exits. Outside an armed scope: a clear one-line message +
259
- // immediate exit (instead of Node's silent abrupt kill). Plus an EPIPE guard
258
+ // signal hard-exits. Outside an armed scope: a clear one-line message, then
259
+ // drain an in-flight request or exit immediately when idle. Plus an EPIPE guard
260
260
  // so piping to a reader that closes early (`| head`) exits cleanly instead of
261
261
  // dumping a raw `write EPIPE` stack.
262
262
  installSignalHandlers();
@@ -292,7 +292,7 @@ catch (err) {
292
292
  // user's error. The classification mirrors the exit-code mapping the
293
293
  // branches apply.
294
294
  //
295
- // DEV-673: SET `process.exitCode` and let the event loop drain instead of
295
+ // SET `process.exitCode` and let the event loop drain instead of
296
296
  // forcing `process.exit()`. A forced exit tears the process down while the
297
297
  // just-completed HTTPS request's TLS socket is still mid-close; on Windows
298
298
  // libuv asserts on the half-closed handle (src/win/async.c) and the process
@@ -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(),
@@ -319,6 +321,7 @@ catch (err) {
319
321
  const mode = isOutputMode(rawMode) ? rawMode : 'text';
320
322
  const output = new Output(mode);
321
323
  if (err instanceof ApiError) {
324
+ const billingRefusal = classifyBillingRefusal(err);
322
325
  const message = err.code === 'UNSUPPORTED' &&
323
326
  err.getDetail('reason') === 'tunnel-unsupported-for-backend-test'
324
327
  ? '--local only supports frontend tests today. Re-run without --local, or point the test at a reachable base URL.'
@@ -331,6 +334,7 @@ catch (err) {
331
334
  nextAction: err.nextAction,
332
335
  requestId: err.requestId,
333
336
  details: err.details,
337
+ ...(billingRefusal ? { links: billingRefusal.links } : {}),
334
338
  },
335
339
  };
336
340
  process.stderr.write(`${JSON.stringify(envelope, null, 2)}\n`);
@@ -339,6 +343,10 @@ catch (err) {
339
343
  process.stderr.write(`Error: ${message}\n`);
340
344
  if (err.nextAction)
341
345
  process.stderr.write(`${err.nextAction}\n`);
346
+ if (billingRefusal) {
347
+ for (const line of billingRefusal.lines)
348
+ process.stderr.write(`${line}\n`);
349
+ }
342
350
  if (err.requestId && err.requestId !== 'local')
343
351
  process.stderr.write(`requestId: ${err.requestId}\n`);
344
352
  // C1: surface requiredScopes / grantedScopes on AUTH_FORBIDDEN
@@ -370,14 +378,18 @@ catch (err) {
370
378
  process.stderr.write(`${line}\n`);
371
379
  }
372
380
  }
381
+ if (err.code === 'RATE_LIMITED' && err.getDetail('reason') === 'tunnel_binding_limit') {
382
+ for (const line of renderTunnelBindingLimitIds(err.getDetail('clientIds'))) {
383
+ process.stderr.write(`${line}\n`);
384
+ }
385
+ }
373
386
  }
374
387
  await flushThenSetExitCode(err.exitCode);
375
388
  }
376
389
  else if (err instanceof InterruptError) {
377
- // Graceful detach (DEV-331 piece 1, errors.md §8.1): the wait-path catch
378
- // block already printed the honest partial + re-attach hint. Exit with
379
- // the conventional 128+signum code; `INTERRUPTED` is deliberately outside
380
- // the error catalog. Note: Ctrl-C does NOT cancel the server-side run.
390
+ // A run wait may already have printed a partial result and re-attach hint.
391
+ // A disarmed request has no run ID, so its JSON hint describes checking
392
+ // current state before retrying. Both use the conventional 128+signum code.
381
393
  if (mode === 'json') {
382
394
  const tunnelDetach = err
383
395
  .tunnelDetach;
@@ -386,9 +398,12 @@ catch (err) {
386
398
  code: 'INTERRUPTED',
387
399
  message: err.message,
388
400
  nextAction: tunnelDetach?.nextAction ??
389
- 'The server-side run (if any) keeps executing and billing. ' +
390
- 'Re-attach with: testsprite test wait <runId>, or stop it with: testsprite test cancel <runId> ' +
391
- '(runId is in the partial JSON on stdout).',
401
+ (err.runWaitContext
402
+ ? 'The server-side run (if any) keeps executing and billing. ' +
403
+ 'Re-attach with: testsprite test wait <runId>, or stop it with: testsprite test cancel <runId> ' +
404
+ '(runId is in the partial JSON on stdout).'
405
+ : 'The request was interrupted. Check the current state before retrying; ' +
406
+ 'a multi-item command may have processed some items.'),
392
407
  requestId: 'local',
393
408
  details: {
394
409
  signal: err.signal,
@@ -404,6 +419,7 @@ catch (err) {
404
419
  process.stderr.write(`Error: ${err.message}\n`);
405
420
  }
406
421
  await flushThenSetExitCode(err.exitCode);
422
+ armInterruptExitBackstop(err.exitCode);
407
423
  }
408
424
  else if (err instanceof RequestTimeoutError) {
409
425
  // Structured rendering for per-request timeouts: JSON mode emits a
@@ -439,7 +455,7 @@ catch (err) {
439
455
  // help`, `help test`, etc.)
440
456
  // Both are user-initiated "show me help" requests and must exit 0 per the
441
457
  // AWS-CLI convention. Failing to map 'commander.help' caused these paths
442
- // to fall through to the generic `process.exit(5)` branch (dogfood P1-4).
458
+ // to fall through to the generic `process.exit(5)` branch.
443
459
  if (err.code === 'commander.helpDisplayed' ||
444
460
  err.code === 'commander.help' ||
445
461
  err.code === 'commander.version') {
@@ -468,11 +484,19 @@ catch (err) {
468
484
  }
469
485
  }
470
486
  else if (err instanceof CLIError) {
471
- output.error(err.message);
487
+ // Same 5-key envelope shape as the ApiError/InterruptError/
488
+ // RequestTimeoutError branches above — `err.code` defaults to the
489
+ // out-of-catalog 'CLI_ERROR' bucket for a plain CLIError (see errors.ts).
490
+ output.error({ code: err.code, message: err.message });
472
491
  await flushThenSetExitCode(err.exitCode);
473
492
  }
474
493
  else {
475
- output.error(err instanceof Error ? err.message : String(err));
494
+ // Genuinely uncaught, non-CLIError exception. Prefer a real Node error
495
+ // code (ENOENT, ECONNREFUSED, …) when one is present; otherwise fall
496
+ // back to the same 'UNCAUGHT_EXCEPTION' bucket classifyCliError() uses,
497
+ // so the JSON envelope's code and the telemetry errorCode always agree.
498
+ const message = err instanceof Error ? err.message : String(err);
499
+ output.error({ code: extractNodeErrorCode(err) ?? 'UNCAUGHT_EXCEPTION', message });
476
500
  await flushThenSetExitCode(1);
477
501
  }
478
502
  }
@@ -21,7 +21,7 @@ export interface TargetSpec {
21
21
  * truncated beyond) and `copilot` (no cap, but `applyTo: '**'` injects it into
22
22
  * every request, so context cost is the constraint).
23
23
  *
24
- * Read it via {@link ownFileBodyFor}, never by testing target names (DEV-672).
24
+ * Read it via {@link ownFileBodyFor}, never by testing target names.
25
25
  */
26
26
  compactBody?: boolean;
27
27
  /**
@@ -153,8 +153,8 @@ export declare function compactBodyFor(skill: string, read?: ReadFn): string;
153
153
  /**
154
154
  * The canonical own-file body for a (target, skill) pair, and therefore the body
155
155
  * the install marker's hash covers. Every producer AND consumer of an own-file
156
- * body must resolve through here — install and status keeping separate copies of
157
- * this rule is what caused DEV-672.
156
+ * body must resolve through here — keeping separate copies of this rule is
157
+ * what lets install and status disagree on the same file.
158
158
  */
159
159
  export declare function ownFileBodyFor(target: AgentTarget, skill: string, read?: ReadFn): string;
160
160
  /**
@@ -287,8 +287,8 @@ export function compactBodyFor(skill, read = defaultRead) {
287
287
  /**
288
288
  * The canonical own-file body for a (target, skill) pair, and therefore the body
289
289
  * the install marker's hash covers. Every producer AND consumer of an own-file
290
- * body must resolve through here — install and status keeping separate copies of
291
- * this rule is what caused DEV-672.
290
+ * body must resolve through here — keeping separate copies of this rule is
291
+ * what lets install and status disagree on the same file.
292
292
  */
293
293
  export function ownFileBodyFor(target, skill, read = defaultRead) {
294
294
  return TARGETS[target].compactBody ? compactBodyFor(skill, read) : loadSkillBodyFor(skill, read);
@@ -0,0 +1,43 @@
1
+ import type { ApiError } from './errors.js';
2
+ /**
3
+ * The workspace gate's three refusals, named as the backend's `GateRefusal`
4
+ * names them — the one set the CLI, MCP, portal and agent all share.
5
+ */
6
+ export type GateRefusal = 'paused' | 'not_entitled' | 'limit_exceeded';
7
+ export interface BillingRefusal {
8
+ /** A gate refusal, or a credit shortfall (reported separately as INSUFFICIENT_CREDITS). */
9
+ reason: GateRefusal | 'insufficient_credits';
10
+ links: {
11
+ pricing: string;
12
+ billing: string;
13
+ };
14
+ nextAction: string;
15
+ lines: string[];
16
+ }
17
+ type BillingInput = Pick<ApiError, 'code' | 'message' | 'nextAction' | 'details'> & {
18
+ apiUrl?: string;
19
+ serverNextAction?: string;
20
+ };
21
+ /** Shared pricing/billing destinations for refusals and history-window notes. */
22
+ export declare function resolveBillingLinks(input: {
23
+ apiUrl?: string;
24
+ billingUrl?: string;
25
+ orgId?: unknown;
26
+ nextAction?: string;
27
+ message?: string;
28
+ }): {
29
+ pricing: string;
30
+ billing: string;
31
+ };
32
+ /**
33
+ * Which gate refusal a FEATURE_GATED `details.reason` is. An absent or empty
34
+ * reason is an older backend that never sent one (historically a plan
35
+ * exclusion). Any other value — `rollout`, the MCP view-only mirror's
36
+ * `mcp_origin`, or one this CLI doesn't know yet — is not a billing refusal:
37
+ * upgrading does nothing for it, so it gets no links and no fallback advice.
38
+ */
39
+ export declare function gateRefusalOf(reason: unknown): GateRefusal | undefined;
40
+ /** True for a paused-workspace reason, including the deprecated `billing_hold`. */
41
+ export declare function isPausedReason(reason: unknown): boolean;
42
+ export declare function classifyBillingRefusal(input: BillingInput): BillingRefusal | undefined;
43
+ export {};
@@ -0,0 +1,171 @@
1
+ import { resolvePortalBase } from './facade.js';
2
+ function hasPlaceholder(url) {
3
+ return (/^(undefined|null)$/i.test(url.hostname) || /\/(?:undefined|null)(?:\/|$)/i.test(url.pathname));
4
+ }
5
+ function portalUrlIn(text, billingOnly = false) {
6
+ for (const match of text.matchAll(/https?:\/\/[^\s<>"'`]+/g)) {
7
+ const candidate = match[0].replace(/[),.;!?]+$/, '');
8
+ try {
9
+ const url = new URL(candidate);
10
+ if (hasPlaceholder(url))
11
+ continue;
12
+ if (url.pathname.endsWith('/settings/billing') ||
13
+ (!billingOnly && url.pathname === '/pricing')) {
14
+ return candidate;
15
+ }
16
+ }
17
+ catch {
18
+ // Ignore malformed server text and use the next available source.
19
+ }
20
+ }
21
+ return undefined;
22
+ }
23
+ /**
24
+ * The `TESTSPRITE_PORTAL_URL` origin, when the override is set and valid.
25
+ * `resolvePortalBase` checks this same env var first and ignores its `apiUrl`
26
+ * argument once it finds it set, so any argument resolves it — `''` keeps the
27
+ * intent explicit at each call site (there is no API URL to fall back to).
28
+ */
29
+ function overridePortalBase() {
30
+ if (!process.env.TESTSPRITE_PORTAL_URL?.trim())
31
+ return undefined;
32
+ const resolved = resolvePortalBase('');
33
+ return resolved && !hasPlaceholder(new URL(resolved)) ? resolved : undefined;
34
+ }
35
+ function portalBase(input) {
36
+ const override = overridePortalBase();
37
+ if (override)
38
+ return override;
39
+ const billingUrl = typeof input.details.billingUrl === 'string' ? input.details.billingUrl : '';
40
+ const serverUrl = portalUrlIn([billingUrl, input.serverNextAction ?? input.nextAction, input.message].join(' '));
41
+ if (serverUrl)
42
+ return new URL(serverUrl).origin;
43
+ return input.apiUrl ? resolvePortalBase(input.apiUrl) : undefined;
44
+ }
45
+ /**
46
+ * Rebase an absolute server-supplied billing URL onto the operator's
47
+ * `TESTSPRITE_PORTAL_URL` override, keeping the path (and query, if any) —
48
+ * the server knows its own routes, but the override says where the CLI's
49
+ * links should actually point. Without this, an override set for `pricing`
50
+ * (always synthesized from `portalBase`) silently didn't apply to a
51
+ * server-found `billing` URL, sending the two links to different hosts.
52
+ */
53
+ function rebaseOntoOverride(url) {
54
+ const override = overridePortalBase();
55
+ if (!override)
56
+ return url;
57
+ const parsed = new URL(url);
58
+ return `${override}${parsed.pathname}${parsed.search}`;
59
+ }
60
+ /** Shared pricing/billing destinations for refusals and history-window notes. */
61
+ export function resolveBillingLinks(input) {
62
+ const base = portalBase({
63
+ apiUrl: input.apiUrl,
64
+ details: { billingUrl: input.billingUrl },
65
+ nextAction: input.nextAction ?? '',
66
+ message: input.message ?? '',
67
+ code: 'FEATURE_GATED',
68
+ });
69
+ const pricing = base ? `${base}/pricing` : '/pricing';
70
+ const foundBilling = portalUrlIn(input.billingUrl ?? '', true) ??
71
+ portalUrlIn([input.nextAction, input.message].join(' '), true);
72
+ const orgId = safeOrgId(input.orgId);
73
+ const billing = (foundBilling !== undefined ? rebaseOntoOverride(foundBilling) : undefined) ??
74
+ (base
75
+ ? `${base}${orgId ? `/dashboard-v3/o/${orgId}` : '/dashboard'}/settings/billing`
76
+ : orgId
77
+ ? `/dashboard-v3/o/${orgId}/settings/billing`
78
+ : '/dashboard/settings/billing');
79
+ return { pricing, billing };
80
+ }
81
+ /** One ` label: value` line, aligned like the CLI's other key/value output. */
82
+ function fact(label, value) {
83
+ return ` ${`${label}:`.padEnd(11)}${value}`;
84
+ }
85
+ function safeOrgId(value) {
86
+ return typeof value === 'string' &&
87
+ value.trim() !== '' &&
88
+ !/^(undefined|null)$/i.test(value.trim()) &&
89
+ !/[/?#]/.test(value)
90
+ ? encodeURIComponent(value)
91
+ : undefined;
92
+ }
93
+ /**
94
+ * `details.reason` spellings of the three gate refusals: the gate's own names,
95
+ * plus the deprecated `billing_hold` / `plan` / `plan_limit` that older
96
+ * backends' CLI envelope and gate body still send. The CLI reads both and
97
+ * only ever writes the gate's names.
98
+ */
99
+ const GATE_REFUSAL_BY_REASON = new Map([
100
+ ['paused', 'paused'],
101
+ ['billing_hold', 'paused'],
102
+ ['not_entitled', 'not_entitled'],
103
+ ['plan', 'not_entitled'],
104
+ ['limit_exceeded', 'limit_exceeded'],
105
+ ['plan_limit', 'limit_exceeded'],
106
+ ]);
107
+ /**
108
+ * Which gate refusal a FEATURE_GATED `details.reason` is. An absent or empty
109
+ * reason is an older backend that never sent one (historically a plan
110
+ * exclusion). Any other value — `rollout`, the MCP view-only mirror's
111
+ * `mcp_origin`, or one this CLI doesn't know yet — is not a billing refusal:
112
+ * upgrading does nothing for it, so it gets no links and no fallback advice.
113
+ */
114
+ export function gateRefusalOf(reason) {
115
+ if (reason === undefined || reason === '')
116
+ return 'not_entitled';
117
+ return typeof reason === 'string' ? GATE_REFUSAL_BY_REASON.get(reason) : undefined;
118
+ }
119
+ /** True for a paused-workspace reason, including the deprecated `billing_hold`. */
120
+ export function isPausedReason(reason) {
121
+ return reason === 'paused' || reason === 'billing_hold';
122
+ }
123
+ export function classifyBillingRefusal(input) {
124
+ let reason;
125
+ if (input.code === 'INSUFFICIENT_CREDITS') {
126
+ reason = 'insufficient_credits';
127
+ }
128
+ else if (input.code === 'FEATURE_GATED') {
129
+ const refusal = gateRefusalOf(input.details.reason);
130
+ if (!refusal)
131
+ return undefined;
132
+ reason = refusal;
133
+ }
134
+ else {
135
+ return undefined;
136
+ }
137
+ const { pricing, billing } = resolveBillingLinks({
138
+ apiUrl: input.apiUrl,
139
+ billingUrl: typeof input.details.billingUrl === 'string' ? input.details.billingUrl : undefined,
140
+ orgId: input.details.orgId,
141
+ nextAction: input.serverNextAction ?? input.nextAction,
142
+ message: input.message,
143
+ });
144
+ // The server's message says why (which feature, which limit, why the
145
+ // workspace is paused) and its nextAction says what to do. These fallbacks
146
+ // only cover a response that arrived without a nextAction, and follow the
147
+ // backend's own CLI wording rather than guessing a cause.
148
+ let nextAction = input.nextAction;
149
+ if (!nextAction) {
150
+ switch (reason) {
151
+ case 'not_entitled':
152
+ nextAction = `Upgrade at ${billing} (plans: ${pricing}), then retry.`;
153
+ break;
154
+ case 'limit_exceeded':
155
+ nextAction = `Delete one and retry, or upgrade at ${billing} for a higher limit.`;
156
+ break;
157
+ case 'paused':
158
+ nextAction = `See ${billing} to resume this workspace, then retry.`;
159
+ break;
160
+ }
161
+ }
162
+ // Add only the links the printed message and nextAction don't already carry.
163
+ const printed = `${input.message}\n${nextAction}`;
164
+ const lines = [];
165
+ if (!printed.includes(pricing))
166
+ lines.push(fact('upgrade', pricing));
167
+ if (!printed.includes(billing))
168
+ lines.push(fact('billing', billing));
169
+ return { reason, links: { pricing, billing }, nextAction, lines };
170
+ }
171
+ //# sourceMappingURL=billing-refusal.js.map
@@ -33,6 +33,7 @@
33
33
  * when the agent re-runs. M3 may add resume.
34
34
  */
35
35
  import type { CliFailureContext } from '../commands/test.js';
36
+ import { type ShutdownHandle } from './interrupt.js';
36
37
  import type { FetchImpl } from './http.js';
37
38
  /** Schema version stamped into `meta.json`. Bumps with the contract. */
38
39
  export declare const BUNDLE_SCHEMA_VERSION: "cli-v1";
@@ -90,6 +91,8 @@ export interface WriteBundleOptions {
90
91
  failedOnly: boolean;
91
92
  /** Custom fetch impl for tests. Defaults to global `fetch`. */
92
93
  fetchImpl?: FetchImpl;
94
+ shutdownSignal?: AbortSignal;
95
+ shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
93
96
  /** Server requestId to embed in `.partial` on failure. */
94
97
  requestId?: string;
95
98
  }
@@ -226,4 +229,6 @@ export declare function commitBundle(tmpDir: string, dir: string, files: Readonl
226
229
  */
227
230
  export declare function streamUrlToFile(url: string, filePath: string, fetchImpl: FetchImpl, deps?: {
228
231
  sleep?: (ms: number) => Promise<void>;
232
+ shutdownSignal?: AbortSignal;
233
+ shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
229
234
  }): Promise<void>;
@@ -37,7 +37,9 @@ import { mkdir, mkdtemp, readdir, rename, rm, stat, unlink, writeFile } from 'no
37
37
  import { pipeline } from 'node:stream/promises';
38
38
  import { createWriteStream } from 'node:fs';
39
39
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
40
- import { ApiError, TransportError, localValidationError } from './errors.js';
40
+ import { ApiError, InterruptError, TransportError, localValidationError } from './errors.js';
41
+ import { globalShutdown } from './interrupt.js';
42
+ import { defaultSleep, sleepUnlessInterrupted } from './poll-support.js';
41
43
  import { requireEnum } from './validate.js';
42
44
  /** Schema version stamped into `meta.json`. Bumps with the contract. */
43
45
  export const BUNDLE_SCHEMA_VERSION = 'cli-v1';
@@ -321,6 +323,10 @@ export async function writeBundle(ctx, options) {
321
323
  assertContextIntegrity(filtered, requestId);
322
324
  const dir = resolveBundleDir(options.dir);
323
325
  const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
326
+ const downloadDeps = {
327
+ shutdownSignal: options.shutdownSignal,
328
+ shutdown: options.shutdown,
329
+ };
324
330
  const meta = buildMeta(filtered);
325
331
  const codeExt = pickCodeExtension(filtered.code.language, filtered.code.framework);
326
332
  await mkdir(dir, { recursive: true });
@@ -343,7 +349,7 @@ export async function writeBundle(ctx, options) {
343
349
  // bodies), stream the URL into the file rather than embedding
344
350
  // the URL in code.<ext>. M2's backend hasn't shipped the
345
351
  // >=100KB branch yet, but the contract supports it.
346
- await streamUrlToFile(filtered.code.code, join(tmpDir, codeFile), fetchImpl);
352
+ await streamUrlToFile(filtered.code.code, join(tmpDir, codeFile), fetchImpl, downloadDeps);
347
353
  }
348
354
  else {
349
355
  await writeFile(join(tmpDir, codeFile), filtered.code.code, 'utf8');
@@ -356,11 +362,11 @@ export async function writeBundle(ctx, options) {
356
362
  // (some runs ship `.webm`, not `.mp4`).
357
363
  if (filtered.result.videoUrl) {
358
364
  const videoFile = `video.${pickVideoExtension(filtered.result.videoUrl)}`;
359
- await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, videoFile), fetchImpl);
365
+ await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, videoFile), fetchImpl, downloadDeps);
360
366
  filesWritten.push(videoFile);
361
367
  }
362
368
  for (const step of filtered.steps) {
363
- await writeStepArtifacts(step, filtered.failure.evidence, stepsTmpDir, fetchImpl, filesWritten);
369
+ await writeStepArtifacts(step, filtered.failure.evidence, stepsTmpDir, fetchImpl, filesWritten, downloadDeps);
364
370
  }
365
371
  // meta.json LAST. Its presence is the sentinel that the bundle
366
372
  // is complete. An agent that opens <dir> and finds meta.json can
@@ -521,7 +527,7 @@ async function dirExists(path) {
521
527
  * console — for that step). The evidence-json file is omitted when
522
528
  * there's nothing to put in it; it's NOT a placeholder.
523
529
  */
524
- async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, filesWritten) {
530
+ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, filesWritten, downloadDeps) {
525
531
  // stepIndex comes straight from the response and is used to build the
526
532
  // filename — reject anything that isn't a real index before composing a path.
527
533
  if (!Number.isInteger(step.stepIndex) || step.stepIndex < 0) {
@@ -530,12 +536,12 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
530
536
  const prefix = stepFilenamePrefix(step.stepIndex);
531
537
  if (step.screenshotUrl) {
532
538
  const file = `${prefix}-screenshot.png`;
533
- await streamUrlToFile(step.screenshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl);
539
+ await streamUrlToFile(step.screenshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl, downloadDeps);
534
540
  filesWritten.push(`steps/${file}`);
535
541
  }
536
542
  if (step.htmlSnapshotUrl) {
537
543
  const file = `${prefix}-snapshot.html`;
538
- await streamUrlToFile(step.htmlSnapshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl);
544
+ await streamUrlToFile(step.htmlSnapshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl, downloadDeps);
539
545
  filesWritten.push(`steps/${file}`);
540
546
  }
541
547
  // Evidence sidecar artifacts. Per codex round-1 P2: the bundle must
@@ -583,7 +589,7 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
583
589
  }
584
590
  const ext = sidecarExtension(entry.kind);
585
591
  const filename = `${prefix}-${entry.kind}-${i}.${ext}`;
586
- await streamUrlToFile(entry.url, assertNoEscape(stepsTmpDir, filename), fetchImpl);
592
+ await streamUrlToFile(entry.url, assertNoEscape(stepsTmpDir, filename), fetchImpl, downloadDeps);
587
593
  filesWritten.push(`steps/${filename}`);
588
594
  return {
589
595
  kind: entry.kind,
@@ -628,21 +634,31 @@ function sidecarExtension(kind) {
628
634
  * Presigned URLs are valid for 15 minutes, so retries are safe.
629
635
  */
630
636
  export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
631
- const sleepFn = deps?.sleep ?? ((ms) => new Promise(r => setTimeout(r, ms)));
637
+ const shutdownSignal = deps?.shutdownSignal ?? globalShutdown.signal;
638
+ const shutdown = deps?.shutdown ?? globalShutdown;
639
+ return shutdown.runCriticalOperation(() => streamUrlToFileTracked(url, filePath, fetchImpl, deps?.sleep ?? defaultSleep, shutdownSignal));
640
+ }
641
+ async function streamUrlToFileTracked(url, filePath, fetchImpl, sleepFn, shutdownSignal) {
632
642
  const artifactUrl = redactArtifactUrlForDetails(url);
633
643
  for (let attempt = 1; attempt <= STREAM_URL_MAX_RETRIES; attempt++) {
644
+ if (shutdownSignal.aborted)
645
+ throw shutdownSignal.reason;
634
646
  let response;
635
647
  try {
636
- response = await fetchImpl(url, { redirect: 'error' });
648
+ response = await fetchImpl(url, { redirect: 'error', signal: shutdownSignal });
637
649
  }
638
650
  catch (err) {
651
+ if (err instanceof InterruptError || shutdownSignal.aborted)
652
+ throw shutdownSignal.reason ?? err;
639
653
  const message = err instanceof Error ? err.message : String(err);
640
654
  if (attempt < STREAM_URL_MAX_RETRIES) {
641
- await sleepFn(STREAM_URL_RETRY_DELAY_MS);
655
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
642
656
  continue;
643
657
  }
644
658
  throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
645
659
  }
660
+ if (shutdownSignal.aborted)
661
+ throw shutdownSignal.reason;
646
662
  if (!response.ok) {
647
663
  // Non-2xx: the URL itself is bad (expired, unauthorized, not found).
648
664
  // Retrying the same URL won't help — surface immediately.
@@ -665,12 +681,20 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
665
681
  try {
666
682
  const buffer = Buffer.from(await response.arrayBuffer());
667
683
  await writeFile(filePath, buffer);
684
+ if (shutdownSignal.aborted) {
685
+ await rm(filePath, { force: true }).catch(() => undefined);
686
+ throw shutdownSignal.reason;
687
+ }
668
688
  return;
669
689
  }
670
690
  catch (err) {
691
+ if (err instanceof InterruptError || shutdownSignal.aborted) {
692
+ await rm(filePath, { force: true }).catch(() => undefined);
693
+ throw shutdownSignal.reason ?? err;
694
+ }
671
695
  const message = err instanceof Error ? err.message : String(err);
672
696
  if (attempt < STREAM_URL_MAX_RETRIES) {
673
- await sleepFn(STREAM_URL_RETRY_DELAY_MS);
697
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
674
698
  continue;
675
699
  }
676
700
  throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
@@ -688,12 +712,18 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
688
712
  const { Readable } = await import('node:stream');
689
713
  const nodeStream = Readable.fromWeb(webBody);
690
714
  await pipeline(nodeStream, fileSink);
715
+ if (shutdownSignal.aborted)
716
+ throw shutdownSignal.reason;
691
717
  return;
692
718
  }
693
719
  catch (err) {
720
+ if (err instanceof InterruptError || shutdownSignal.aborted) {
721
+ await rm(filePath, { force: true }).catch(() => undefined);
722
+ throw shutdownSignal.reason ?? err;
723
+ }
694
724
  const message = err instanceof Error ? err.message : String(err);
695
725
  if (attempt < STREAM_URL_MAX_RETRIES) {
696
- await sleepFn(STREAM_URL_RETRY_DELAY_MS);
726
+ await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
697
727
  continue;
698
728
  }
699
729
  throw new TransportError(`Failed mid-download of ${artifactUrl}: ${message}`);