@testsprite/testsprite-cli 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +65 -41
  2. package/dist/commands/auth.d.ts +5 -1
  3. package/dist/commands/auth.js +17 -5
  4. package/dist/commands/ci.js +34 -4
  5. package/dist/commands/init.d.ts +6 -1
  6. package/dist/commands/init.js +13 -5
  7. package/dist/commands/project-env.d.ts +90 -0
  8. package/dist/commands/project-env.js +486 -0
  9. package/dist/commands/project.d.ts +19 -0
  10. package/dist/commands/project.js +92 -25
  11. package/dist/commands/test.d.ts +42 -4
  12. package/dist/commands/test.js +344 -49
  13. package/dist/commands/testlist.js +29 -3
  14. package/dist/commands/tunnel.d.ts +2 -2
  15. package/dist/commands/tunnel.js +139 -31
  16. package/dist/index.js +42 -14
  17. package/dist/lib/client-factory.d.ts +4 -1
  18. package/dist/lib/client-factory.js +14 -4
  19. package/dist/lib/client-tag.d.ts +13 -0
  20. package/dist/lib/client-tag.js +44 -0
  21. package/dist/lib/conflict-reason.d.ts +43 -2
  22. package/dist/lib/conflict-reason.js +100 -14
  23. package/dist/lib/credentials.d.ts +4 -0
  24. package/dist/lib/credentials.js +43 -4
  25. package/dist/lib/cron.js +8 -1
  26. package/dist/lib/errors.d.ts +44 -1
  27. package/dist/lib/errors.js +69 -12
  28. package/dist/lib/gh-output.d.ts +25 -11
  29. package/dist/lib/gh-output.js +36 -13
  30. package/dist/lib/http.d.ts +21 -2
  31. package/dist/lib/http.js +45 -8
  32. package/dist/lib/local-target.d.ts +32 -0
  33. package/dist/lib/local-target.js +77 -0
  34. package/dist/lib/output.d.ts +27 -1
  35. package/dist/lib/output.js +22 -3
  36. package/dist/lib/response-schemas.d.ts +5 -2
  37. package/dist/lib/response-schemas.js +39 -1
  38. package/dist/lib/runs.types.d.ts +50 -2
  39. package/dist/lib/target-url.d.ts +1 -1
  40. package/dist/lib/target-url.js +35 -12
  41. package/dist/lib/telemetry.d.ts +174 -4
  42. package/dist/lib/telemetry.js +286 -13
  43. package/dist/lib/tunnel-session.d.ts +13 -2
  44. package/dist/lib/tunnel-session.js +92 -23
  45. package/dist/lib/tunnel.types.d.ts +3 -1
  46. package/dist/lib/version-notice.d.ts +20 -1
  47. package/dist/lib/version-notice.js +59 -12
  48. package/dist/vendor/tunnel-client/client.d.ts +11 -0
  49. package/dist/vendor/tunnel-client/client.js +383 -56
  50. package/dist/vendor/tunnel-client/config.d.ts +11 -3
  51. package/dist/vendor/tunnel-client/config.js +11 -3
  52. package/dist/vendor/tunnel-client/types.d.ts +26 -1
  53. package/dist/vendor/tunnel-client/types.js +1 -0
  54. package/dist/vendor/tunnel-client/ws-compat.d.ts +3 -2
  55. package/dist/vendor/tunnel-client/ws-compat.js +3 -2
  56. package/dist/version.d.ts +1 -1
  57. package/dist/version.js +1 -1
  58. package/package.json +2 -1
  59. package/skills/testsprite-onboard.skill.md +74 -59
  60. package/skills/testsprite-verify.codex.md +82 -97
  61. package/skills/testsprite-verify.skill.md +64 -15
@@ -6,7 +6,8 @@ import { REQUEST_TIMEOUT_DEFAULT_MS, REQUEST_TIMEOUT_MAX_MS, } from '../lib/http
6
6
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
7
7
  import { pollRunUntilTerminal, TimeoutError } from '../lib/poll.js';
8
8
  import { emitCiArtifacts, summarizeAcceptedPayload } from '../lib/gh-output.js';
9
- import { describeConflict, summarizeConflicts } from '../lib/conflict-reason.js';
9
+ import { describeConflict, insufficientCreditsConflictError, isAllCreditsRefusal, summarizeConflicts, } from '../lib/conflict-reason.js';
10
+ import { recordBatchOutcome } from '../lib/telemetry.js';
10
11
  import { formatRunProgressLine } from '../lib/run-progress.js';
11
12
  import { createTicker } from '../lib/ticker.js';
12
13
  import { buildJUnitReport, parseJUnitReportFormat, writeJUnitReportFile, } from '../lib/junit-report.js';
@@ -339,6 +340,12 @@ export async function runTestlistRun(opts, deps = {}) {
339
340
  // flows through the tail below so its CI artifacts are still emitted.
340
341
  if (resp.accepted.length === 0 && resp.conflicts.length > 0) {
341
342
  out.print(resp, () => renderRunAcceptedText(resp));
343
+ recordBatchOutcome({
344
+ accepted: 0,
345
+ conflicts: resp.conflicts,
346
+ deferred: resp.deferred.length,
347
+ skipped: 0,
348
+ });
342
349
  // Surface the exit-6 in CI too (only under --wait, the CI-artifact contract):
343
350
  // an all-conflict re-run — every targeted case already in flight — otherwise
344
351
  // exits 6 with no ::error:: annotation and no summary file. The conflicts fold
@@ -360,6 +367,12 @@ export async function runTestlistRun(opts, deps = {}) {
360
367
  stderr: stderrFn,
361
368
  }, 'testlist run');
362
369
  }
370
+ // Every case refused for credits → exit 12, the same INSUFFICIENT_CREDITS
371
+ // envelope the single-run route answers (a rate-deferred remainder is exit 7
372
+ // below; `isAllCreditsRefusal` requires an empty deferred set).
373
+ if (isAllCreditsRefusal(resp)) {
374
+ throw insufficientCreditsConflictError(resp.conflicts, client.resolvedBaseUrl);
375
+ }
363
376
  const pollIds = resp.conflicts
364
377
  .map(c => c.currentRunId)
365
378
  .filter((id) => Boolean(id));
@@ -376,6 +389,12 @@ export async function runTestlistRun(opts, deps = {}) {
376
389
  out.print(resp, () => resp.accepted.length > 0
377
390
  ? renderRunAcceptedText(resp)
378
391
  : `No runs dispatched${resp.reason ? ` (${resp.reason})` : ''}.`);
392
+ recordBatchOutcome({
393
+ accepted: resp.accepted.length,
394
+ conflicts: resp.conflicts,
395
+ deferred: resp.deferred.length,
396
+ skipped: 0,
397
+ });
379
398
  assertNoDeferred(resp);
380
399
  assertNoNotFound(resp);
381
400
  return resp;
@@ -531,6 +550,13 @@ export async function runTestlistRun(opts, deps = {}) {
531
550
  await writeJUnitReportFile(opts.reportFile, xml);
532
551
  }
533
552
  out.print(jsonPayload, () => results.map(r => `${r.runId} ${r.status}`).join('\n'));
553
+ recordBatchOutcome({
554
+ accepted: resp.accepted.length,
555
+ conflicts: resp.conflicts,
556
+ deferred: resp.deferred.length,
557
+ skipped: 0,
558
+ results,
559
+ });
534
560
  // CI-native output parity with `test run` (--gh-output / --summary-file):
535
561
  // auto-enable under GITHUB_ACTIONS. Emit BEFORE the exit-code gates below so a
536
562
  // failing/timed-out/deferred run still gets its ::error:: annotations + the
@@ -728,8 +754,8 @@ export function createTestListCommand(deps = {}) {
728
754
  .option('--report <format>', 'with --wait: write a JUnit XML sidecar after polling (accepted: junit)')
729
755
  .option('--report-file <path>', 'output path for --report (atomic write)')
730
756
  .option('--report-suite-name <name>', 'JUnit <testsuite name=...> override (default: testsprite:testlist:<listId>)')
731
- .option('--gh-output', 'with --wait: emit GitHub-native output (::error:: annotations per non-passed member; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
732
- .option('--summary-file <path>', 'with --wait: also write the reduced machine summary JSON {total, passed, failed, timedOut, runs[]} to this file')
757
+ .option('--gh-output', 'with --wait: emit GitHub-native output (::error:: annotations for failed/timed-out members, ::warning:: for never-dispatched ones; job-summary table when $GITHUB_STEP_SUMMARY is set). Auto-enabled when GITHUB_ACTIONS=true')
758
+ .option('--summary-file <path>', 'with --wait: also write the reduced machine summary JSON {total, passed, failed, skipped, timedOut, runs[]} to this file')
733
759
  .addHelpText('after', GLOBAL_OPTS_HINT)
734
760
  .action(async (listId, cmdOpts, command) => {
735
761
  const wait = cmdOpts.wait === true;
@@ -65,8 +65,8 @@ export declare function runTunnelStatus(opts: TunnelClientIdOptions, deps?: Tunn
65
65
  * already-deleted binding is a success, because the requested end state holds.
66
66
  *
67
67
  * Worth knowing: this removes the ability to ATTACH a run to that client, and
68
- * removes the client from the tunnel server. It does not reach into a
69
- * `tunnel start` process still running elsewhere; stop that one with Ctrl-C.
68
+ * removes the client from the tunnel server. A running `tunnel start`
69
+ * observes the revocation on its next status check and exits.
70
70
  */
71
71
  export declare function runTunnelStop(opts: TunnelClientIdOptions, deps?: TunnelDeps): Promise<void>;
72
72
  export declare function createTunnelCommand(deps?: TunnelDeps): Command;
@@ -19,12 +19,27 @@
19
19
  * credentials are a settled no in this codebase.
20
20
  */
21
21
  import { Command } from 'commander';
22
- import { emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
22
+ import * as v from 'valibot';
23
+ import { createHttpClientFactory, emitDryRunBanner, makeHttpClient, parseRequestTimeoutFlag, resolveRequestTimeoutMs, } from '../lib/client-factory.js';
23
24
  import { ApiError, RequestTimeoutError } from '../lib/errors.js';
24
25
  import { globalShutdown } from '../lib/interrupt.js';
25
26
  import { GLOBAL_OPTS_HINT, Output, resolveOutputMode } from '../lib/output.js';
26
- import { openTunnelSession } from '../lib/tunnel-session.js';
27
+ import { formatDataPlaneUnreachableMessage, formatDataPlaneUnreachableNextAction, openTunnelSession, } from '../lib/tunnel-session.js';
27
28
  import { TunnelClient } from '../vendor/tunnel-client/index.js';
29
+ const TUNNEL_CLIENT_ID_SCHEMA = v.pipe(v.string(), v.uuid());
30
+ function assertTunnelClientId(clientId) {
31
+ if (v.is(TUNNEL_CLIENT_ID_SCHEMA, clientId))
32
+ return;
33
+ throw ApiError.fromEnvelope({
34
+ error: {
35
+ code: 'VALIDATION_ERROR',
36
+ message: "Tunnel client id must be a UUID (see 'testsprite tunnel status'/'tunnel start' output).",
37
+ nextAction: "Run 'testsprite tunnel start' to get a tunnel client id.",
38
+ requestId: 'local',
39
+ details: { field: 'clientId', reason: 'must be a UUID' },
40
+ },
41
+ });
42
+ }
28
43
  function stdoutOf(deps) {
29
44
  return deps.stdout ?? ((line) => process.stdout.write(`${line}\n`));
30
45
  }
@@ -40,14 +55,14 @@ function makeClient(opts, deps, shutdownSignal = (deps.shutdown ?? globalShutdow
40
55
  shutdownSignal,
41
56
  });
42
57
  }
43
- async function withUninterruptibleRequest(opts, deps, timeoutMs, operation) {
58
+ async function withUninterruptibleRequest(createClient, timeoutMs, operation) {
44
59
  const deadline = new AbortController();
45
60
  const timer = setTimeout(() => {
46
61
  deadline.abort(new RequestTimeoutError(timeoutMs));
47
62
  }, timeoutMs);
48
63
  timer.unref?.();
49
64
  try {
50
- return await operation(makeClient({ ...opts, requestTimeoutMs: timeoutMs }, deps, deadline.signal));
65
+ return await operation(createClient({ requestTimeoutMs: timeoutMs, shutdownSignal: deadline.signal }));
51
66
  }
52
67
  finally {
53
68
  clearTimeout(timer);
@@ -88,35 +103,73 @@ function shutdownAwareTunnelClientFactory(createClient, signal) {
88
103
  * the delete it issues at that moment must actually leave the machine — see
89
104
  * the same helper in `commands/test.ts`.
90
105
  */
91
- function makeDetachedClient(opts, deps, operationSignal) {
92
- return makeHttpClient({ ...opts, requestTimeoutMs: TEARDOWN_OPERATION_TIMEOUT_MS }, {
93
- env: deps.env,
94
- credentialsPath: deps.credentialsPath,
95
- fetchImpl: deps.fetchImpl,
96
- stderr: deps.stderr,
106
+ function makeDetachedClient(createClient, operationSignal) {
107
+ return createClient({
108
+ requestTimeoutMs: TEARDOWN_OPERATION_TIMEOUT_MS,
97
109
  shutdownSignal: operationSignal,
98
110
  });
99
111
  }
100
- async function withTeardownDeadline(opts, deps, operation) {
112
+ async function withTeardownDeadline(createClient, shutdown, operation) {
101
113
  const deadline = new AbortController();
102
114
  const timer = setTimeout(() => {
103
115
  deadline.abort(new RequestTimeoutError(TEARDOWN_OPERATION_TIMEOUT_MS));
104
116
  }, TEARDOWN_OPERATION_TIMEOUT_MS);
105
117
  timer.unref?.();
106
- const shutdown = deps.shutdown ?? globalShutdown;
107
118
  try {
108
- return await shutdown.runCriticalOperation(() => operation(makeDetachedClient(opts, deps, deadline.signal)));
119
+ return await shutdown.runCriticalOperation(() => operation(makeDetachedClient(createClient, deadline.signal)));
109
120
  }
110
121
  finally {
111
122
  clearTimeout(timer);
112
123
  }
113
124
  }
114
- async function deleteTunnelForCleanup(opts, deps, clientId) {
115
- await withTeardownDeadline(opts, deps, client => client.delete(`/tunnel/${encodeURIComponent(clientId)}`, {
125
+ async function deleteTunnelForCleanup(createClient, shutdown, clientId) {
126
+ await withTeardownDeadline(createClient, shutdown, client => client.delete(`/tunnel/${encodeURIComponent(clientId)}`, {
116
127
  allowNoContent: true,
117
128
  }));
118
129
  }
119
130
  const TEARDOWN_OPERATION_TIMEOUT_MS = 10_000;
131
+ const CREDENTIAL_POLL_INTERVAL_MS = 15_000;
132
+ function startCredentialRevocationPoll(args) {
133
+ const controller = new AbortController();
134
+ let checking = false;
135
+ let warned = false;
136
+ const check = async () => {
137
+ if (checking || controller.signal.aborted)
138
+ return;
139
+ checking = true;
140
+ try {
141
+ await args.client.getTunnelStatus(args.clientId, {
142
+ signal: controller.signal,
143
+ // The observation owns its cadence, including after errors.
144
+ retry: false,
145
+ });
146
+ warned = false;
147
+ }
148
+ catch (err) {
149
+ if (controller.signal.aborted)
150
+ return;
151
+ // Only the HTTP status is conclusive. An offline client still has a
152
+ // credential; a 5xx carrying NOT_FOUND is an observation outage.
153
+ if (err instanceof ApiError && err.httpStatus === 404) {
154
+ args.onRevoked();
155
+ }
156
+ else if (!warned) {
157
+ warned = true;
158
+ args.log(`[advisory] could not check tunnel credential ${args.clientId}; continuing to hold and retrying every 15 s.`);
159
+ }
160
+ }
161
+ finally {
162
+ checking = false;
163
+ }
164
+ };
165
+ // Skip ticks while a request is pending; never overlap reads or catch up
166
+ // missed ticks in a burst. The first read happens after a full interval.
167
+ const timer = setInterval(() => void check(), CREDENTIAL_POLL_INTERVAL_MS);
168
+ return () => {
169
+ clearInterval(timer);
170
+ controller.abort();
171
+ };
172
+ }
120
173
  function makeOutput(mode, deps) {
121
174
  return new Output(mode, { stdout: deps.stdout, stderr: deps.stderr });
122
175
  }
@@ -150,8 +203,23 @@ export async function runTunnelStart(opts, deps = {}) {
150
203
  const requestTimeoutMs = resolveRequestTimeoutMs(opts, deps.env ?? process.env);
151
204
  const clientOpts = { ...opts, requestTimeoutMs };
152
205
  const shutdown = deps.shutdown ?? globalShutdown;
206
+ const createClient = createHttpClientFactory(clientOpts, {
207
+ env: deps.env,
208
+ credentialsPath: deps.credentialsPath,
209
+ fetchImpl: deps.fetchImpl,
210
+ stderr: deps.stderr,
211
+ shutdownSignal: shutdown.signal,
212
+ });
153
213
  let fatal = false;
214
+ let fatalReason;
215
+ let fatalMessage;
216
+ let revoked = false;
154
217
  let resolveWait;
218
+ let stopPolling;
219
+ const onShutdown = () => {
220
+ stopPolling?.();
221
+ resolveWait?.();
222
+ };
155
223
  let session;
156
224
  const disarm = shutdown.arm();
157
225
  try {
@@ -160,13 +228,16 @@ export async function runTunnelStart(opts, deps = {}) {
160
228
  log: stderr,
161
229
  logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error',
162
230
  ...(opts.ttlSeconds !== undefined ? { ttlSeconds: opts.ttlSeconds } : {}),
163
- onFatal: () => {
231
+ onFatal: (reason, message) => {
164
232
  fatal = true;
233
+ fatalReason = reason;
234
+ fatalMessage = message;
235
+ revoked = reason === 'credential-revoked';
165
236
  resolveWait?.();
166
237
  },
167
238
  }, {
168
- mint: async (ttlSeconds) => withUninterruptibleRequest(clientOpts, deps, requestTimeoutMs, client => client.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
169
- destroy: async (clientId) => deleteTunnelForCleanup(opts, deps, clientId),
239
+ mint: async (ttlSeconds) => withUninterruptibleRequest(createClient, requestTimeoutMs, client => client.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
240
+ destroy: async (clientId) => deleteTunnelForCleanup(createClient, shutdown, clientId),
170
241
  createClient: shutdownAwareTunnelClientFactory(deps.createTunnelClient ?? (options => new TunnelClient(options)), shutdown.signal),
171
242
  });
172
243
  }
@@ -178,27 +249,45 @@ export async function runTunnelStart(opts, deps = {}) {
178
249
  return;
179
250
  throw err;
180
251
  }
181
- out.print({ clientId: session.clientId, expiresAt: session.expiresAt, status: 'online' }, data => {
252
+ out.print({
253
+ clientId: session.clientId,
254
+ expiresAt: session.expiresAt,
255
+ status: 'online',
256
+ transport: session.transport,
257
+ }, data => {
182
258
  const d = data;
183
259
  return [
184
260
  `clientId ${d.clientId}`,
185
261
  `expiresAt ${d.expiresAt}`,
186
262
  `status online`,
263
+ `transport ${d.transport}`,
187
264
  `hint Attach a run: testsprite test run <test-id> --local <port> --tunnel-client ${d.clientId}`,
188
- `hint Stop it: Ctrl-C here (or: testsprite tunnel stop ${d.clientId})`,
265
+ `hint Stop it: press Ctrl-C here, or run 'testsprite tunnel stop ${d.clientId}' from another terminal`,
189
266
  ].join('\n');
190
267
  });
191
268
  void stdout;
269
+ const { clientId } = session;
192
270
  await new Promise(resolve => {
193
271
  resolveWait = resolve;
194
272
  if (fatal || shutdown.signal.aborted) {
195
273
  resolve();
196
274
  return;
197
275
  }
198
- shutdown.signal.addEventListener('abort', () => resolve(), { once: true });
276
+ shutdown.signal.addEventListener('abort', onShutdown, { once: true });
277
+ stopPolling = startCredentialRevocationPoll({
278
+ client: createClient(),
279
+ clientId,
280
+ log: stderr,
281
+ onRevoked: () => {
282
+ revoked = true;
283
+ resolve();
284
+ },
285
+ });
199
286
  });
200
287
  }
201
288
  finally {
289
+ stopPolling?.();
290
+ shutdown.signal.removeEventListener('abort', onShutdown);
202
291
  try {
203
292
  await session?.close();
204
293
  }
@@ -206,15 +295,32 @@ export async function runTunnelStart(opts, deps = {}) {
206
295
  disarm();
207
296
  }
208
297
  }
209
- if (fatal && !shutdown.signal.aborted) {
298
+ if ((fatal || revoked) && !shutdown.signal.aborted) {
299
+ const dataPlaneUnreachable = fatalReason === 'data-plane-unreachable';
300
+ if (revoked) {
301
+ stderr(`Tunnel credential ${session.clientId} was revoked, expired, or taken over by another process.`);
302
+ }
210
303
  throw ApiError.fromEnvelope({
211
304
  error: {
212
305
  code: 'UNAVAILABLE',
213
- message: 'The tunnel service disconnected this client and it cannot be restored.',
214
- nextAction: 'Start it again — the retry mints a fresh client. Any run attached to the old client ' +
215
- 'has already stopped being able to reach this machine.',
306
+ message: dataPlaneUnreachable
307
+ ? formatDataPlaneUnreachableMessage(fatalMessage)
308
+ : revoked
309
+ ? `Tunnel credential ${session.clientId} was revoked, expired, or taken over by another process.`
310
+ : 'The tunnel service disconnected this client and it cannot be restored.',
311
+ nextAction: dataPlaneUnreachable
312
+ ? formatDataPlaneUnreachableNextAction(fatalMessage, 'retry testsprite tunnel start')
313
+ : 'Start it again — the retry mints a fresh client. Any run attached to the old client ' +
314
+ 'has already stopped being able to reach this machine.',
216
315
  requestId: 'local',
217
- details: { reason: 'auth-failed', clientId: session.clientId },
316
+ details: {
317
+ reason: dataPlaneUnreachable
318
+ ? 'data-plane-unreachable'
319
+ : revoked
320
+ ? 'credential-revoked'
321
+ : 'auth-failed',
322
+ clientId: session.clientId,
323
+ },
218
324
  },
219
325
  });
220
326
  }
@@ -230,6 +336,7 @@ export async function runTunnelStart(opts, deps = {}) {
230
336
  * defect backend-v2.0 #1068 fixed on the server side of this same question.
231
337
  */
232
338
  export async function runTunnelStatus(opts, deps = {}) {
339
+ assertTunnelClientId(opts.clientId);
233
340
  const out = makeOutput(opts.output, deps);
234
341
  if (opts.dryRun) {
235
342
  emitDryRunBanner(stderrOf(deps));
@@ -261,10 +368,11 @@ function renderStatus(status) {
261
368
  * already-deleted binding is a success, because the requested end state holds.
262
369
  *
263
370
  * Worth knowing: this removes the ability to ATTACH a run to that client, and
264
- * removes the client from the tunnel server. It does not reach into a
265
- * `tunnel start` process still running elsewhere; stop that one with Ctrl-C.
371
+ * removes the client from the tunnel server. A running `tunnel start`
372
+ * observes the revocation on its next status check and exits.
266
373
  */
267
374
  export async function runTunnelStop(opts, deps = {}) {
375
+ assertTunnelClientId(opts.clientId);
268
376
  const out = makeOutput(opts.output, deps);
269
377
  if (opts.dryRun) {
270
378
  emitDryRunBanner(stderrOf(deps));
@@ -272,7 +380,7 @@ export async function runTunnelStop(opts, deps = {}) {
272
380
  return;
273
381
  }
274
382
  await makeClient(opts, deps).deleteTunnel(opts.clientId);
275
- out.print({ clientId: opts.clientId, deleted: true }, () => `Tunnel ${opts.clientId} deleted.`);
383
+ out.print({ clientId: opts.clientId, deleted: true }, () => `Tunnel credential ${opts.clientId} revoked (or already absent).`);
276
384
  }
277
385
  export function createTunnelCommand(deps = {}) {
278
386
  const tunnel = new Command('tunnel')
@@ -327,8 +435,8 @@ export function createTunnelCommand(deps = {}) {
327
435
  tunnel
328
436
  .command('stop <client-id>')
329
437
  .description('Destroy a tunnel credential (idempotent)')
330
- .addHelpText('after', '\nStopping one that is already gone succeeds. This revokes the credential; it does not\n' +
331
- 'stop a `tunnel start` still running in another terminal (press Ctrl-C there).\n')
438
+ .addHelpText('after', '\nStopping one that is already gone succeeds. Revoking the credential\n' +
439
+ 'also makes a running `tunnel start` exit within ~15 s.\n')
332
440
  .addHelpText('after', GLOBAL_OPTS_HINT)
333
441
  .action(async (clientId, _cmdOpts, command) => {
334
442
  await runTunnelStop({ ...resolveCommonOptions(command), clientId }, deps);
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ import { createTestCommand } from './commands/test.js';
13
13
  import { createTestListCommand } from './commands/testlist.js';
14
14
  import { createUsageCommand } from './commands/usage.js';
15
15
  import { TARGETS } from './lib/agent-targets.js';
16
- import { ApiError, CLIError, InterruptError, RequestTimeoutError } from './lib/errors.js';
16
+ import { ApiError, CLIError, InterruptError, RequestTimeoutError, extractNodeErrorCode, } from './lib/errors.js';
17
17
  import { installBrokenPipeGuard, installSignalHandlers } from './lib/interrupt.js';
18
18
  import { Output, isOutputMode } from './lib/output.js';
19
19
  import { maybeInstallProxyAgent } from './lib/proxy.js';
@@ -68,7 +68,12 @@ addSetupOptions(authCommand.command('configure', { hidden: true }), authConfigur
68
68
  });
69
69
  program.addCommand(authCommand);
70
70
  program.addCommand(createProjectCommand({}));
71
- program.addCommand(createTestCommand());
71
+ let waitTimeoutTelemetry = {};
72
+ program.addCommand(createTestCommand({
73
+ onWaitTimeout: context => {
74
+ waitTimeoutTelemetry = context;
75
+ },
76
+ }));
72
77
  program.addCommand(createTestListCommand());
73
78
  program.addCommand(createCiCommand({}));
74
79
  program.addCommand(createScheduleCommand({}));
@@ -116,12 +121,14 @@ let telemetryEmit = false;
116
121
  // `auth remove` (which deletes the profile) is still reported on the key it used.
117
122
  let telemetryAuth;
118
123
  // True when the leaf command that is about to run carries a `--local` option
119
- // value — i.e. `test run --local <port>` (no other command declares `--local`).
120
- // Set by the preAction hook, BEFORE the command's own validation runs, so a
121
- // zero-network `--local` refusal (dead port, an incompatible flag combo) is
122
- // still reported: the whole point of this field is to see the attempts a
123
- // backend-side mint/attach event never observes.
124
+ // value — `test run --local <port>` or `project create --local <port>`.
125
+ // Set before validation so test-run refusals still report attempts that a
126
+ // backend-side mint/attach event never observes. Local project admission
127
+ // failures have a separate zero-HTTP exception below.
124
128
  let telemetryLocal = false;
129
+ // Local project admission failures must exit without any TestSprite HTTP,
130
+ // including telemetry. Track companion flags even when --local is missing.
131
+ let telemetryLocalProject = false;
125
132
  // Propagate exitOverride AND the buffered outputError config to every
126
133
  // subcommand in the tree. Commander's addCommand() does NOT inherit either
127
134
  // from the parent, so commands built externally (createTestCommand, etc.) and
@@ -199,10 +206,12 @@ program.hook('preAction', (_thisCommand, actionCommand) => {
199
206
  const commandPath = commandPathOf(actionCommand);
200
207
  // Record which leaf command ran, for the telemetry emit around parseAsync.
201
208
  ranCommandPath = commandPath;
202
- // `--local` is only declared on `test run`, so this is false for every
203
- // other command. The raw opt is a port string; only its presence is
209
+ // The raw --local opt is a port string; only its presence is
204
210
  // recorded (see `telemetryLocal`'s own comment — never the value).
205
211
  telemetryLocal = globals.local !== undefined;
212
+ telemetryLocalProject =
213
+ commandPath === 'project create' &&
214
+ (globals.local !== undefined || globals.localHost !== undefined);
206
215
  // See `isPlanTemplateInvocation` for why this one case is
207
216
  // filtered here rather than in skill-nudge.ts / update-check.ts.
208
217
  const isPlanTemplate = isPlanTemplateInvocation(commandPath, globals.planTemplate);
@@ -274,6 +283,10 @@ try {
274
283
  }
275
284
  catch (err) {
276
285
  const telemetryOutcome = classifyCliError(err);
286
+ const localProjectAdmissionFailure = telemetryLocalProject &&
287
+ err instanceof ApiError &&
288
+ err.code === 'VALIDATION_ERROR' &&
289
+ err.requestId === 'local';
277
290
  // Flush the outcome AFTER the error is rendered to stderr below (via each
278
291
  // branch's `flushThenSetExitCode`), so a slow backend never delays the
279
292
  // user's error. The classification mirrors the exit-code mapping the
@@ -288,12 +301,15 @@ catch (err) {
288
301
  // script/CI/agent that branches on it. Draining takes milliseconds and is
289
302
  // exactly how the success path above already exits.
290
303
  const flushThenSetExitCode = async (code) => {
291
- if (telemetryEmit) {
304
+ if (telemetryEmit && !localProjectAdmissionFailure) {
292
305
  await recordOutcome({
293
306
  command: ranCommandPath,
294
307
  outcome: telemetryOutcome.outcome,
295
308
  exitCode: telemetryOutcome.exitCode,
296
309
  errorCode: telemetryOutcome.errorCode,
310
+ errorOrigin: telemetryOutcome.errorOrigin,
311
+ timeoutSeconds: telemetryOutcome.timeoutSeconds,
312
+ ...waitTimeoutTelemetry,
297
313
  durationMs: Date.now() - telemetryStartedAt,
298
314
  ...telemetryGlobals(),
299
315
  local: telemetryLocal,
@@ -305,11 +321,15 @@ catch (err) {
305
321
  const mode = isOutputMode(rawMode) ? rawMode : 'text';
306
322
  const output = new Output(mode);
307
323
  if (err instanceof ApiError) {
324
+ const message = err.code === 'UNSUPPORTED' &&
325
+ err.getDetail('reason') === 'tunnel-unsupported-for-backend-test'
326
+ ? '--local only supports frontend tests today. Re-run without --local, or point the test at a reachable base URL.'
327
+ : err.message;
308
328
  if (mode === 'json') {
309
329
  const envelope = {
310
330
  error: {
311
331
  code: err.code,
312
- message: err.message,
332
+ message,
313
333
  nextAction: err.nextAction,
314
334
  requestId: err.requestId,
315
335
  details: err.details,
@@ -318,7 +338,7 @@ catch (err) {
318
338
  process.stderr.write(`${JSON.stringify(envelope, null, 2)}\n`);
319
339
  }
320
340
  else {
321
- process.stderr.write(`Error: ${err.message}\n`);
341
+ process.stderr.write(`Error: ${message}\n`);
322
342
  if (err.nextAction)
323
343
  process.stderr.write(`${err.nextAction}\n`);
324
344
  if (err.requestId && err.requestId !== 'local')
@@ -450,11 +470,19 @@ catch (err) {
450
470
  }
451
471
  }
452
472
  else if (err instanceof CLIError) {
453
- output.error(err.message);
473
+ // Same 5-key envelope shape as the ApiError/InterruptError/
474
+ // RequestTimeoutError branches above — `err.code` defaults to the
475
+ // out-of-catalog 'CLI_ERROR' bucket for a plain CLIError (see errors.ts).
476
+ output.error({ code: err.code, message: err.message });
454
477
  await flushThenSetExitCode(err.exitCode);
455
478
  }
456
479
  else {
457
- output.error(err instanceof Error ? err.message : String(err));
480
+ // Genuinely uncaught, non-CLIError exception. Prefer a real Node error
481
+ // code (ENOENT, ECONNREFUSED, …) when one is present; otherwise fall
482
+ // back to the same 'UNCAUGHT_EXCEPTION' bucket classifyCliError() uses,
483
+ // so the JSON envelope's code and the telemetry errorCode always agree.
484
+ const message = err instanceof Error ? err.message : String(err);
485
+ output.error({ code: extractNodeErrorCode(err) ?? 'UNCAUGHT_EXCEPTION', message });
458
486
  await flushThenSetExitCode(1);
459
487
  }
460
488
  }
@@ -1,4 +1,4 @@
1
- import type { FetchImpl } from './http.js';
1
+ import type { FetchImpl, HttpClientOptions } from './http.js';
2
2
  import { HttpClient } from './http.js';
3
3
  import type { OutputMode } from './output.js';
4
4
  export interface CommonOptions {
@@ -142,3 +142,6 @@ export declare function assertValidApiKeyHeaderValue(apiKey: string): void;
142
142
  */
143
143
  export declare function parseRequestTimeoutFlag(raw: string | undefined): number | undefined;
144
144
  export declare function makeHttpClient(opts: CommonOptions, deps?: ClientFactoryDeps): HttpClient;
145
+ export type HttpClientFactory = (overrides?: Pick<HttpClientOptions, 'requestTimeoutMs' | 'shutdownSignal'>) => HttpClient;
146
+ /** Resolve the profile once so related requests share an identity and endpoint. */
147
+ export declare function createHttpClientFactory(opts: CommonOptions, deps?: ClientFactoryDeps): HttpClientFactory;
@@ -191,6 +191,14 @@ export function parseRequestTimeoutFlag(raw) {
191
191
  return Math.round(n * 1000); // seconds → milliseconds
192
192
  }
193
193
  export function makeHttpClient(opts, deps = {}) {
194
+ return new HttpClient(resolveHttpClientOptions(opts, deps));
195
+ }
196
+ /** Resolve the profile once so related requests share an identity and endpoint. */
197
+ export function createHttpClientFactory(opts, deps = {}) {
198
+ const snapshot = Object.freeze(resolveHttpClientOptions(opts, deps));
199
+ return overrides => new HttpClient({ ...snapshot, ...overrides });
200
+ }
201
+ function resolveHttpClientOptions(opts, deps) {
194
202
  const stderr = deps.stderr ?? ((line) => process.stderr.write(`${line}\n`));
195
203
  const env = deps.env ?? process.env;
196
204
  const requestTimeoutMs = resolveRequestTimeoutMs(opts, env);
@@ -201,15 +209,16 @@ export function makeHttpClient(opts, deps = {}) {
201
209
  // endpoint doesn't first announce a "sample response".
202
210
  assertValidEndpointUrl(dryRunEndpoint);
203
211
  emitDryRunBanner(stderr);
204
- return new HttpClient({
212
+ return {
205
213
  baseUrl: facadeBaseUrl(dryRunEndpoint),
206
214
  apiKey: DRY_RUN_API_KEY,
207
215
  fetchImpl: deps.fetchImpl ?? createDryRunFetch(),
208
216
  onDebug: opts.debug ? (event) => stderr(formatDryRunDebug(event)) : undefined,
209
217
  onTransition: opts.verbose ? (msg) => stderr(`[verbose] ${msg}`) : undefined,
218
+ env,
210
219
  requestTimeoutMs,
211
220
  shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
212
- });
221
+ };
213
222
  }
214
223
  const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
215
224
  const config = loadConfig({
@@ -225,7 +234,7 @@ export function makeHttpClient(opts, deps = {}) {
225
234
  if (!config.apiKey)
226
235
  throw ApiError.authRequired();
227
236
  assertValidApiKey(config.apiKey);
228
- return new HttpClient({
237
+ return {
229
238
  baseUrl: facadeBaseUrl(config.apiUrl),
230
239
  apiKey: config.apiKey,
231
240
  fetchImpl: deps.fetchImpl,
@@ -242,9 +251,10 @@ export function makeHttpClient(opts, deps = {}) {
242
251
  dryRun: opts.dryRun,
243
252
  stderr,
244
253
  }),
254
+ env,
245
255
  requestTimeoutMs,
246
256
  shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
247
- });
257
+ };
248
258
  }
249
259
  function formatDebug(event) {
250
260
  return `[debug ${new Date().toISOString()}] ${JSON.stringify(event)}`;
@@ -0,0 +1,13 @@
1
+ /** Env var a wrapper (e.g. the GitHub Action) sets to identify itself. */
2
+ export declare const CLIENT_TAG_ENV = "TESTSPRITE_CLIENT";
3
+ /**
4
+ * The validated client tag from `env`, or undefined when unset or invalid.
5
+ * Pure — reads only the one variable it owns.
6
+ */
7
+ export declare function resolveClientTag(env: NodeJS.ProcessEnv): string | undefined;
8
+ /**
9
+ * The User-Agent every outgoing request (API + telemetry beacon) sends.
10
+ * `testsprite-cli/<version>`, with ` (<client>)` appended only for a valid
11
+ * {@link CLIENT_TAG_ENV} value.
12
+ */
13
+ export declare function buildUserAgent(env?: NodeJS.ProcessEnv): string;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Optional "client" identity a wrapper can stamp onto every request the CLI
3
+ * makes on its behalf — the GitHub Action sets `TESTSPRITE_CLIENT=github-action/<ref>`
4
+ * so the backend can tell an Action-driven run from a developer's shell without
5
+ * a second credential or a new header.
6
+ *
7
+ * Wire shape: the User-Agent becomes `testsprite-cli/<version> (<client>)`.
8
+ * Without the env var (or with an invalid value) the UA is byte-identical to
9
+ * what it has always been, `testsprite-cli/<version>`.
10
+ *
11
+ * The value is validated against a tight grammar — `<name>/<version>` where the
12
+ * name is lowercase alphanumeric plus `-` (≤32 chars) and the version is a
13
+ * short token of `[0-9A-Za-z._+-]` (≤40 chars) — so a caller can never smuggle
14
+ * header-breaking characters (spaces, parentheses, CR/LF) or free text into a
15
+ * request header. An invalid value is dropped silently and NEVER echoed: the
16
+ * tag rides on telemetry too, and a rejected value must not leak back into a
17
+ * log line either.
18
+ */
19
+ import { VERSION } from '../version.js';
20
+ /** Env var a wrapper (e.g. the GitHub Action) sets to identify itself. */
21
+ export const CLIENT_TAG_ENV = 'TESTSPRITE_CLIENT';
22
+ /** `<name>/<version>`: e.g. `github-action/v1`, `github-action/1.2.0`. */
23
+ const CLIENT_TAG_RE = /^[a-z0-9][a-z0-9-]{0,31}\/[0-9A-Za-z][0-9A-Za-z._+-]{0,39}$/;
24
+ /**
25
+ * The validated client tag from `env`, or undefined when unset or invalid.
26
+ * Pure — reads only the one variable it owns.
27
+ */
28
+ export function resolveClientTag(env) {
29
+ const raw = env[CLIENT_TAG_ENV];
30
+ if (typeof raw !== 'string')
31
+ return undefined;
32
+ return CLIENT_TAG_RE.test(raw) ? raw : undefined;
33
+ }
34
+ /**
35
+ * The User-Agent every outgoing request (API + telemetry beacon) sends.
36
+ * `testsprite-cli/<version>`, with ` (<client>)` appended only for a valid
37
+ * {@link CLIENT_TAG_ENV} value.
38
+ */
39
+ export function buildUserAgent(env = process.env) {
40
+ const base = `testsprite-cli/${VERSION}`;
41
+ const client = resolveClientTag(env);
42
+ return client === undefined ? base : `${base} (${client})`;
43
+ }
44
+ //# sourceMappingURL=client-tag.js.map