@testsprite/testsprite-cli 0.4.0 → 0.6.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 (56) hide show
  1. package/README.md +27 -1
  2. package/dist/commands/agent.js +17 -6
  3. package/dist/commands/auth.d.ts +46 -0
  4. package/dist/commands/auth.js +37 -2
  5. package/dist/commands/completion.d.ts +36 -0
  6. package/dist/commands/completion.js +111 -0
  7. package/dist/commands/doctor.js +20 -2
  8. package/dist/commands/init.d.ts +32 -1
  9. package/dist/commands/init.js +40 -10
  10. package/dist/commands/project.d.ts +77 -3
  11. package/dist/commands/project.js +176 -43
  12. package/dist/commands/test.d.ts +200 -10
  13. package/dist/commands/test.js +1636 -351
  14. package/dist/commands/usage.d.ts +56 -17
  15. package/dist/commands/usage.js +144 -29
  16. package/dist/index.js +132 -26
  17. package/dist/lib/browser.d.ts +6 -0
  18. package/dist/lib/browser.js +54 -0
  19. package/dist/lib/bundle.d.ts +32 -31
  20. package/dist/lib/bundle.js +125 -83
  21. package/dist/lib/client-factory.d.ts +23 -0
  22. package/dist/lib/client-factory.js +33 -1
  23. package/dist/lib/config.js +7 -3
  24. package/dist/lib/credentials.d.ts +17 -1
  25. package/dist/lib/credentials.js +175 -16
  26. package/dist/lib/dry-run/samples.js +15 -1
  27. package/dist/lib/errors.d.ts +6 -1
  28. package/dist/lib/errors.js +70 -19
  29. package/dist/lib/flaky.d.ts +12 -1
  30. package/dist/lib/flaky.js +7 -12
  31. package/dist/lib/gh-output.d.ts +84 -0
  32. package/dist/lib/gh-output.js +202 -0
  33. package/dist/lib/http.d.ts +33 -15
  34. package/dist/lib/http.js +141 -7
  35. package/dist/lib/org-render.d.ts +52 -0
  36. package/dist/lib/org-render.js +59 -0
  37. package/dist/lib/poll.js +72 -36
  38. package/dist/lib/render-error.d.ts +14 -0
  39. package/dist/lib/render-error.js +30 -0
  40. package/dist/lib/response-schemas.d.ts +83 -0
  41. package/dist/lib/response-schemas.js +282 -0
  42. package/dist/lib/runs.types.d.ts +53 -8
  43. package/dist/lib/skill-nudge.d.ts +17 -0
  44. package/dist/lib/skill-nudge.js +19 -0
  45. package/dist/lib/telemetry.d.ts +90 -0
  46. package/dist/lib/telemetry.js +171 -0
  47. package/dist/lib/text-table.d.ts +14 -0
  48. package/dist/lib/text-table.js +45 -0
  49. package/dist/lib/v3-advisory.d.ts +30 -1
  50. package/dist/lib/v3-advisory.js +35 -4
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +17 -5
  54. package/schemas/plan.schema.json +61 -0
  55. package/skills/testsprite-verify.codex.md +2 -2
  56. package/skills/testsprite-verify.skill.md +3 -3
@@ -2,39 +2,38 @@
2
2
  * `testsprite usage` — show the account's credit balance and plan/entitlement
3
3
  * info as a proactive pre-flight before a large `test run` fan-out.
4
4
  *
5
- * Backend note: the `GET /me` endpoint does NOT currently return credit balance
6
- * or plan info. This command calls `/me` for auth-identity fields and surfaces
7
- * the `credits` / `subPlan` fields when and only when the backend supplies them
8
- * (forward-compat / absent-safe). A dedicated backend endpoint is a required
9
- * follow-up.
10
- *
11
- * BACKEND FOLLOW-UP REQUIRED:
12
- * Add `credits`, `subPlan` to the `/me` response, or add a dedicated
13
- * `GET /api/cli/v1/usage` endpoint returning `{ credits, subPlan, creditsPerRun }`.
5
+ * Backend note: `GET /me` now includes the `credits` / `subPlan` projection
6
+ * (this shipped; the CLI's old "requires a backend update"
7
+ * wording is stale and was removed). This command calls `/me` and surfaces
8
+ * the `credits` / `subPlan` / `creditsPerRun` fields when and only when the
9
+ * backend response includes them — kept absent-safe/forward-compat since not
10
+ * every account shape is guaranteed to populate all three (e.g. `creditsPerRun`
11
+ * has no server-side source at all today).
14
12
  */
15
13
  import { Command } from 'commander';
16
14
  import { type CommonOptions as FactoryCommonOptions } from '../lib/client-factory.js';
17
15
  import type { FetchImpl } from '../lib/http.js';
16
+ import type { CliOrgBinding, CliOrgSummary } from '../lib/org-render.js';
18
17
  /**
19
18
  * Usage/balance response from `/me` (when the backend supplies it) or a future
20
19
  * `/usage` endpoint.
21
20
  *
22
- * All fields except `userId`/`keyId`/`env` are forward-compat: the backend
23
- * does not return them today. They are rendered only when present.
21
+ * `credits` / `subPlan` now ship on `/me` (live). Still
22
+ * kept optional/absent-safe: `userId`/`keyId`/`env` are the only fields every
23
+ * backend and account shape is guaranteed to populate.
24
24
  */
25
25
  export interface UsageResponse {
26
26
  userId: string;
27
27
  keyId: string;
28
28
  env: 'development' | 'staging' | 'production';
29
29
  /**
30
- * Remaining credit balance. Present only when the backend /me (or /usage)
31
- * includes the User.credits projection. BACKEND FOLLOW-UP: me.controller.ts.
30
+ * Remaining credit balance. Present when the backend /me (or /usage)
31
+ * includes the User.credits projection (live).
32
32
  */
33
33
  credits?: number;
34
34
  /**
35
- * Subscription plan name (e.g. "Free", "Standard", "Pro"). Present only when
36
- * the backend /me (or /usage) includes the User.subPlan projection.
37
- * BACKEND FOLLOW-UP: me.controller.ts.
35
+ * Subscription plan name (e.g. "Free", "Standard", "Pro"). Present when
36
+ * the backend /me (or /usage) includes the User.subPlan projection (live).
38
37
  */
39
38
  subPlan?: string;
40
39
  /**
@@ -42,6 +41,45 @@ export interface UsageResponse {
42
41
  * backend supplies it.
43
42
  */
44
43
  creditsPerRun?: number;
44
+ /**
45
+ * The caller's organization wallet — the billing subject on org-based
46
+ * accounts. Rendered only together with `v3Enabled: true` (see
47
+ * `renderUsage`): the org wallet supersedes the legacy `credits`/`subPlan`
48
+ * pair only for callers whose commands actually bill it. Absent-safe like
49
+ * every other optional field.
50
+ */
51
+ activeOrg?: ActiveOrg;
52
+ /**
53
+ * Authoritative per-caller routing bit: true when this caller's commands
54
+ * run (and bill) on the V3 platform. Always present on current backends;
55
+ * absent on older ones.
56
+ */
57
+ v3Enabled?: boolean;
58
+ /**
59
+ * Every organization the underlying user belongs to (account-wide
60
+ * membership list, personal org included). Absent-safe: omitted on a
61
+ * server-side lookup failure or an older backend.
62
+ */
63
+ organizations?: CliOrgSummary[];
64
+ /**
65
+ * The calling key's own org binding. Present only when the request
66
+ * authenticated with a Postgres-backed membership key (`sk-member-…`).
67
+ */
68
+ org?: CliOrgBinding;
69
+ }
70
+ /** Slim org-wallet view shipped on `/me` (see the backend `Me` schema). */
71
+ export interface ActiveOrg {
72
+ id: string;
73
+ name: string;
74
+ /** Org plan (`Free` | `Starter` | `Standard`). */
75
+ plan: string;
76
+ /** Caller's role in the org (`owner` | `admin` | `member`). */
77
+ role: string;
78
+ /** Spendable balance: the caller's member bucket + the org's shared top-up pool. */
79
+ remaining: number;
80
+ /** Monthly per-seat credit allowance for the org's plan. */
81
+ includedCredits: number;
82
+ seats: number;
45
83
  }
46
84
  export interface UsageDeps {
47
85
  env?: NodeJS.ProcessEnv;
@@ -56,7 +94,8 @@ export declare const DRY_RUN_USAGE_SAMPLE: UsageResponse;
56
94
  /**
57
95
  * Run the `usage` command. Calls `GET /me`, surfaces identity + any
58
96
  * credits/plan fields the backend supplies. Absent fields are silently
59
- * omitted (forward-compat until the backend adds the projection).
97
+ * omitted (forward-compat in case a given account/backend version doesn't
98
+ * populate them).
60
99
  */
61
100
  export declare function runUsage(opts: CommonOptions, deps?: UsageDeps): Promise<UsageResponse>;
62
101
  export declare function createUsageCommand(deps?: UsageDeps): Command;
@@ -2,20 +2,19 @@
2
2
  * `testsprite usage` — show the account's credit balance and plan/entitlement
3
3
  * info as a proactive pre-flight before a large `test run` fan-out.
4
4
  *
5
- * Backend note: the `GET /me` endpoint does NOT currently return credit balance
6
- * or plan info. This command calls `/me` for auth-identity fields and surfaces
7
- * the `credits` / `subPlan` fields when and only when the backend supplies them
8
- * (forward-compat / absent-safe). A dedicated backend endpoint is a required
9
- * follow-up.
10
- *
11
- * BACKEND FOLLOW-UP REQUIRED:
12
- * Add `credits`, `subPlan` to the `/me` response, or add a dedicated
13
- * `GET /api/cli/v1/usage` endpoint returning `{ credits, subPlan, creditsPerRun }`.
5
+ * Backend note: `GET /me` now includes the `credits` / `subPlan` projection
6
+ * (this shipped; the CLI's old "requires a backend update"
7
+ * wording is stale and was removed). This command calls `/me` and surfaces
8
+ * the `credits` / `subPlan` / `creditsPerRun` fields when and only when the
9
+ * backend response includes them — kept absent-safe/forward-compat since not
10
+ * every account shape is guaranteed to populate all three (e.g. `creditsPerRun`
11
+ * has no server-side source at all today).
14
12
  */
15
13
  import { Command } from 'commander';
16
14
  import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, } from '../lib/client-factory.js';
17
15
  import { loadConfig } from '../lib/config.js';
18
16
  import { resolvePortalBase } from '../lib/facade.js';
17
+ import { formatOrgBinding, formatOrgsSummary } from '../lib/org-render.js';
19
18
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
20
19
  /** Dry-run canned response — matches what the real /me + User lookup would return. */
21
20
  export const DRY_RUN_USAGE_SAMPLE = {
@@ -25,18 +24,29 @@ export const DRY_RUN_USAGE_SAMPLE = {
25
24
  credits: 42,
26
25
  subPlan: 'Standard',
27
26
  creditsPerRun: 2,
27
+ v3Enabled: true,
28
+ activeOrg: {
29
+ id: '22222222-2222-4222-8222-222222222222',
30
+ name: 'Dry Run Workspace',
31
+ plan: 'Standard',
32
+ role: 'owner',
33
+ remaining: 1650,
34
+ includedCredits: 1600,
35
+ seats: 1,
36
+ },
28
37
  };
29
38
  /**
30
39
  * Run the `usage` command. Calls `GET /me`, surfaces identity + any
31
40
  * credits/plan fields the backend supplies. Absent fields are silently
32
- * omitted (forward-compat until the backend adds the projection).
41
+ * omitted (forward-compat in case a given account/backend version doesn't
42
+ * populate them).
33
43
  */
34
44
  export async function runUsage(opts, deps = {}) {
35
45
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
36
46
  const out = makeOutput(opts.output, deps);
37
47
  if (opts.dryRun) {
38
48
  emitDryRunBanner(stderr);
39
- stderr('[note] credit balance requires a backend update — showing dry-run sample values');
49
+ stderr('[note] --dry-run showing canned sample values, not your real balance');
40
50
  out.print(DRY_RUN_USAGE_SAMPLE, data => renderUsage(data));
41
51
  return DRY_RUN_USAGE_SAMPLE;
42
52
  }
@@ -59,28 +69,109 @@ export async function runUsage(opts, deps = {}) {
59
69
  const billingUrl = portalBase !== undefined
60
70
  ? `${portalBase}/dashboard/settings/billing`
61
71
  : 'the portal Billing page (/dashboard/settings/billing)';
62
- // /me is the only available source of credits/plan today.
63
- // When the backend adds credits/subPlan to MeResponse (or adds /usage),
64
- // this single get call is sufficient — no code change needed in the CLI.
72
+ // /me is the only available source of credits/plan today. If the backend
73
+ // adds a dedicated /usage endpoint later, this single get call is where
74
+ // it would be swapped in — no other code change needed in the CLI.
65
75
  const me = await client.get('/me');
66
76
  out.print(me, data => renderUsage(data, portalBase));
67
- // In text mode, emit a backend-gap note when credits are missing so the
68
- // user knows why the balance isn't shown (instead of assuming zero or error).
69
- if (opts.output === 'text' && me.credits === undefined) {
70
- stderr('[note] credit balance not available — backend does not yet expose credits on /me.' +
71
- ` Check ${billingUrl} for your current balance.`);
77
+ // In text mode, emit a note when NO balance was shown at all — neither the
78
+ // legacy per-user `credits` nor an org wallet. A V3-routed org account can
79
+ // legitimately have no DDB `credits` field (org-native members never get a
80
+ // legacy user row), and its balance already rendered in the organization
81
+ // block — the note would contradict the output right above it.
82
+ //
83
+ // "Is this key org-bound" and "do I have a balance number to show" are two
84
+ // different questions and must not be conflated. `me.org` is the key's own
85
+ // binding — always present, no I/O, populated whenever the request
86
+ // authenticated with a membership key (`sk-member-…`). `activeOrg` is the
87
+ // *enriched* org balance: the backend does a best-effort Postgres read for
88
+ // it and swallows the exception on failure, so `org` can be present while
89
+ // `activeOrg` (and, for a V3-native user with no legacy DynamoDB row,
90
+ // `credits` too) is absent. Deciding org-boundedness from `activeOrg`
91
+ // (i.e. `orgWalletShown`) alone means that degraded state falls through to
92
+ // this personal-billing note — pointing an org-key operator at the wrong
93
+ // wallet in exactly the situation this whole surface exists to prevent.
94
+ const isOrgBound = me.org !== undefined;
95
+ const orgWalletShown = me.v3Enabled === true && me.activeOrg !== undefined;
96
+ if (opts.output === 'text' && me.credits === undefined && !orgWalletShown) {
97
+ stderr(isOrgBound
98
+ ? "[note] this key is organization-bound, but the org balance could not be loaded right now. Retry `testsprite usage`, or check the Portal's organization billing settings (ask an org admin if you don't have access)."
99
+ : `[note] credit balance not returned for this account. Check ${billingUrl} for your current balance.`);
72
100
  }
73
101
  return me;
74
102
  }
103
+ /**
104
+ * Org-wallet low-balance threshold: the cost of a generation action —
105
+ * the priciest common single action on org billing. Below this, the next
106
+ * AI-assisted operation may fail; cheaper actions can still succeed.
107
+ */
108
+ const LOW_ORG_BALANCE_CREDITS = 2;
75
109
  function renderUsage(u, portalBase) {
76
110
  const lines = [];
77
111
  // Identity block (always present)
78
112
  lines.push(`userId: ${u.userId}`);
79
113
  lines.push(`keyId: ${u.keyId}`);
80
114
  lines.push(`env: ${u.env}`);
81
- // Balance block — shown only when the backend supplies it
115
+ // Org attribution — rendered only when the backend supplies it.
116
+ const orgsSummary = formatOrgsSummary(u.organizations);
117
+ if (orgsSummary)
118
+ lines.push(`orgs: ${orgsSummary}`);
119
+ const orgBinding = formatOrgBinding(u.org);
120
+ if (orgBinding)
121
+ lines.push(`org binding: ${orgBinding}`);
122
+ // Whether the CALLING KEY is org-bound — read from `u.org` (the key's own
123
+ // membership binding: always present, no I/O, populated whenever the
124
+ // request authenticated with a `sk-member-…` key), NOT from `activeOrg`.
125
+ // `activeOrg` is the *enriched* org balance: the backend does a best-effort
126
+ // Postgres read for it and swallows the exception on failure, so a caller
127
+ // can be genuinely org-bound (`org` present) while `activeOrg` — and, for a
128
+ // V3-native user with no legacy DynamoDB row, `credits` too — is absent.
129
+ // "Is this key org-bound" and "do I have a balance number to show" are two
130
+ // different questions; conflating them (deciding org-boundedness from
131
+ // `orgWallet`/`activeOrg` alone) sends a degraded-enrichment org caller
132
+ // down the personal-wallet branches below.
133
+ const isOrgBound = u.org !== undefined;
134
+ // Org wallet block — the billing subject on org-based accounts. Rendered
135
+ // only when the caller is actually V3-routed: `v3Enabled` is the
136
+ // authoritative routing bit, so wallet selection never rests on field
137
+ // presence alone. A V2-routed caller keeps the legacy block below (their
138
+ // billable commands still charge the legacy wallet); older backends send
139
+ // neither field and degrade the same way.
140
+ // `?? undefined` also normalizes a hypothetical explicit `null` from the
141
+ // wire so the block below can't dereference it.
142
+ const orgWallet = u.v3Enabled === true ? (u.activeOrg ?? undefined) : undefined;
143
+ if (orgWallet !== undefined) {
144
+ const org = orgWallet;
145
+ lines.push('');
146
+ lines.push('--- organization ---');
147
+ lines.push(`org: ${org.name} (${org.role})`);
148
+ lines.push(`plan: ${org.plan}`);
149
+ // Labeled `balance:` (not `credits:`) — `--output json` exposes the
150
+ // legacy per-user number under `.credits`, and giving the org wallet the
151
+ // same label in text mode would make one word mean two different values.
152
+ lines.push(`balance: ${org.remaining} remaining (${org.includedCredits}/mo per seat)`);
153
+ lines.push(`seats: ${org.seats}`);
154
+ // No "~N runs" estimate here: org billing prices actions individually and
155
+ // the API does not expose a per-run rate for the org wallet — an estimate
156
+ // computed from the legacy frontend rate would be wrong.
157
+ }
158
+ else if (isOrgBound) {
159
+ // Org-bound key, but the enrichment that would have populated `activeOrg`
160
+ // degraded (best-effort Postgres read failed server-side, or `v3Enabled`
161
+ // itself couldn't be resolved). Say so honestly — never fall through to
162
+ // the legacy per-user blocks below (this key's commands bill the org
163
+ // wallet, not the personal one, regardless of whether we could load its
164
+ // number just now), and never fabricate an org-scoped URL.
165
+ lines.push('');
166
+ lines.push('--- organization ---');
167
+ lines.push("balance: could not be loaded right now. Retry `testsprite usage`, or check the Portal's organization billing settings (ask an org admin if you don't have access).");
168
+ }
169
+ // Legacy balance block — shown only when the backend supplies it, no org
170
+ // wallet superseded it (older backends / V2-routed accounts), AND the key
171
+ // isn't org-bound (an org-bound key's commands never charge these numbers,
172
+ // even if a legacy row happens to still carry them).
82
173
  const hasBalanceData = u.credits !== undefined || u.subPlan !== undefined;
83
- if (hasBalanceData) {
174
+ if (orgWallet === undefined && !isOrgBound && hasBalanceData) {
84
175
  lines.push('');
85
176
  lines.push('--- credits & plan ---');
86
177
  if (u.subPlan !== undefined) {
@@ -91,7 +182,7 @@ function renderUsage(u, portalBase) {
91
182
  }
92
183
  if (u.creditsPerRun !== undefined) {
93
184
  lines.push(`cost per frontend run: ${u.creditsPerRun} credit(s)`);
94
- // Backend runs DO consume credits (confirmed by design 2026-06-30 / DEV-289).
185
+ // Backend runs DO consume credits (confirmed by design 2026-06-30).
95
186
  // The API exposes no backend-specific per-run cost field, and it differs from
96
187
  // the frontend rate, so state that it bills without asserting a possibly-wrong
97
188
  // number — check your balance before/after, or see the billing page.
@@ -103,13 +194,35 @@ function renderUsage(u, portalBase) {
103
194
  lines.push(`can trigger: ~${maxRuns} run(s) at current balance`);
104
195
  }
105
196
  }
106
- // Actionable upgrade line for Free or low-balance keys
107
- const isLowBalance = u.credits !== undefined && u.creditsPerRun !== undefined && u.credits < u.creditsPerRun;
108
- const isFree = u.subPlan?.toLowerCase() === 'free';
197
+ // Actionable upgrade line for Free or low-balance keys. Prefer the org
198
+ // wallet's plan/balance when present. `!isOrgBound` guards the personal
199
+ // branch of each: an org-bound key with degraded enrichment has no
200
+ // `orgWallet` to compute from, but must not fall back to reading `u.credits`
201
+ // / `u.subPlan` either (a legacy row that happens to coexist with an org
202
+ // binding is not what this key's commands actually bill).
203
+ const isLowBalance = orgWallet !== undefined
204
+ ? orgWallet.remaining < LOW_ORG_BALANCE_CREDITS
205
+ : !isOrgBound &&
206
+ u.credits !== undefined &&
207
+ u.creditsPerRun !== undefined &&
208
+ u.credits < u.creditsPerRun;
209
+ const isFree = orgWallet !== undefined
210
+ ? orgWallet.plan.toLowerCase() === 'free'
211
+ : !isOrgBound && u.subPlan?.toLowerCase() === 'free';
109
212
  if (isLowBalance) {
110
213
  lines.push('');
111
- lines.push('warning: credit balance is below the per-run cost. Top up at:' +
112
- ` ${portalBase !== undefined ? `${portalBase}/dashboard/settings/billing` : 'the portal Billing page (/dashboard/settings/billing)'}`);
214
+ // The org wallet is billed under the ORGANIZATION's own settings, not the
215
+ // personal `/dashboard/settings/billing` page (that page manages the
216
+ // legacy per-user DDB balance, a different column entirely) — so the
217
+ // org branch deliberately does not point at that URL. No org-scoped
218
+ // settings URL is fabricated here either: the CLI has no confirmed route
219
+ // for one, so "ask an org admin" is the honest next step.
220
+ lines.push(orgWallet !== undefined
221
+ ? // Org billing prices actions individually, and cheaper actions (e.g.
222
+ // a 1-credit backend run) may still succeed below the threshold —
223
+ // so this is "low", not "cannot run".
224
+ `warning: organization balance is low (under the ${LOW_ORG_BALANCE_CREDITS}-credit cost of a generation action). Top up in the Portal's organization billing settings (ask an org admin if you don't have access).`
225
+ : `warning: credit balance is below the per-run cost. Top up at: ${portalBase !== undefined ? `${portalBase}/dashboard/settings/billing` : 'the portal Billing page (/dashboard/settings/billing)'}`);
113
226
  }
114
227
  else if (isFree) {
115
228
  lines.push('');
@@ -132,8 +245,10 @@ export function createUsageCommand(deps = {}) {
132
245
  ' 0 success (or --dry-run)\n' +
133
246
  ' 3 auth error — run `testsprite setup` to configure credentials\n' +
134
247
  ' 10 transport/network failure (UNAVAILABLE) — retry the command\n' +
135
- '\nNote: credit balance requires a backend update to /me. Until shipped,\n' +
136
- " check your portal's Billing page (/dashboard/settings/billing) for your balance.")
248
+ "\nNote: if credit balance isn't shown for your account, check your portal's\n" +
249
+ ' Billing page (/dashboard/settings/billing) for a personal key, or your\n' +
250
+ ' organization billing settings (ask an org admin) if this key is\n' +
251
+ ' organization-bound.')
137
252
  .action(async (_cmdOpts, command) => {
138
253
  await runUsage(resolveCommonOptions(command), deps);
139
254
  });
package/dist/index.js CHANGED
@@ -2,17 +2,20 @@
2
2
  import { Command, CommanderError } from 'commander';
3
3
  import { createAgentCommand } from './commands/agent.js';
4
4
  import { createAuthCommand } from './commands/auth.js';
5
+ import { createCompletionCommand } from './commands/completion.js';
5
6
  import { createDoctorCommand } from './commands/doctor.js';
6
- import { createDeprecatedInitCommand, createSetupCommand, runConfigureViaSetup, } from './commands/init.js';
7
+ import { addSetupOptions, createDeprecatedInitCommand, createSetupCommand, runConfigureViaSetup, } from './commands/init.js';
7
8
  import { createProjectCommand } from './commands/project.js';
8
9
  import { createTestCommand } from './commands/test.js';
9
10
  import { createUsageCommand } from './commands/usage.js';
11
+ import { TARGETS } from './lib/agent-targets.js';
10
12
  import { ApiError, CLIError, InterruptError, RequestTimeoutError } from './lib/errors.js';
11
13
  import { installBrokenPipeGuard, installSignalHandlers } from './lib/interrupt.js';
12
14
  import { Output, isOutputMode } from './lib/output.js';
13
15
  import { maybeInstallProxyAgent } from './lib/proxy.js';
14
- import { renderCommanderError, rephraseUnknownOption } from './lib/render-error.js';
15
- import { maybeEmitSkillNudge } from './lib/skill-nudge.js';
16
+ import { renderAmbiguousOrgCandidates, renderCommanderError, rephraseUnknownOption, } from './lib/render-error.js';
17
+ import { isPlanTemplateInvocation, maybeEmitSkillNudge } from './lib/skill-nudge.js';
18
+ import { classifyCliError, isTelemetryOptedOut, recordOutcome, resolveTelemetryAuth, } from './lib/telemetry.js';
16
19
  import { maybeNotifyUpdate } from './lib/update-check.js';
17
20
  import { VERSION } from './version.js';
18
21
  import { shouldRejectNodeVersion } from './version-guard.js';
@@ -48,14 +51,16 @@ program.addCommand(createDeprecatedInitCommand({}), { hidden: true });
48
51
  // `auth configure` is a hidden, deprecated alias that runs FULL `setup`
49
52
  // (configure + skill install), so an agent reaching for the old command still
50
53
  // ends up with the skill. `setup` remains the ONLY path that writes credentials.
54
+ // Attach the SAME flag set `setup` has (previously only
55
+ // `--from-env` was wired up, so README's "runs the full setup" claim didn't
56
+ // hold — `--yes`/`--agent`/`--api-key`/`--force`/`--dir`/`--no-agent` were all
57
+ // rejected as `unknown option`).
51
58
  const authCommand = createAuthCommand();
52
- authCommand
53
- .command('configure', { hidden: true })
54
- .option('--from-env', 'Read TESTSPRITE_API_KEY (and optionally TESTSPRITE_API_URL) from the environment instead of prompting', false)
55
- .action(async (cmdOpts, command) => {
59
+ const authConfigureValidTargets = Object.keys(TARGETS);
60
+ addSetupOptions(authCommand.command('configure', { hidden: true }), authConfigureValidTargets, 'claude').action(async (cmdOpts, command) => {
56
61
  process.stderr.write('[deprecated] `testsprite auth configure` now runs full setup (configure + skill install) — ' +
57
62
  'use `testsprite setup` (add --no-agent to skip the skill).\n');
58
- await runConfigureViaSetup(command, {}, Boolean(cmdOpts.fromEnv));
63
+ await runConfigureViaSetup(command, {}, cmdOpts);
59
64
  });
60
65
  program.addCommand(authCommand);
61
66
  program.addCommand(createProjectCommand({}));
@@ -63,11 +68,45 @@ program.addCommand(createTestCommand());
63
68
  program.addCommand(createAgentCommand({}));
64
69
  program.addCommand(createUsageCommand());
65
70
  program.addCommand(createDoctorCommand());
71
+ program.addCommand(createCompletionCommand(() => buildCompletionSpec()));
72
+ // Derive the shell-completion spec from the fully-assembled command tree at call
73
+ // time (not module-load), so `testsprite completion` can never drift from the
74
+ // real commands, subcommands, and global flags.
75
+ function buildCompletionSpec() {
76
+ const subcommands = {};
77
+ for (const command of program.commands) {
78
+ const subs = command.commands.map(sub => sub.name()).filter(name => name !== 'help');
79
+ if (subs.length > 0)
80
+ subcommands[command.name()] = subs;
81
+ }
82
+ const flags = program.options
83
+ .map(option => option.long)
84
+ .filter((long) => typeof long === 'string');
85
+ if (!flags.includes('--help'))
86
+ flags.push('--help');
87
+ return {
88
+ program: 'testsprite',
89
+ commands: [...new Set([...program.commands.map(command => command.name()), 'help'])],
90
+ subcommands,
91
+ globalFlags: flags,
92
+ };
93
+ }
66
94
  // Buffer Commander error messages instead of writing immediately. The catch
67
95
  // block re-emits in the correct format (JSON or text) once the requested
68
96
  // output mode is known. Safe because applyExitOverrideDeep ensures every
69
97
  // command throws CommanderError rather than calling process.exit directly.
70
98
  let pendingCommanderErrorMsg = null;
99
+ // Leaf command path that actually reached an action (set by the preAction hook
100
+ // below). Empty when no action ran (bare `--help`, parse error) — telemetry
101
+ // skips those. Read by the success + error telemetry emits around parseAsync.
102
+ let ranCommandPath = '';
103
+ // Whether the command that ran should emit telemetry. `completion` (its stdout
104
+ // is eval'd by shells) and `--plan-template` (pure-local) are kept off the
105
+ // beacon, same as the update notice. Set by the preAction hook.
106
+ let telemetryEmit = false;
107
+ // Auth resolved in the preAction hook, before the command's action runs, so
108
+ // `auth remove` (which deletes the profile) is still reported on the key it used.
109
+ let telemetryAuth;
71
110
  // Propagate exitOverride AND the buffered outputError config to every
72
111
  // subcommand in the tree. Commander's addCommand() does NOT inherit either
73
112
  // from the parent, so commands built externally (createTestCommand, etc.) and
@@ -100,6 +139,11 @@ function commandPathOf(cmd) {
100
139
  }
101
140
  return names.join(' ');
102
141
  }
142
+ /** Global flags the telemetry emit needs (config resolution + context). */
143
+ function telemetryGlobals() {
144
+ const g = program.opts();
145
+ return { profile: g.profile, endpointUrl: g.endpointUrl, output: g.output, dryRun: g.dryRun };
146
+ }
103
147
  // Best-effort onboarding nudge (see lib/skill-nudge.ts): when a configured
104
148
  // caller drives a verify-loop command in a project with no installed skill,
105
149
  // point it at `testsprite setup`. A preAction hook runs before every leaf
@@ -108,20 +152,44 @@ function commandPathOf(cmd) {
108
152
  program.hook('preAction', (_thisCommand, actionCommand) => {
109
153
  const globals = actionCommand.optsWithGlobals();
110
154
  const commandPath = commandPathOf(actionCommand);
111
- maybeEmitSkillNudge({
112
- commandPath,
113
- output: isOutputMode(globals.output) ? globals.output : 'text',
114
- dryRun: globals.dryRun ?? false,
115
- profile: globals.profile ?? 'default',
116
- cwd: process.cwd(),
117
- env: process.env,
118
- });
155
+ // Record which leaf command ran, for the telemetry emit around parseAsync.
156
+ ranCommandPath = commandPath;
157
+ // See `isPlanTemplateInvocation` for why this one case is
158
+ // filtered here rather than in skill-nudge.ts / update-check.ts.
159
+ const isPlanTemplate = isPlanTemplateInvocation(commandPath, globals.planTemplate);
160
+ // Telemetry gate, same reasons as the update notice below: skip `completion`
161
+ // (its stdout is eval'd by shells) and `--plan-template` (pure-local). Resolve
162
+ // auth now, before the command's action runs, so `auth remove` still reports
163
+ // on the key it used; skip the read for opt-out / dry-run.
164
+ telemetryEmit = commandPath !== 'completion' && !isPlanTemplate;
165
+ if (telemetryEmit && !isTelemetryOptedOut(process.env) && globals.dryRun !== true) {
166
+ telemetryAuth = resolveTelemetryAuth({
167
+ profile: globals.profile,
168
+ endpointUrl: globals.endpointUrl,
169
+ });
170
+ }
171
+ if (!isPlanTemplate) {
172
+ maybeEmitSkillNudge({
173
+ commandPath,
174
+ output: isOutputMode(globals.output) ? globals.output : 'text',
175
+ dryRun: globals.dryRun ?? false,
176
+ profile: globals.profile ?? 'default',
177
+ cwd: process.cwd(),
178
+ env: process.env,
179
+ });
180
+ }
119
181
  // Best-effort update notice (see lib/update-check.ts): self-gates on the
120
182
  // opt-out env, CI, TTY, and a 24h cache; the wiring adds the flag-level
121
183
  // gates the lib cannot see. Skipped for `completion` (its stdout is eval'd
122
- // by shells), under --output json, and under --dry-run. Deliberately not
123
- // awaited: an advisory must never delay the real command.
124
- if (globals.output !== 'json' && globals.dryRun !== true && commandPath !== 'completion') {
184
+ // by shells), under --output json, under --dry-run, and for
185
+ // `--plan-template` (pure-local — this check hits the npm registry over
186
+ // the network and writes ~/.testsprite/update-check.json, both of which
187
+ // contradict "no network" for this flag). Deliberately not awaited: an
188
+ // advisory must never delay the real command.
189
+ if (globals.output !== 'json' &&
190
+ globals.dryRun !== true &&
191
+ commandPath !== 'completion' &&
192
+ !isPlanTemplate) {
125
193
  void maybeNotifyUpdate();
126
194
  }
127
195
  });
@@ -138,10 +206,40 @@ installBrokenPipeGuard();
138
206
  // Corporate/CI proxies: honor HTTPS_PROXY/HTTP_PROXY/NO_PROXY (Node's fetch
139
207
  // ignores them by default). No-op when no proxy variable is set.
140
208
  maybeInstallProxyAgent();
209
+ const telemetryStartedAt = Date.now();
141
210
  try {
142
211
  await program.parseAsync(process.argv);
212
+ // Flush a success outcome event before the process exits 0. Bounded +
213
+ // best-effort (see lib/telemetry.ts); skips when no command ran / no key
214
+ // configured / opted out / --dry-run.
215
+ if (telemetryEmit) {
216
+ await recordOutcome({
217
+ command: ranCommandPath,
218
+ outcome: 'success',
219
+ exitCode: 0,
220
+ durationMs: Date.now() - telemetryStartedAt,
221
+ ...telemetryGlobals(),
222
+ }, { resolvedAuth: telemetryAuth });
223
+ }
143
224
  }
144
225
  catch (err) {
226
+ const telemetryOutcome = classifyCliError(err);
227
+ // Flush the outcome AFTER the error is rendered to stderr below (via each
228
+ // branch's `flushThenExit`), so a slow backend never delays the user's error.
229
+ // The classification mirrors the exit-code mapping the branches apply.
230
+ const flushThenExit = async (code) => {
231
+ if (telemetryEmit) {
232
+ await recordOutcome({
233
+ command: ranCommandPath,
234
+ outcome: telemetryOutcome.outcome,
235
+ exitCode: telemetryOutcome.exitCode,
236
+ errorCode: telemetryOutcome.errorCode,
237
+ durationMs: Date.now() - telemetryStartedAt,
238
+ ...telemetryGlobals(),
239
+ }, { resolvedAuth: telemetryAuth });
240
+ }
241
+ process.exit(code);
242
+ };
145
243
  const rawMode = program.opts().output;
146
244
  const mode = isOutputMode(rawMode) ? rawMode : 'text';
147
245
  if (err instanceof ApiError) {
@@ -184,8 +282,16 @@ catch (err) {
184
282
  process.stderr.write(` your version: ${your}, minimum supported: ${min}\n`);
185
283
  }
186
284
  }
285
+ // AMBIGUOUS_ORG: the same testId resolved inside more than one of the
286
+ // caller's organizations. List each colliding candidate plus a hint to
287
+ // disambiguate, mirroring the AUTH_FORBIDDEN required/granted pattern above.
288
+ if (err.code === 'AMBIGUOUS_ORG') {
289
+ for (const line of renderAmbiguousOrgCandidates(err.getDetail('candidates'))) {
290
+ process.stderr.write(`${line}\n`);
291
+ }
292
+ }
187
293
  }
188
- process.exit(err.exitCode);
294
+ await flushThenExit(err.exitCode);
189
295
  }
190
296
  const output = new Output(mode);
191
297
  if (err instanceof InterruptError) {
@@ -210,7 +316,7 @@ catch (err) {
210
316
  else {
211
317
  process.stderr.write(`Error: ${err.message}\n`);
212
318
  }
213
- process.exit(err.exitCode);
319
+ await flushThenExit(err.exitCode);
214
320
  }
215
321
  if (err instanceof RequestTimeoutError) {
216
322
  // Structured rendering for per-request timeouts: JSON mode emits a
@@ -231,7 +337,7 @@ catch (err) {
231
337
  else {
232
338
  process.stderr.write(`Error: ${err.message}\n`);
233
339
  }
234
- process.exit(err.exitCode);
340
+ await flushThenExit(err.exitCode);
235
341
  }
236
342
  if (err instanceof CommanderError) {
237
343
  // Map exit codes per the CLI taxonomy:
@@ -250,7 +356,7 @@ catch (err) {
250
356
  if (err.code === 'commander.helpDisplayed' ||
251
357
  err.code === 'commander.help' ||
252
358
  err.code === 'commander.version') {
253
- process.exit(0);
359
+ await flushThenExit(0);
254
360
  }
255
361
  // For parse errors, write the buffered message in the correct format.
256
362
  // rawMode from program.opts() is reliable when --output was parsed before
@@ -270,13 +376,13 @@ catch (err) {
270
376
  return mode;
271
377
  })();
272
378
  process.stderr.write(renderCommanderError(pendingCommanderErrorMsg, err.message, commanderMode));
273
- process.exit(5);
379
+ await flushThenExit(5);
274
380
  }
275
381
  if (err instanceof CLIError) {
276
382
  output.error(err.message);
277
- process.exit(err.exitCode);
383
+ await flushThenExit(err.exitCode);
278
384
  }
279
385
  output.error(err instanceof Error ? err.message : String(err));
280
- process.exit(1);
386
+ await flushThenExit(1);
281
387
  }
282
388
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ export interface OpenInBrowserDeps {
2
+ platform?: NodeJS.Platform;
3
+ /** Process spawner taking an argv array. Defaults to a detached spawn. */
4
+ exec?: (command: string, args: readonly string[]) => void;
5
+ }
6
+ export declare function openInBrowser(url: string, deps?: OpenInBrowserDeps): void;