@testsprite/testsprite-cli 0.12.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 (91) hide show
  1. package/README.md +11 -4
  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 +436 -5
  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.js +9 -9
  11. package/dist/commands/project.d.ts +5 -5
  12. package/dist/commands/project.js +42 -42
  13. package/dist/commands/schedule.d.ts +2 -0
  14. package/dist/commands/schedule.js +18 -10
  15. package/dist/commands/test.d.ts +73 -27
  16. package/dist/commands/test.js +1756 -413
  17. package/dist/commands/testlist.js +49 -19
  18. package/dist/commands/tunnel.d.ts +26 -3
  19. package/dist/commands/tunnel.js +211 -14
  20. package/dist/commands/usage.d.ts +3 -0
  21. package/dist/commands/usage.js +12 -5
  22. package/dist/index.js +34 -20
  23. package/dist/lib/agent-targets.d.ts +3 -3
  24. package/dist/lib/agent-targets.js +2 -2
  25. package/dist/lib/billing-refusal.d.ts +43 -0
  26. package/dist/lib/billing-refusal.js +171 -0
  27. package/dist/lib/bundle.d.ts +5 -0
  28. package/dist/lib/bundle.js +43 -13
  29. package/dist/lib/ci-linkage.d.ts +90 -0
  30. package/dist/lib/ci-linkage.js +181 -0
  31. package/dist/lib/client-factory.d.ts +4 -1
  32. package/dist/lib/client-factory.js +23 -2
  33. package/dist/lib/config.d.ts +17 -0
  34. package/dist/lib/config.js +20 -1
  35. package/dist/lib/conflict-reason.d.ts +27 -3
  36. package/dist/lib/conflict-reason.js +53 -4
  37. package/dist/lib/credentials.js +56 -14
  38. package/dist/lib/dry-run/samples.d.ts +13 -1
  39. package/dist/lib/dry-run/samples.js +51 -7
  40. package/dist/lib/errors.d.ts +18 -11
  41. package/dist/lib/errors.js +111 -13
  42. package/dist/lib/failing-fe-resolver.d.ts +1 -1
  43. package/dist/lib/failing-fe-resolver.js +3 -3
  44. package/dist/lib/gh-output.d.ts +1 -0
  45. package/dist/lib/gh-output.js +13 -4
  46. package/dist/lib/history-retention.d.ts +8 -0
  47. package/dist/lib/history-retention.js +24 -0
  48. package/dist/lib/http.d.ts +37 -19
  49. package/dist/lib/http.js +46 -24
  50. package/dist/lib/interrupt.d.ts +21 -13
  51. package/dist/lib/interrupt.js +32 -21
  52. package/dist/lib/junit-report.d.ts +11 -1
  53. package/dist/lib/junit-report.js +15 -3
  54. package/dist/lib/local-target.d.ts +1 -1
  55. package/dist/lib/local-target.js +1 -1
  56. package/dist/lib/plan-poll.d.ts +11 -11
  57. package/dist/lib/plan-poll.js +12 -12
  58. package/dist/lib/plans.types.d.ts +9 -9
  59. package/dist/lib/plans.types.js +3 -3
  60. package/dist/lib/poll.d.ts +2 -2
  61. package/dist/lib/poll.js +9 -3
  62. package/dist/lib/render-error.d.ts +2 -0
  63. package/dist/lib/render-error.js +13 -0
  64. package/dist/lib/response-schemas.d.ts +54 -12
  65. package/dist/lib/response-schemas.js +88 -7
  66. package/dist/lib/runs.types.d.ts +59 -10
  67. package/dist/lib/secret-file.js +72 -14
  68. package/dist/lib/skill-nudge.d.ts +6 -1
  69. package/dist/lib/skill-nudge.js +32 -5
  70. package/dist/lib/target-url-preflight.d.ts +6 -4
  71. package/dist/lib/target-url-preflight.js +64 -51
  72. package/dist/lib/target-url.js +6 -6
  73. package/dist/lib/telemetry.d.ts +4 -1
  74. package/dist/lib/telemetry.js +13 -13
  75. package/dist/lib/ticker.js +93 -4
  76. package/dist/lib/tunnel-session.d.ts +13 -0
  77. package/dist/lib/tunnel-session.js +4 -1
  78. package/dist/lib/tunnel.types.d.ts +12 -2
  79. package/dist/lib/tunnel.types.js +2 -2
  80. package/dist/lib/wait-exit.d.ts +8 -0
  81. package/dist/lib/wait-exit.js +76 -4
  82. package/dist/lib/workspace-status.d.ts +23 -0
  83. package/dist/lib/workspace-status.js +15 -0
  84. package/dist/version-guard.d.ts +7 -1
  85. package/dist/version-guard.js +19 -1
  86. package/dist/version.d.ts +1 -1
  87. package/dist/version.js +1 -1
  88. package/package.json +4 -4
  89. package/skills/testsprite-onboard.skill.md +4 -4
  90. package/skills/testsprite-verify.codex.md +59 -57
  91. package/skills/testsprite-verify.skill.md +53 -38
package/README.md CHANGED
@@ -61,7 +61,7 @@ npm install -g @testsprite/testsprite-cli
61
61
  testsprite setup
62
62
  ```
63
63
 
64
- `testsprite setup` prompts for your [API key](https://www.testsprite.com), verifies it, and installs the verification-loop skill for the coding agents this project uses — one command, so your agent is wired to verify its own work.
64
+ `testsprite setup` prompts for your [API key](https://www.testsprite.com/dashboard/settings/apikey), verifies it, and installs the verification-loop skill for the coding agents this project uses — one command, so your agent is wired to verify its own work.
65
65
 
66
66
  **Which agent it installs for.** Each of the eight supported targets — `claude`, `cursor`, `cline`, `windsurf`, `antigravity`, `kiro`, `copilot`, `codex` — lands its skill in a different place, so `setup` works out which you use: the agent calling it, if it identifies itself, together with every agent whose config is already in the project. It installs for all of them and prints what it found — in a terminal it shows you that list first, so you can accept it or narrow it before anything is written. If nothing identifies an agent, it installs for `claude` and says so — that is the one case where you want `--agent <target>` to name one yourself. Check the result any time with `testsprite agent status`.
67
67
 
@@ -136,18 +136,25 @@ Use an API key with `run:tunnel`: keys minted before that scope existed need to
136
136
  ```bash
137
137
  testsprite project create --type frontend --name "My local app" --local 3000
138
138
  testsprite test create --plan-from ./checkout.plan.json --project <project-id>
139
- testsprite test run <test-id> --local 3000 # per-run tunnel; waits up to 1200 seconds
139
+ testsprite test run <test-id> --local 3000 # waits up to 1200 seconds
140
+ testsprite test run <id> <id> --local 3000 --max-concurrency 5
141
+ testsprite test run --all --project <project-id> --local 3000
140
142
  # Or keep one tunnel open in terminal A (no port argument)
141
143
  testsprite tunnel start --ttl 3600
142
144
  # Terminal B: borrow the clientId printed above; keep terminal A running
143
145
  testsprite test run <test-id> --local 3000 --tunnel-client <client-uuid>
146
+ testsprite tunnel list
147
+ testsprite tunnel stop <client-uuid>
148
+ # Stop every live tunnel on this account only when you intend to revoke them all
149
+ testsprite tunnel stop --all --confirm
144
150
  ```
145
151
 
146
- Run one test per invocation; parallel invocations are fine (5 live tunnel bindings per user); `--all --local` is refused.
152
+ Run several local frontend tests in one invocation to share one tunnel binding. The batch runs up to 5 tests at once by default; `--max-concurrency` accepts 1–10. `--all --local` skips backend tests. An owned batch cancels unfinished runs on Ctrl-C or tunnel loss; JSON output lists every requested test in input order, including tests that did not start. The minted client id is printed before the tunnel connects.
153
+ Hit the tunnel limit? Run `testsprite tunnel list`, then `testsprite tunnel stop <client-uuid>` for an unused binding, or `testsprite tunnel stop --all --confirm` to revoke them all. An older server without listing returns exit 4; a key without `run:tunnel` returns exit 3.
147
154
  A second `tunnel start` or process using the same credential takes over, and the first exits **10**.
148
155
  The examples use `127.0.0.1`. For another loopback listener, pass the same `--local-host localhost` or `--local-host ::1` to project creation and every follow-up run. The selected host is stored in the project URL (`::1` becomes `http://[::1]:<port>`); `project get/list` exposes `originMode: 'local'` in JSON and shows `(Local)` in text output.
149
156
  The control plane is WebSocket over TLS (`wss://control.tun.testsprite.com/ws`). The data plane, which carries the tunnel secret and proxied traffic, uses TLS at `data.tun.testsprite.com:443` and verifies the certificate with Node's default trust store: its bundled Mozilla roots, plus certificates supplied through `NODE_EXTRA_CA_CERTS` and the system CAs when Node is started with `--use-system-ca`. Node 20 is supported without losing `NODE_EXTRA_CA_CERTS`. Verification cannot be disabled, and the CLI never falls back from TLS to plaintext. On a network that re-signs TLS, export your organisation's root CA to a PEM file and set `NODE_EXTRA_CA_CERTS=/path/to/ca.pem` before running `testsprite`. Plaintext connects and TLS handshakes each time out after 10 seconds. The first failed attempt starts a **60-second** retry episode; writing `TunnelHello` is not enough to reset it. The episode ends only after the first inbound tunnel stream or after the socket remains open for 5 seconds following the hello. A real deadline timer stays armed across retries and destroys an in-flight socket when it expires. After that, an owned `test run --local` run is cancelled and refunded and the command exits **10**; `tunnel start` exits **10**. If a self-hosted or older TestSprite server does not advertise a TLS endpoint, the CLI prints a one-time warning and uses legacy plaintext port **7400** under the same timeout and retry rules. `tunnel start` prints `transport: tls` or `transport: plaintext`.
150
- An owned tunnel's timeout or Ctrl-C cancels the run by default. A borrowed run still detaches without cancellation on Ctrl-C/SIGTERM because its owner keeps the tunnel alive; if that owner disappears while the run is active, the borrower cancels its own run and reports `cancelled`, `already finished`, or `skipped`. A run cancelled before it finishes is refunded. `--no-cancel-on-interrupt` also skips this owner-gone cancellation. Keep the early `Run <runId>` receipt on stderr and read the reported run before re-running.
157
+ An owned tunnel's timeout or Ctrl-C cancels unfinished runs by default. A borrowed run still detaches without cancellation on Ctrl-C/SIGTERM because its owner keeps the tunnel alive; if that owner disappears while a run is active, the borrower cancels its own run and reports `cancelled`, `already finished`, or `skipped`. A run cancelled before it finishes is refunded. `--no-cancel-on-interrupt` also skips this owner-gone cancellation. Keep the early stderr run-id receipts (`Run <runId>` for one test, `[i/N] <testId> → run <runId>` for a batch) and read the reported runs before re-running.
151
158
  Local projects skip exploration/plan generation; author plans with `test create --plan-from`. Portal runs are blocked for free until you set a public project URL.
152
159
  See [the full local-testing reference](./DOCUMENTATION.md#local-frontend-testing-and-tunnels) for flags, login, billing/refunds, timeouts, and retargeting.
153
160
 
@@ -1,6 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import fs from 'node:fs/promises';
3
3
  import { Command } from 'commander';
4
+ import { resolveProfileName } from '../lib/config.js';
4
5
  import { CLIError, localValidationError } from '../lib/errors.js';
5
6
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
6
7
  import { promptText } from '../lib/prompt.js';
@@ -215,7 +216,7 @@ function composeManagedFile(state, section) {
215
216
  }
216
217
  /**
217
218
  * Actions that mean bytes actually changed on disk — the trigger set for the
218
- * post-install reload hint (DEV-279). Covers both write modes: own-file
219
+ * post-install reload hint. Covers both write modes: own-file
219
220
  * (`written`/`updated`) and codex managed-section (`section-*`).
220
221
  */
221
222
  const CHANGED_ACTIONS = new Set([
@@ -231,7 +232,7 @@ const CHANGED_ACTIONS = new Set([
231
232
  * Per-invocation cache in front of {@link ownFileBodyFor}, so each (target, skill)
232
233
  * pair reads its asset once. `agent install` (which stamps the body's hash into the
233
234
  * marker) and `agent status` (which re-derives it) share this rather than keeping
234
- * private copies — they didn't, hence DEV-672.
235
+ * private copies that could silently disagree.
235
236
  */
236
237
  function makeOwnFileBodyResolver() {
237
238
  // Keyed on the pair: the same skill resolves to different bytes per target.
@@ -387,9 +388,9 @@ export async function runInstall(opts, deps = {}) {
387
388
  }
388
389
  // We DO read the existing file (if present) to compute the
389
390
  // would-be byte count and emit the 32 KiB budget warning — without
390
- // this the warning was silently absent on --dry-run runs (Fix 4).
391
+ // this the warning was silently absent on --dry-run runs.
391
392
  //
392
- // [P3 round-2] Measure the ACTUAL composed result via the same
393
+ // Measure the ACTUAL composed result via the same
393
394
  // classifySection + composeManagedFile pipeline the real install
394
395
  // uses — `existing + section` double-counts the old block on the
395
396
  // replace path and misses the append separator. Read failures other
@@ -605,7 +606,7 @@ export async function runInstall(opts, deps = {}) {
605
606
  const items = data;
606
607
  return items.map(r => `${r.target.padEnd(12)} ${r.action.padEnd(12)} ${r.path}`).join('\n');
607
608
  });
608
- // 8b. Reload hint (DEV-279). A coding agent reads its skill/rule files at
609
+ // 8b. Reload hint. A coding agent reads its skill/rule files at
609
610
  // session start, so a session already open when we wrote the file won't pick
610
611
  // it up. Fire only when something actually changed on disk — silent on
611
612
  // skipped/unchanged/blocked/dry-run and in --output json. Targets are
@@ -627,7 +628,7 @@ export async function runInstall(opts, deps = {}) {
627
628
  * Display name for the AGENT column. Experimental targets get an "(exp.)" tag so
628
629
  * support maturity stays visible without a dedicated STATUS column — a bare
629
630
  * `ga`/`experimental` column reads like install state, which is `agent status`'s
630
- * job, not this catalog's (DEV-279).
631
+ * job, not this catalog's.
631
632
  */
632
633
  function agentDisplayName(target, status) {
633
634
  return status === 'experimental' ? `${target} (exp.)` : target;
@@ -655,7 +656,7 @@ export async function runList(opts, deps = {}) {
655
656
  // (with an "(exp.)" maturity tag), the skill, and where it lands. STATUS and
656
657
  // MODE stay in the JSON shape for back-compat but are dropped from the human
657
658
  // table — MODE is an internal write strategy, and STATUS (ga/experimental)
658
- // reads like install state, which lives in `agent status` (DEV-279).
659
+ // reads like install state, which lives in `agent status`.
659
660
  out.print(results, data => {
660
661
  const items = data;
661
662
  const header = `${'AGENT'.padEnd(20)} ${'SKILL'.padEnd(20)} PATH`;
@@ -674,8 +675,9 @@ export async function runList(opts, deps = {}) {
674
675
  * comparison for own-file targets.
675
676
  *
676
677
  * `canonicalBody` is already bound to THIS target by the caller and takes no
677
- * arguments, so the per-skill-only lookup that caused DEV-672 cannot be expressed
678
- * here. It is called only once an artifact is known to exist and carry a marker,
678
+ * arguments, so a lookup keyed on skill alone — which let install and status
679
+ * resolve different bodies for the same target — cannot be expressed here. It
680
+ * is called only once an artifact is known to exist and carry a marker,
679
681
  * so a row with nothing installed never touches the skill assets.
680
682
  */
681
683
  async function classifyOwnFileState(agentFs, abs, target, skill, canonicalBody) {
@@ -773,7 +775,8 @@ export async function runStatus(opts, deps = {}) {
773
775
  }
774
776
  const dir = opts.dir !== undefined ? opts.dir.trim() : (deps.cwd ?? process.cwd());
775
777
  const root = path.resolve(dir);
776
- // The SAME resolver the installer stamps its marker hashes from (DEV-672).
778
+ // The SAME resolver the installer stamps its marker hashes from — a
779
+ // separate copy here is exactly how install and status end up disagreeing.
777
780
  const ownFileBodyFor = makeOwnFileBodyResolver();
778
781
  const results = [];
779
782
  for (const [target, spec] of Object.entries(TARGETS)) {
@@ -792,7 +795,7 @@ export async function runStatus(opts, deps = {}) {
792
795
  path: relPath,
793
796
  state: await classifyOwnFileState(agentFs, path.resolve(root, relPath), target, skill,
794
797
  // Deferred, not resolved here: an absent artifact must not need the
795
- // skill assets at all, as it didn't before DEV-672.
798
+ // skill assets at all.
796
799
  () => ownFileBodyFor(target, skill)),
797
800
  });
798
801
  }
@@ -865,10 +868,10 @@ export function createAgentCommand(deps = {}) {
865
868
  // ---------------------------------------------------------------------------
866
869
  // Per-file helpers (per convention: copy from auth.ts)
867
870
  // ---------------------------------------------------------------------------
868
- function resolveCommonOptions(command) {
871
+ function resolveCommonOptions(command, env) {
869
872
  const globals = command.optsWithGlobals();
870
873
  return {
871
- profile: globals.profile ?? 'default',
874
+ profile: resolveProfileName(globals.profile, env),
872
875
  output: resolveOutputMode(globals.output),
873
876
  endpointUrl: globals.endpointUrl,
874
877
  debug: globals.debug ?? false,
@@ -1,6 +1,9 @@
1
1
  import { Command } from 'commander';
2
+ import { type WorkspaceStatus } from '../lib/workspace-status.js';
2
3
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
4
+ import { ApiError } from '../lib/errors.js';
3
5
  import type { FetchImpl } from '../lib/http.js';
6
+ import { type ShutdownHandle } from '../lib/interrupt.js';
4
7
  import type { CliOrgBinding, CliOrgSummary } from '../lib/org-render.js';
5
8
  export interface MeResponse {
6
9
  userId: string;
@@ -41,6 +44,8 @@ export interface MeResponse {
41
44
  remaining: number;
42
45
  includedCredits: number;
43
46
  seats: number;
47
+ /** Billing standing (paused / pending / ok). Absent on an older backend. */
48
+ workspace?: WorkspaceStatus;
44
49
  };
45
50
  /**
46
51
  * Every organization the underlying user belongs to (account-wide
@@ -60,9 +65,13 @@ export interface AuthDeps {
60
65
  env?: NodeJS.ProcessEnv;
61
66
  credentialsPath?: string;
62
67
  fetchImpl?: FetchImpl;
68
+ shutdownSignal?: AbortSignal;
69
+ shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
63
70
  prompt?: {
64
71
  secret: (question: string) => Promise<string>;
65
72
  };
73
+ /** Setup passes a supplied --api-key through a synthetic prompt. */
74
+ suppliedApiKey?: boolean;
66
75
  stdout?: (line: string) => void;
67
76
  stderr?: (line: string) => void;
68
77
  preludeWrite?: (chunk: string) => void;
@@ -92,6 +101,16 @@ interface ConfigureOptions extends CommonOptions {
92
101
  */
93
102
  skipIfConfigured?: boolean;
94
103
  }
104
+ /**
105
+ * Exit-5 error for "no key arrived" on any path: the interactive prompt,
106
+ * `--from-env`, and non-interactive setup. The hint is appended to the message
107
+ * and to `nextAction`; a path-specific `nextAction` lead-in and `details` are
108
+ * kept so callers lose nothing by routing through here.
109
+ */
110
+ export declare function missingApiKeyError(message: string, apiUrl: string, opts?: {
111
+ nextAction?: string;
112
+ details?: Record<string, unknown>;
113
+ }): ApiError;
95
114
  export interface ConfigureResult {
96
115
  persisted: boolean;
97
116
  source: 'env' | 'prompt' | 'profile' | 'dry-run';
@@ -1,17 +1,49 @@
1
1
  import { Command } from 'commander';
2
+ import { formatWorkspaceStatus } from '../lib/workspace-status.js';
2
3
  import { assertValidApiKey, assertValidEndpointUrl, emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
3
- import { ApiError, CLIError } from '../lib/errors.js';
4
- import { facadeBaseUrl } from '../lib/facade.js';
4
+ import { ApiError, CLIError, InterruptError } from '../lib/errors.js';
5
+ import { facadeBaseUrl, resolvePortalBase } from '../lib/facade.js';
5
6
  import { HttpClient } from '../lib/http.js';
7
+ import { globalShutdown } from '../lib/interrupt.js';
6
8
  import { defaultCredentialsPath, deleteProfile, isCredentialsWritePermissionError, readProfile, writeProfile, } from '../lib/credentials.js';
7
- import { loadConfig, normalizeEnvVar } from '../lib/config.js';
9
+ import { loadConfig, normalizeEnvVar, resolveProfileName } from '../lib/config.js';
8
10
  import { emitDeprecationNotice } from '../lib/deprecate.js';
9
11
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
10
12
  import { promptSecret } from '../lib/prompt.js';
13
+ import { ME_RESPONSE_SCHEMA } from '../lib/response-schemas.js';
11
14
  import { formatOrgBinding, formatOrgsSummary, formatPersonalScopeHint } from '../lib/org-render.js';
12
15
  import { emitV3RoutingAdvisory, routingLabel } from '../lib/v3-advisory.js';
13
16
  const DEFAULT_API_URL = 'https://api.testsprite.com';
14
17
  const FROM_ENV_MISSING_KEY = 'TESTSPRITE_API_KEY is not set in the environment. Set it and re-run with --from-env, or omit --from-env to enter the key interactively.';
18
+ const API_KEY_PAGE_PATH = '/dashboard/settings/apikey';
19
+ /**
20
+ * Where a key comes from. Names the Portal origin that matches the API
21
+ * endpoint; for an endpoint the host map does not know, names the page by
22
+ * path only. `resolvePortalBase` returns undefined there on purpose — a
23
+ * confident link to the wrong environment's portal is worse than no origin.
24
+ */
25
+ function apiKeyHint(apiUrl) {
26
+ const portalBase = resolvePortalBase(apiUrl);
27
+ return portalBase === undefined
28
+ ? `Create or copy an API key on your TestSprite dashboard's API-keys page (${API_KEY_PAGE_PATH}).`
29
+ : `Create or copy an API key at ${portalBase}${API_KEY_PAGE_PATH}`;
30
+ }
31
+ /**
32
+ * Exit-5 error for "no key arrived" on any path: the interactive prompt,
33
+ * `--from-env`, and non-interactive setup. The hint is appended to the message
34
+ * and to `nextAction`; a path-specific `nextAction` lead-in and `details` are
35
+ * kept so callers lose nothing by routing through here.
36
+ */
37
+ export function missingApiKeyError(message, apiUrl, opts = {}) {
38
+ const hint = apiKeyHint(apiUrl);
39
+ return new ApiError({
40
+ code: 'VALIDATION_ERROR',
41
+ message: `${message} ${hint}`,
42
+ nextAction: opts.nextAction === undefined ? hint : `${opts.nextAction} ${hint}`,
43
+ requestId: 'local',
44
+ details: opts.details ?? {},
45
+ });
46
+ }
15
47
  export async function runConfigure(opts, deps = {}) {
16
48
  const env = deps.env ?? process.env;
17
49
  const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
@@ -58,8 +90,12 @@ export async function runConfigure(opts, deps = {}) {
58
90
  assertValidEndpointUrl(apiUrl);
59
91
  if (opts.fromEnv) {
60
92
  apiKey = env.TESTSPRITE_API_KEY?.trim();
61
- if (!apiKey)
62
- throw validationError('TESTSPRITE_API_KEY', FROM_ENV_MISSING_KEY);
93
+ if (!apiKey) {
94
+ throw missingApiKeyError(FROM_ENV_MISSING_KEY, apiUrl, {
95
+ nextAction: 'Set TESTSPRITE_API_KEY and re-run.',
96
+ details: { field: 'TESTSPRITE_API_KEY', reason: 'missing' },
97
+ });
98
+ }
63
99
  }
64
100
  else {
65
101
  // --skip-if-configured: when a non-empty API key is already saved for
@@ -78,9 +114,11 @@ export async function runConfigure(opts, deps = {}) {
78
114
  const promptApi = deps.prompt ?? { secret: (q) => promptSecret(q) };
79
115
  prelude(`Configuring profile "${opts.profile}".\n`);
80
116
  // Only the API key is prompted -- the endpoint defaults to prod (see above).
117
+ if (!deps.suppliedApiKey)
118
+ stderr(apiKeyHint(apiUrl));
81
119
  apiKey = (await promptApi.secret('TestSprite API key: ')).trim();
82
120
  if (!apiKey)
83
- throw new CLIError('No API key provided.', 5);
121
+ throw missingApiKeyError('No API key provided.', apiUrl);
84
122
  }
85
123
  // Advisory: when the endpoint was silently inherited from an existing profile
86
124
  // (not an explicit flag/env), surface it before validating the key against it
@@ -103,6 +141,8 @@ export async function runConfigure(opts, deps = {}) {
103
141
  apiKey,
104
142
  fetchImpl: deps.fetchImpl,
105
143
  requestTimeoutMs: opts.requestTimeoutMs,
144
+ shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
145
+ shutdown: deps.shutdown ?? globalShutdown,
106
146
  });
107
147
  try {
108
148
  // Tag the validation call with the originating command (when provided) so
@@ -112,6 +152,8 @@ export async function runConfigure(opts, deps = {}) {
112
152
  await pingClient.get('/me', deps.commandTag ? { headers: { 'x-cli-command': deps.commandTag } } : {});
113
153
  }
114
154
  catch (err) {
155
+ if (err instanceof InterruptError)
156
+ throw err;
115
157
  const message = err instanceof Error ? err.message : String(err);
116
158
  stderr(`API key rejected by ${apiUrl}: ${message} — profile NOT updated`);
117
159
  // When the verification call returned a typed API error (AUTH_INVALID,
@@ -181,7 +223,7 @@ export async function runWhoami(opts, deps = {}) {
181
223
  fetchImpl: deps.fetchImpl,
182
224
  stderr: deps.stderr,
183
225
  });
184
- const me = await client.get('/me');
226
+ const me = await client.get('/me', { schema: ME_RESPONSE_SCHEMA });
185
227
  out.print(me, data => {
186
228
  const m = data;
187
229
  const lines = [
@@ -202,6 +244,11 @@ export async function runWhoami(opts, deps = {}) {
202
244
  ...(m.v3Enabled === true && m.activeOrg
203
245
  ? [`org: ${m.activeOrg.name} (${m.activeOrg.plan}, ${m.activeOrg.role})`]
204
246
  : []),
247
+ // A paused (or payment-pending) workspace refuses every write, so say so
248
+ // next to the org it applies to instead of letting the next command find out.
249
+ ...(m.v3Enabled === true && formatWorkspaceStatus(m.activeOrg?.workspace)
250
+ ? [`workspace: ${formatWorkspaceStatus(m.activeOrg?.workspace)}`]
251
+ : []),
205
252
  // Authoritative routing mode, rendered only when the backend supplies it.
206
253
  ...(m.v3Enabled !== undefined ? [`routing: ${routingLabel(m.v3Enabled)}`] : []),
207
254
  // Org attribution — account-wide membership list, rendered only when
@@ -262,7 +309,7 @@ export function createAuthCommand(deps = {}) {
262
309
  .description('Show the user, API key, env, and scopes bound to the active profile')
263
310
  .addHelpText('after', GLOBAL_OPTS_HINT)
264
311
  .action(async (_cmdOpts, command) => {
265
- await runWhoami(resolveCommonOptions(command), deps);
312
+ await runWhoami(resolveCommonOptions(command, deps.env), deps);
266
313
  });
267
314
  // `whoami` — hidden, deprecated alias for `status` (kept so scripts/agents
268
315
  // on the old name keep working; invisible to --help).
@@ -271,14 +318,14 @@ export function createAuthCommand(deps = {}) {
271
318
  .addHelpText('after', GLOBAL_OPTS_HINT)
272
319
  .action(async (_cmdOpts, command) => {
273
320
  emitDeprecationNotice('auth whoami', 'auth status', deps.stderr);
274
- await runWhoami(resolveCommonOptions(command), deps);
321
+ await runWhoami(resolveCommonOptions(command, deps.env), deps);
275
322
  });
276
323
  auth
277
324
  .command('remove')
278
325
  .description('Remove credentials for the active profile')
279
326
  .addHelpText('after', GLOBAL_OPTS_HINT)
280
327
  .action(async (_cmdOpts, command) => {
281
- await runLogout(resolveCommonOptions(command), deps);
328
+ await runLogout(resolveCommonOptions(command, deps.env), deps);
282
329
  });
283
330
  // `logout` — hidden, deprecated alias for `remove`.
284
331
  auth
@@ -286,14 +333,14 @@ export function createAuthCommand(deps = {}) {
286
333
  .addHelpText('after', GLOBAL_OPTS_HINT)
287
334
  .action(async (_cmdOpts, command) => {
288
335
  emitDeprecationNotice('auth logout', 'auth remove', deps.stderr);
289
- await runLogout(resolveCommonOptions(command), deps);
336
+ await runLogout(resolveCommonOptions(command, deps.env), deps);
290
337
  });
291
338
  return auth;
292
339
  }
293
- function resolveCommonOptions(command) {
340
+ function resolveCommonOptions(command, env) {
294
341
  const globals = command.optsWithGlobals();
295
342
  return {
296
- profile: globals.profile ?? 'default',
343
+ profile: resolveProfileName(globals.profile, env),
297
344
  output: resolveOutputMode(globals.output),
298
345
  endpointUrl: globals.endpointUrl,
299
346
  debug: globals.debug ?? false,
@@ -305,15 +352,4 @@ function resolveCommonOptions(command) {
305
352
  function makeOutput(mode, deps) {
306
353
  return new Output(mode, { stdout: deps.stdout, stderr: deps.stderr });
307
354
  }
308
- function validationError(field, message) {
309
- return ApiError.fromEnvelope({
310
- error: {
311
- code: 'VALIDATION_ERROR',
312
- message,
313
- nextAction: `Set ${field} and re-run.`,
314
- requestId: 'local',
315
- details: { field, reason: 'missing' },
316
- },
317
- });
318
- }
319
355
  //# sourceMappingURL=auth.js.map
@@ -2,6 +2,7 @@ import { type SpawnSyncReturns } from 'node:child_process';
2
2
  import { Command } from 'commander';
3
3
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
4
4
  import { type FetchImpl } from '../lib/http.js';
5
+ import { type DeploymentRecord, type LinkageStatus } from '../lib/ci-linkage.js';
5
6
  /** Platforms `ci init` can scaffold. One today; the positional arg leaves room. */
6
7
  declare const SUPPORTED_PLATFORMS: readonly ["github"];
7
8
  type Platform = (typeof SUPPORTED_PLATFORMS)[number];
@@ -18,10 +19,12 @@ export interface CiFs {
18
19
  readFile(target: string): Promise<string>;
19
20
  }
20
21
  /** Injectable subprocess runner (defaults to a real `spawnSync`), so tests never
21
- * shell out. Runs `git` (default-branch detection) and `gh` (optional secret set). */
22
+ * shell out. Runs `git` (default-branch detection), `gh` (optional secret set,
23
+ * deployment history) and `npx vercel` (`ci connect`). */
22
24
  export type SpawnImpl = (cmd: string, args: string[], opts: {
23
25
  input?: string;
24
26
  cwd?: string;
27
+ shell?: boolean;
25
28
  }) => SpawnSyncReturns<string>;
26
29
  export interface CiDeps {
27
30
  env?: NodeJS.ProcessEnv;
@@ -32,6 +35,10 @@ export interface CiDeps {
32
35
  cwd?: string;
33
36
  fs?: CiFs;
34
37
  spawn?: SpawnImpl;
38
+ /** Injected by `ci doctor --wait` tests so polling never really sleeps. */
39
+ sleep?: (ms: number) => Promise<void>;
40
+ /** OS seam for the Windows `npx` shim handling (defaults to `process.platform`). */
41
+ platform?: NodeJS.Platform;
35
42
  }
36
43
  type CommonOptions = FactoryCommonOptions;
37
44
  export interface CiInitOptions extends CommonOptions {
@@ -83,6 +90,84 @@ export declare function buildGithubWorkflow(input: {
83
90
  defaultBranch: string;
84
91
  }): string;
85
92
  export declare function runCiInit(opts: CiInitOptions, deps?: CiDeps): Promise<void>;
93
+ export interface CiDoctorOptions extends CommonOptions {
94
+ repo?: string;
95
+ /** Poll until a NEW deployment record arrives (the post-connect check). */
96
+ wait: boolean;
97
+ /** Bound for `--wait`, in seconds; undefined = `--timeout` was not given. */
98
+ waitTimeoutSeconds?: number;
99
+ }
100
+ export interface CiDoctorSummary {
101
+ repo: string;
102
+ status: LinkageStatus;
103
+ ok: boolean;
104
+ detail: string;
105
+ lastDeployAt: string | null;
106
+ creators: string[];
107
+ hasPreview: boolean;
108
+ /** Whether this run watched for a new record (`--wait`). */
109
+ waited: boolean;
110
+ /** `--wait` only: the record whose arrival ended the wait, or null. */
111
+ newDeployment: DeploymentRecord | null;
112
+ /** Set when history could not be read at all — then the rest is not a verdict. */
113
+ error: string | null;
114
+ }
115
+ /**
116
+ * `owner/repo` for the check: the explicit `--repo`, else the `origin` remote.
117
+ * Returns null when neither resolves — the caller turns that into guidance
118
+ * rather than an opaque failure.
119
+ */
120
+ export declare function resolveRepoSlug(explicit: string | undefined, cwd: string, spawn: SpawnImpl): string | null;
121
+ /**
122
+ * Diagnose whether deployment events reach this repo — the precondition every
123
+ * deployment-gated workflow rests on, and the only one that fails *silently*.
124
+ *
125
+ * Exits non-zero when the chain is not live, so a script (or `ci init`) can
126
+ * gate on it. `--wait` makes the post-connect verification one command instead
127
+ * of "go watch GitHub yourself": it baselines the history on the first read and
128
+ * succeeds when a NEW record arrives. That success condition is a hard fact,
129
+ * deliberately independent of the preview/production heuristic — pushing to a
130
+ * default branch produces a *production* deployment, and that still proves the
131
+ * link is live.
132
+ */
133
+ export declare function runCiDoctor(opts: CiDoctorOptions, deps?: CiDeps): Promise<void>;
134
+ export declare function renderCiDoctorText(s: CiDoctorSummary): string;
135
+ export interface CiConnectOptions extends CommonOptions {
136
+ /** Vercel project to link when this directory is not linked yet. */
137
+ project?: string;
138
+ }
139
+ export interface CiConnectSummary {
140
+ platform: 'vercel';
141
+ /** The commands that were actually spawned, in order — no secrets in them. */
142
+ ran: string[];
143
+ connected: boolean;
144
+ alreadyConnected: boolean;
145
+ reason: string | null;
146
+ }
147
+ /**
148
+ * Link the deploy platform to the repo — the fix for `ci doctor`'s `none`.
149
+ *
150
+ * Runs the platform's OWN CLI as a subprocess (`npx vercel …`, so nothing needs
151
+ * pre-installing) rather than calling Vercel's API ourselves. That is a
152
+ * deliberate boundary: any other approach would require the user to hand us a
153
+ * Vercel token, and a third-party credential should never pass through this
154
+ * CLI. Vercel's CLI keeps its own credentials; we only read exit codes.
155
+ *
156
+ * Every step runs `--non-interactive`, and `--yes` is NEVER passed to the
157
+ * Vercel CLI on any path. `--yes` does not mean "skip confirmations": on an
158
+ * unlinked directory `vercel link --yes` answers the new-project questions
159
+ * with the default scope and the current directory name — creating a project
160
+ * nobody asked for, which `git connect` then wires the repo to and starts
161
+ * deploying. `ci doctor` would report that as `linked`: the exact silent
162
+ * false-green this command exists to prevent. When Vercel needs a decision it
163
+ * refuses with a structured reason instead, and that is relayed.
164
+ *
165
+ * `vercel git connect` is effectively idempotent — an already-connected repo
166
+ * says so, which also resolves the one ambiguity `ci doctor` cannot see from
167
+ * GitHub: "never linked" vs "linked but never deployed".
168
+ */
169
+ export declare function runCiConnect(opts: CiConnectOptions, deps?: CiDeps): Promise<void>;
170
+ export declare function renderCiConnectText(s: CiConnectSummary): string;
86
171
  export declare function renderCiInitText(s: CiInitSummary): string;
87
172
  export declare function createCiCommand(deps?: CiDeps): Command;
88
173
  export {};