@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
@@ -19,13 +19,31 @@
19
19
  * would be cut off before delivery anyway).
20
20
  *
21
21
  * Privacy: the event is a fixed allowlist of low-cardinality, PII-free fields.
22
- * It NEVER carries target URLs, api keys, flag values, arg values, or error
23
- * messages — `errorCode` is a stable machine code, never the human message.
22
+ * It NEVER carries target URLs, api keys, arg values, error messages, or
23
+ * repository names — `errorCode` is a stable machine code, never the human
24
+ * message, and the CI repository is reduced to a salted, truncated hash so
25
+ * runs from one repo can be grouped without the slug ever leaving the runner.
26
+ * Flag-derived values are limited to bounded numeric controls:
27
+ * `timeoutSeconds` is the operator's timeout (not a URL or free text) and
28
+ * distinguishes a wait deadline from a slow backend; `localConcurrencyLimit`
29
+ * is an integer 1–10 and lets local batch outcomes be grouped by load.
30
+ * `localPeakInFlight` is the observed count, also bounded by that limit.
31
+ *
32
+ * `errorOrigin` ('client' | 'server') and `timeoutSeconds` are sent by this
33
+ * revision of the CLI. The telemetry endpoint validates against an allowlist
34
+ * and silently DROPS fields it does not declare rather than rejecting the
35
+ * request, so a server that predates these two fields accepts the event and
36
+ * discards them — inert, not an error. Declaring a field is also not enough
37
+ * on its own: the server has a separate mapping step onto the analytics
38
+ * event, so a field can pass validation and still not be recorded.
24
39
  */
40
+ import { createHash } from 'node:crypto';
25
41
  import { CommanderError } from 'commander';
42
+ import { buildUserAgent, resolveClientTag } from './client-tag.js';
43
+ import { dominantConflictReason } from './conflict-reason.js';
26
44
  import { loadConfig } from './config.js';
27
45
  import { defaultCredentialsPath } from './credentials.js';
28
- import { ApiError, CLIError, InterruptError, RequestTimeoutError } from './errors.js';
46
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, extractNodeErrorCode, } from './errors.js';
29
47
  import { facadeBaseUrl } from './facade.js';
30
48
  import { VERSION } from '../version.js';
31
49
  /**
@@ -35,20 +53,237 @@ import { VERSION } from '../version.js';
35
53
  * dropping the event is the correct best-effort behavior.
36
54
  */
37
55
  export const TELEMETRY_TIMEOUT_MS = 1000;
56
+ /**
57
+ * Which CI system the process is running under, from the standard env markers
58
+ * each vendor documents. `other` is any CI that only sets the generic `CI`
59
+ * variable; `none` is an interactive/unknown context.
60
+ */
61
+ export function detectCiProvider(env) {
62
+ if (env.GITHUB_ACTIONS === 'true')
63
+ return 'github';
64
+ if (isTruthyEnv(env.GITLAB_CI))
65
+ return 'gitlab';
66
+ if (isTruthyEnv(env.CIRCLECI))
67
+ return 'circleci';
68
+ if (isTruthyEnv(env.BUILDKITE))
69
+ return 'buildkite';
70
+ if (isTruthyEnv(env.CI))
71
+ return 'other';
72
+ return 'none';
73
+ }
74
+ const CI_EVENTS = new Set([
75
+ 'push',
76
+ 'pull_request',
77
+ 'schedule',
78
+ 'workflow_dispatch',
79
+ ]);
80
+ /**
81
+ * The GitHub Actions event that triggered the workflow, bucketed to a fixed
82
+ * vocabulary (`other` for everything outside it, e.g. `release`). Only
83
+ * meaningful under GitHub; undefined for every other provider and when the
84
+ * runner did not set `GITHUB_EVENT_NAME`.
85
+ */
86
+ export function detectCiEvent(env, provider) {
87
+ if (provider !== 'github')
88
+ return undefined;
89
+ const name = env.GITHUB_EVENT_NAME;
90
+ if (typeof name !== 'string' || name === '')
91
+ return undefined;
92
+ return CI_EVENTS.has(name) ? name : 'other';
93
+ }
94
+ /**
95
+ * Stable, non-reversible grouping key for a CI repository: the first 16 hex
96
+ * chars of `sha256('testsprite-ci-repo:' + slug)`. The salt prefix keeps the
97
+ * digest from matching a plain `sha256(slug)` lookup table; the slug itself
98
+ * never leaves the runner.
99
+ */
100
+ export function hashRepository(slug) {
101
+ return createHash('sha256').update(`testsprite-ci-repo:${slug}`).digest('hex').slice(0, 16);
102
+ }
103
+ /** The CI-context slice of the event (provider always present; the rest only when known). */
104
+ export function buildCiContext(env) {
105
+ const ciProvider = detectCiProvider(env);
106
+ const ciEvent = detectCiEvent(env, ciProvider);
107
+ const repo = env.GITHUB_REPOSITORY;
108
+ return {
109
+ ciProvider,
110
+ ...(ciEvent !== undefined ? { ciEvent } : {}),
111
+ ...(typeof repo === 'string' && repo !== '' ? { repoHash: hashRepository(repo) } : {}),
112
+ };
113
+ }
114
+ const COUNT_KEYS = [
115
+ 'accepted',
116
+ 'conflicts',
117
+ 'deferred',
118
+ 'skipped',
119
+ 'passed',
120
+ 'failed',
121
+ 'blocked',
122
+ 'timedOut',
123
+ 'localConcurrencyLimit',
124
+ 'localPeakInFlight',
125
+ ];
126
+ const BOOLEAN_KEYS = ['force', 'workflowExisted'];
127
+ const ENUM_KEYS = {
128
+ conflictReason: new Set([
129
+ 'in_flight',
130
+ 'insufficient_credits',
131
+ 'paused',
132
+ 'billing_hold',
133
+ 'mcp_view_only',
134
+ 'local_address',
135
+ 'tunnel-required',
136
+ 'error',
137
+ ]),
138
+ platform: new Set(['github']),
139
+ projectResolved: new Set(['flag', 'auto']),
140
+ };
141
+ /**
142
+ * Keep only the allowlisted keys with a value of the right shape. Pure: this is
143
+ * the single gate both the sink and the event builder run, so a stray field or
144
+ * a mistyped value can never reach the wire from either direction.
145
+ */
146
+ export function sanitizeTelemetryExtras(partial) {
147
+ const rec = partial;
148
+ const out = {};
149
+ for (const key of COUNT_KEYS) {
150
+ const v = rec[key];
151
+ if (typeof v === 'number' && Number.isInteger(v) && v >= 0)
152
+ out[key] = v;
153
+ }
154
+ for (const key of BOOLEAN_KEYS) {
155
+ const v = rec[key];
156
+ if (typeof v === 'boolean')
157
+ out[key] = v;
158
+ }
159
+ for (const key of Object.keys(ENUM_KEYS)) {
160
+ const v = rec[key];
161
+ if (typeof v === 'string' && ENUM_KEYS[key].has(v)) {
162
+ out[key] = v;
163
+ }
164
+ }
165
+ return out;
166
+ }
167
+ /** Module-level sink: the extras the running command has recorded so far. */
168
+ let pendingExtras = {};
169
+ /**
170
+ * Record outcome facts for the event this process will fire. Called by a
171
+ * command just before it returns/throws; merged per key, so a later call for
172
+ * the same key wins and different commands' keys never collide. Values outside
173
+ * the allowlist (or of the wrong shape) are dropped silently — a caller can
174
+ * never widen the wire contract from here.
175
+ */
176
+ export function recordTelemetryExtras(partial) {
177
+ pendingExtras = { ...pendingExtras, ...sanitizeTelemetryExtras(partial) };
178
+ }
179
+ /** Return everything recorded so far and clear the sink (one event per process). */
180
+ export function takeTelemetryExtras() {
181
+ const taken = pendingExtras;
182
+ pendingExtras = {};
183
+ return taken;
184
+ }
185
+ /**
186
+ * Disjoint verdict counts over a set of polled runs — `passed` + `failed` +
187
+ * `blocked` + `timedOut` = total. Unlike the CI summary's `failed` (which folds
188
+ * blocked in), `blocked` is split out here because it is the signal that
189
+ * separates a broken target from a failing assertion.
190
+ */
191
+ export function batchOutcomeCounts(results) {
192
+ let passed = 0;
193
+ let blocked = 0;
194
+ let timedOut = 0;
195
+ for (const r of results) {
196
+ if (r.status === 'passed')
197
+ passed++;
198
+ else if (r.status === 'blocked')
199
+ blocked++;
200
+ else if (r.status === 'timeout')
201
+ timedOut++;
202
+ }
203
+ return { passed, failed: results.length - passed - blocked - timedOut, blocked, timedOut };
204
+ }
205
+ /**
206
+ * Record a batch command's dispatch accounting (and, under `--wait`, its
207
+ * verdict counts) in one call, so `test run --all` and `testlist run` cannot
208
+ * drift in how they count. `conflictReason` is the dominant reason of the
209
+ * batch; `results` are the polled runs (omit for a non-wait dispatch).
210
+ */
211
+ export function recordBatchOutcome(batch) {
212
+ recordTelemetryExtras({
213
+ accepted: batch.accepted,
214
+ conflicts: batch.conflicts.length,
215
+ deferred: batch.deferred,
216
+ skipped: batch.skipped,
217
+ conflictReason: dominantConflictReason(batch.conflicts),
218
+ ...(batch.results !== undefined ? batchOutcomeCounts(batch.results) : {}),
219
+ });
220
+ }
38
221
  /**
39
222
  * Map a thrown CLI error to its telemetry disposition — mirrors the exit-code
40
223
  * mapping in `index.ts`'s top-level catch so telemetry and the process exit
41
224
  * code never disagree. Pure; safe to unit-test.
225
+ *
226
+ * Every branch below now fills `errorCode` — the two fallback branches
227
+ * (`CLIError`, and the final catch-all for a non-CLIError throw) previously
228
+ * left it `undefined`, which is why a meaningful share of `test run`
229
+ * invocations and `setup` failures landed in telemetry with `errorCode=None`.
230
+ *
231
+ * `errorOrigin` ('client' | 'server') resolves a real UNSUPPORTED
232
+ * misclassification: prod data showed genuine backend 501 UNSUPPORTED
233
+ * responses are rare compared to the PostHog events carrying that code,
234
+ * because every `--wait` timeout is ALSO converted to a client-fabricated
235
+ * `UNSUPPORTED`/exit-7 envelope (exit 7 is the timeout bucket by design;
236
+ * this patch does not touch that contract, only observability).
237
+ *
238
+ * Discriminator: for an `ApiError`, `err.httpStatus !== undefined` iff the
239
+ * code came from a real HTTP response (http.ts passes `response.status` into
240
+ * `ApiError.fromEnvelope` on every non-OK response it parses) — every
241
+ * CLI-fabricated envelope (`localValidationError`, `ApiError.authRequired()`,
242
+ * `TransportError`, and every `throw ApiError.fromEnvelope({... requestId:
243
+ * 'local' ...})` timeout conversion in commands/test.ts) never passes an
244
+ * `httpStatus`, so it reads `undefined`. `requestId` was considered and
245
+ * REJECTED as the discriminator: http.ts stamps a real, non-'local'
246
+ * `x-request-id` (`newRequestId()`) on every OUTGOING request before it knows
247
+ * whether a response will ever arrive, so `TransportError` (a DNS/TLS
248
+ * failure that never got a response) carries a real requestId despite being
249
+ * 100% client-side — `requestId === 'local'` would have misclassified it as
250
+ * 'server'. All non-`ApiError` branches (`RequestTimeoutError`,
251
+ * `InterruptError`, a plain `CLIError`, `CommanderError`, and a genuinely
252
+ * uncaught exception) never involve an HTTP response at all, so they are
253
+ * unconditionally 'client'.
42
254
  */
43
255
  export function classifyCliError(err) {
44
256
  if (err instanceof InterruptError) {
45
- return { outcome: 'abort', exitCode: err.exitCode, errorCode: 'INTERRUPTED' };
257
+ // err.code is 'INTERRUPTED' (set in its constructor) — read it rather
258
+ // than re-hardcoding the literal, so there is exactly one place that
259
+ // knows InterruptError's telemetry code.
260
+ return {
261
+ outcome: 'abort',
262
+ exitCode: err.exitCode,
263
+ errorCode: err.code,
264
+ errorOrigin: 'client',
265
+ };
46
266
  }
47
267
  if (err instanceof RequestTimeoutError) {
48
- return { outcome: 'error', exitCode: err.exitCode, errorCode: 'REQUEST_TIMEOUT' };
268
+ // err.code is 'REQUEST_TIMEOUT' (set in its constructor) — same reasoning.
269
+ return {
270
+ outcome: 'error',
271
+ exitCode: err.exitCode,
272
+ errorCode: err.code,
273
+ errorOrigin: 'client',
274
+ timeoutSeconds: Math.round(err.timeoutMs / 1000),
275
+ };
49
276
  }
50
277
  if (err instanceof ApiError) {
51
- return { outcome: 'error', exitCode: err.exitCode, errorCode: err.code };
278
+ const errorOrigin = err.httpStatus !== undefined ? 'server' : 'client';
279
+ const timeoutSeconds = err.getDetail('timeoutSeconds', (v) => typeof v === 'number');
280
+ return {
281
+ outcome: 'error',
282
+ exitCode: err.exitCode,
283
+ errorCode: err.code,
284
+ errorOrigin,
285
+ ...(timeoutSeconds !== undefined ? { timeoutSeconds } : {}),
286
+ };
52
287
  }
53
288
  if (err instanceof CommanderError) {
54
289
  // Help / version are user-requested successes (exit 0); everything else
@@ -58,12 +293,22 @@ export function classifyCliError(err) {
58
293
  err.code === 'commander.version') {
59
294
  return { outcome: 'success', exitCode: 0 };
60
295
  }
61
- return { outcome: 'error', exitCode: 5, errorCode: 'VALIDATION_ERROR' };
296
+ return {
297
+ outcome: 'error',
298
+ exitCode: 5,
299
+ errorCode: 'VALIDATION_ERROR',
300
+ errorOrigin: 'client',
301
+ };
62
302
  }
63
303
  if (err instanceof CLIError) {
64
- return { outcome: 'error', exitCode: err.exitCode };
304
+ return { outcome: 'error', exitCode: err.exitCode, errorCode: err.code, errorOrigin: 'client' };
65
305
  }
66
- return { outcome: 'error', exitCode: 1 };
306
+ return {
307
+ outcome: 'error',
308
+ exitCode: 1,
309
+ errorCode: extractNodeErrorCode(err) ?? 'UNCAUGHT_EXCEPTION',
310
+ errorOrigin: 'client',
311
+ };
67
312
  }
68
313
  /** True when the operator has opted out via either supported env var. */
69
314
  export function isTelemetryOptedOut(env) {
@@ -75,19 +320,28 @@ function isTruthyEnv(v) {
75
320
  const t = v.trim().toLowerCase();
76
321
  return t !== '' && t !== '0' && t !== 'false';
77
322
  }
78
- /** Assemble the allowlisted wire event. No URL / message / flag value ever. */
79
- export function buildTelemetryEvent(input, env, isTTY) {
323
+ /**
324
+ * Assemble the allowlisted wire event. No URL / message / flag value ever.
325
+ * `extras` are the per-command facts the sink collected (re-sanitized here so a
326
+ * direct caller cannot bypass the allowlist).
327
+ */
328
+ export function buildTelemetryEvent(input, env, isTTY, extras = {}) {
329
+ const client = resolveClientTag(env);
80
330
  return {
81
331
  command: input.command,
82
332
  outcome: input.outcome,
83
333
  exitCode: input.exitCode,
84
334
  ...(input.errorCode ? { errorCode: input.errorCode } : {}),
335
+ ...(input.errorOrigin ? { errorOrigin: input.errorOrigin } : {}),
336
+ ...(typeof input.timeoutSeconds === 'number' ? { timeoutSeconds: input.timeoutSeconds } : {}),
85
337
  durationMs: input.durationMs,
86
338
  cliVersion: VERSION,
87
339
  os: process.platform,
88
340
  nodeVersion: process.versions.node,
89
341
  ...(input.output === 'json' || input.output === 'text' ? { output: input.output } : {}),
90
342
  ci: isTruthyEnv(env.CI) || !isTTY,
343
+ ...(client !== undefined ? { client } : {}),
344
+ ...buildCiContext(env),
91
345
  ...(input.local ? { local: true } : {}),
92
346
  ...(input.outcome === 'error' && input.reason === 'wait_timeout'
93
347
  ? {
@@ -101,6 +355,7 @@ export function buildTelemetryEvent(input, env, isTTY) {
101
355
  : {}),
102
356
  }
103
357
  : {}),
358
+ ...sanitizeTelemetryExtras(extras),
104
359
  };
105
360
  }
106
361
  /**
@@ -112,8 +367,11 @@ export function buildTelemetryEvent(input, env, isTTY) {
112
367
  * opted-out call never reads the credentials file.
113
368
  */
114
369
  export function resolveTelemetryAuth(opts, deps = {}) {
370
+ // No `?? 'default'`: `loadConfig` resolves the documented
371
+ // flag > TESTSPRITE_PROFILE > default order from the same env, and a
372
+ // pre-collapsed string here would hide the env var from it.
115
373
  const config = loadConfig({
116
- profile: opts.profile ?? 'default',
374
+ profile: opts.profile,
117
375
  endpointUrl: opts.endpointUrl,
118
376
  env: deps.env ?? process.env,
119
377
  credentialsPath: deps.credentialsPath ?? defaultCredentialsPath(),
@@ -127,6 +385,9 @@ export function resolveTelemetryAuth(opts, deps = {}) {
127
385
  * command, or when no api-key is configured.
128
386
  */
129
387
  export async function recordOutcome(input, deps = {}) {
388
+ // Drain the sink unconditionally — one event per process, and a gated-out
389
+ // flush must not leave a previous command's facts behind for the next test.
390
+ const extras = takeTelemetryExtras();
130
391
  try {
131
392
  const env = deps.env ?? process.env;
132
393
  if (isTelemetryOptedOut(env))
@@ -145,7 +406,7 @@ export async function recordOutcome(input, deps = {}) {
145
406
  // `auth remove` could delete the profile); fall back to a fresh read.
146
407
  const config = deps.resolvedAuth ??
147
408
  loadConfig({
148
- profile: input.profile ?? 'default',
409
+ profile: input.profile,
149
410
  endpointUrl: input.endpointUrl,
150
411
  env,
151
412
  credentialsPath: deps.credentialsPath ?? defaultCredentialsPath(),
@@ -154,7 +415,7 @@ export async function recordOutcome(input, deps = {}) {
154
415
  return; // authenticated-only
155
416
  const url = `${facadeBaseUrl(config.apiUrl)}/telemetry`;
156
417
  const isTTY = deps.isTTY ?? process.stderr.isTTY === true;
157
- const body = buildTelemetryEvent(input, env, isTTY);
418
+ const body = buildTelemetryEvent(input, env, isTTY, extras);
158
419
  const fetchImpl = deps.fetchImpl ?? globalThis.fetch;
159
420
  const controller = new AbortController();
160
421
  const timer = setTimeout(() => controller.abort(), TELEMETRY_TIMEOUT_MS);
@@ -167,7 +428,7 @@ export async function recordOutcome(input, deps = {}) {
167
428
  headers: {
168
429
  'content-type': 'application/json',
169
430
  'x-api-key': config.apiKey,
170
- 'user-agent': `testsprite-cli/${VERSION}`,
431
+ 'user-agent': buildUserAgent(env),
171
432
  },
172
433
  body: JSON.stringify(body),
173
434
  signal: controller.signal,
@@ -25,6 +25,95 @@ export function isNoColor(env = process.env) {
25
25
  const value = env.NO_COLOR;
26
26
  return typeof value === 'string' && value.length > 0;
27
27
  }
28
+ const DEFAULT_TERMINAL_COLUMNS = 80;
29
+ const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
30
+ const markPattern = /^\p{Mark}$/u;
31
+ const emojiPattern = /\p{Extended_Pictographic}|\p{Regional_Indicator}|\u20e3/u;
32
+ /**
33
+ * Return whether a Unicode code point normally occupies two terminal columns.
34
+ *
35
+ * @param codePoint - Unicode scalar value to classify.
36
+ * @returns Whether the code point is full-width in a terminal.
37
+ */
38
+ function isFullwidthCodePoint(codePoint) {
39
+ return (codePoint >= 0x1100 &&
40
+ (codePoint <= 0x115f ||
41
+ codePoint === 0x2329 ||
42
+ codePoint === 0x232a ||
43
+ (codePoint >= 0x2e80 && codePoint <= 0xa4cf && codePoint !== 0x303f) ||
44
+ (codePoint >= 0xac00 && codePoint <= 0xd7a3) ||
45
+ (codePoint >= 0xf900 && codePoint <= 0xfaff) ||
46
+ (codePoint >= 0xfe10 && codePoint <= 0xfe19) ||
47
+ (codePoint >= 0xfe30 && codePoint <= 0xfe6f) ||
48
+ (codePoint >= 0xff00 && codePoint <= 0xff60) ||
49
+ (codePoint >= 0xffe0 && codePoint <= 0xffe6) ||
50
+ (codePoint >= 0x1b000 && codePoint <= 0x1b001) ||
51
+ (codePoint >= 0x1f200 && codePoint <= 0x1f251) ||
52
+ (codePoint >= 0x20000 && codePoint <= 0x3fffd)));
53
+ }
54
+ /**
55
+ * Measure one grapheme cluster in terminal display columns.
56
+ *
57
+ * @param grapheme - User-perceived character produced by the segmenter.
58
+ * @returns The number of terminal columns occupied by the grapheme.
59
+ */
60
+ function graphemeWidth(grapheme) {
61
+ if (emojiPattern.test(grapheme))
62
+ return 2;
63
+ let width = 0;
64
+ for (const character of grapheme) {
65
+ const codePoint = character.codePointAt(0);
66
+ if (codePoint === 0x200d ||
67
+ (codePoint >= 0xfe00 && codePoint <= 0xfe0f) ||
68
+ (codePoint >= 0xe0100 && codePoint <= 0xe01ef) ||
69
+ codePoint <= 0x1f ||
70
+ (codePoint >= 0x7f && codePoint <= 0x9f) ||
71
+ markPattern.test(character)) {
72
+ continue;
73
+ }
74
+ width += isFullwidthCodePoint(codePoint) ? 2 : 1;
75
+ }
76
+ return width;
77
+ }
78
+ /**
79
+ * Measure a complete string in terminal display columns.
80
+ *
81
+ * @param text - Text to measure.
82
+ * @returns The number of terminal columns occupied by the text.
83
+ */
84
+ function terminalWidth(text) {
85
+ let width = 0;
86
+ for (const { segment } of graphemeSegmenter.segment(text)) {
87
+ width += graphemeWidth(segment);
88
+ }
89
+ return width;
90
+ }
91
+ /**
92
+ * Keep a ticker frame inside the terminal's last safe column. Terminal width is
93
+ * read for every frame so an in-progress ticker follows live resizes.
94
+ */
95
+ function fitToTerminal(line) {
96
+ const reportedColumns = typeof process !== 'undefined' ? process.stderr.columns : undefined;
97
+ const columns = typeof reportedColumns === 'number' && Number.isFinite(reportedColumns) && reportedColumns > 0
98
+ ? Math.floor(reportedColumns)
99
+ : DEFAULT_TERMINAL_COLUMNS;
100
+ const maxWidth = Math.max(0, columns - 1);
101
+ if (terminalWidth(line) <= maxWidth)
102
+ return line;
103
+ if (maxWidth === 0)
104
+ return '';
105
+ const contentWidth = maxWidth - 1;
106
+ let fitted = '';
107
+ let fittedWidth = 0;
108
+ for (const { segment } of graphemeSegmenter.segment(line)) {
109
+ const width = graphemeWidth(segment);
110
+ if (fittedWidth + width > contentWidth)
111
+ break;
112
+ fitted += segment;
113
+ fittedWidth += width;
114
+ }
115
+ return `${fitted}…`;
116
+ }
28
117
  /**
29
118
  * Create a ticker bound to the given stderr writer. Respects
30
119
  * `isTTY` to silently no-op in CI environments.
@@ -59,13 +148,13 @@ export function createTicker(stderrWrite, isTTY, stderrRaw, noColor) {
59
148
  return {
60
149
  redrawsInPlace: false,
61
150
  update(line) {
62
- const stamped = `${new Date().toISOString()} ${line}`;
151
+ const stamped = fitToTerminal(`${new Date().toISOString()} ${line}`);
63
152
  stderrWrite(stamped);
64
153
  lastLength = stamped.length;
65
154
  },
66
155
  finalize(line) {
67
156
  if (line !== undefined) {
68
- const stamped = `${new Date().toISOString()} ${line}`;
157
+ const stamped = fitToTerminal(`${new Date().toISOString()} ${line}`);
69
158
  stderrWrite(stamped);
70
159
  lastLength = stamped.length;
71
160
  }
@@ -77,13 +166,13 @@ export function createTicker(stderrWrite, isTTY, stderrRaw, noColor) {
77
166
  redrawsInPlace: true,
78
167
  update(line) {
79
168
  // ANSI ESC[2K clears the entire line; \r moves to column 0.
80
- const stamped = `${new Date().toISOString()} ${line}`;
169
+ const stamped = fitToTerminal(`${new Date().toISOString()} ${line}`);
81
170
  rawWrite(`\x1b[2K\r${stamped}`);
82
171
  lastLength = stamped.length;
83
172
  },
84
173
  finalize(line) {
85
174
  if (line !== undefined) {
86
- const stamped = `${new Date().toISOString()} ${line}`;
175
+ const stamped = fitToTerminal(`${new Date().toISOString()} ${line}`);
87
176
  rawWrite(`\x1b[2K\r${stamped}`);
88
177
  lastLength = stamped.length;
89
178
  }
@@ -101,6 +101,19 @@ export interface OpenTunnelSessionOptions {
101
101
  connectTimeoutMs?: number;
102
102
  /** Called once, the first time the tunnel becomes unusable for this run. */
103
103
  onFatal?: (reason: TunnelFatalReason, message?: string) => void;
104
+ /**
105
+ * Called once, right after the mint succeeds and BEFORE the connect attempt,
106
+ * with the binding's non-secret handle. A process killed while connecting
107
+ * never reaches the line a caller prints after connect, and the binding it
108
+ * leaves behind holds a slot of the per-account cap until it expires; this
109
+ * is what lets the caller name that binding while it still can. Not called
110
+ * for an adopted client. A throw is treated like a failed connect: the
111
+ * binding is deleted and the error propagates.
112
+ */
113
+ onMinted?: (minted: {
114
+ clientId: string;
115
+ expiresAt: string;
116
+ }) => void;
104
117
  /**
105
118
  * Attach to a client someone else minted (`testsprite tunnel start` in
106
119
  * another terminal) instead of minting one. No secret is available, so
@@ -38,7 +38,7 @@
38
38
  * does instead is honest failure: record the loss, let the caller stop the run
39
39
  * and say why. See `openTunnelSession`'s `onFatal`.
40
40
  */
41
- import { ApiError } from './errors.js';
41
+ import { ApiError, InterruptError } from './errors.js';
42
42
  import { ErrCode, TunnelClient } from '../vendor/tunnel-client/index.js';
43
43
  import { DEFAULT_DATA_PLANE_RETRY_DEADLINE_MS } from '../vendor/tunnel-client/config.js';
44
44
  /**
@@ -218,6 +218,7 @@ export async function openTunnelSession(options, deps) {
218
218
  }
219
219
  };
220
220
  try {
221
+ options.onMinted?.({ clientId: minted.clientId, expiresAt: minted.expiresAt });
221
222
  client = createClient({
222
223
  clientId: minted.clientId,
223
224
  secret: minted.secret,
@@ -280,6 +281,8 @@ export async function openTunnelSession(options, deps) {
280
281
  }
281
282
  catch (err) {
282
283
  await stopAndDestroy();
284
+ if (err instanceof InterruptError)
285
+ throw err;
283
286
  if (err instanceof ApiError)
284
287
  throw err;
285
288
  throw ApiError.fromEnvelope({
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Wire types for the `/api/cli/v1/tunnel` facade (DEV-747 piece 1).
2
+ * Wire types for the `/api/cli/v1/tunnel` facade.
3
3
  *
4
- * Three routes and deliberately no fourth — there is no resume/adopt route to
4
+ * The list and status reads are secret-free. There is no resume/adopt route to
5
5
  * hand a `{clientId, secret}` back to, so the CLI mints fresh per invocation.
6
6
  */
7
7
  /** Body of `POST /api/cli/v1/tunnel`. */
@@ -54,3 +54,13 @@ export interface TunnelStatusResponse {
54
54
  status: 'online' | 'offline' | (string & {});
55
55
  expiresAt: string;
56
56
  }
57
+ /** One secret-free binding returned by `GET /api/cli/v1/tunnel`. */
58
+ export interface TunnelListItem {
59
+ clientId: string;
60
+ status: 'online' | 'offline' | 'unknown' | (string & {});
61
+ expiresAt: string;
62
+ createdAt?: string | null;
63
+ }
64
+ export interface TunnelListResponse {
65
+ tunnels: TunnelListItem[];
66
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Wire types for the `/api/cli/v1/tunnel` facade (DEV-747 piece 1).
2
+ * Wire types for the `/api/cli/v1/tunnel` facade.
3
3
  *
4
- * Three routes and deliberately no fourth — there is no resume/adopt route to
4
+ * The list and status reads are secret-free. There is no resume/adopt route to
5
5
  * hand a `{clientId, secret}` back to, so the CLI mints fresh per invocation.
6
6
  */
7
7
  export {};
@@ -21,17 +21,36 @@ export interface VersionNoticeDeps {
21
21
  * dry-run, and non-TTY all suppress. Pure — no side effects, no process state.
22
22
  */
23
23
  export declare function shouldWarnBelowFloor(info: ServerVersionInfo, deps?: VersionNoticeDeps): boolean;
24
+ /**
25
+ * True when the below-floor state should be surfaced as a GitHub Actions
26
+ * `::warning::` annotation: running under Actions (`GITHUB_ACTIONS=true`), not
27
+ * opted out, not dry-run, and strictly below the floor. Deliberately NOT gated
28
+ * on TTY or `--output json` — an Actions job is never a TTY, and a workflow
29
+ * command is parsed by the runner from either stream, so it can ride stderr
30
+ * without touching a JSON envelope on stdout.
31
+ */
32
+ export declare function shouldWarnPinnedInActions(info: ServerVersionInfo, deps?: VersionNoticeDeps): boolean;
24
33
  /**
25
34
  * The single advisory line. Names the floor (the backend's authority) and the
26
35
  * upgrade command — it deliberately does NOT name a target release; the npm
27
36
  * update-notice is the single source of truth for the newest version.
28
37
  */
29
38
  export declare function formatBelowFloorNotice(currentVersion: string, minVersion: string): string;
39
+ /**
40
+ * The GitHub Actions workflow-command form of the advisory. Names the pinned
41
+ * (running) version, the floor it has fallen below, and the one command that
42
+ * re-pins the workflow to a current release. Both versions come from semver
43
+ * strings that already parsed (see `isBelowFloor`), so no command-data escaping
44
+ * is needed — neither can carry `%`, CR or LF.
45
+ */
46
+ export declare function formatPinnedVersionWarning(currentVersion: string, minVersion: string): string;
30
47
  /** Test-only: reset the once-per-process guard between cases. */
31
48
  export declare function resetBelowFloorNoticeState(): void;
32
49
  /**
33
50
  * Emit the below-floor advisory at most once per process. Wired to the HTTP
34
51
  * client's `onServerVersion` hook. Never throws — an advisory must not break or
35
- * delay the command it rides along with.
52
+ * delay the command it rides along with. Under GitHub Actions the advisory is
53
+ * the `::warning::` workflow command (annotates the job) instead of the plain
54
+ * TTY line; exactly one of the two is ever emitted.
36
55
  */
37
56
  export declare function noteServerVersion(info: ServerVersionInfo, deps?: VersionNoticeDeps): void;