@testsprite/testsprite-cli 0.10.0 → 0.11.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 (42) hide show
  1. package/README.md +25 -2
  2. package/dist/commands/auth.d.ts +5 -1
  3. package/dist/commands/auth.js +17 -5
  4. package/dist/commands/init.d.ts +6 -1
  5. package/dist/commands/init.js +13 -5
  6. package/dist/commands/project.d.ts +9 -0
  7. package/dist/commands/project.js +89 -18
  8. package/dist/commands/test.d.ts +14 -2
  9. package/dist/commands/test.js +141 -33
  10. package/dist/commands/tunnel.d.ts +2 -2
  11. package/dist/commands/tunnel.js +139 -31
  12. package/dist/index.js +29 -11
  13. package/dist/lib/client-factory.d.ts +4 -1
  14. package/dist/lib/client-factory.js +12 -4
  15. package/dist/lib/credentials.d.ts +4 -0
  16. package/dist/lib/credentials.js +43 -4
  17. package/dist/lib/http.d.ts +14 -2
  18. package/dist/lib/http.js +38 -6
  19. package/dist/lib/response-schemas.d.ts +5 -2
  20. package/dist/lib/response-schemas.js +21 -1
  21. package/dist/lib/runs.types.d.ts +11 -0
  22. package/dist/lib/target-url.d.ts +1 -1
  23. package/dist/lib/target-url.js +4 -0
  24. package/dist/lib/telemetry.d.ts +6 -2
  25. package/dist/lib/telemetry.js +12 -0
  26. package/dist/lib/tunnel-session.d.ts +13 -2
  27. package/dist/lib/tunnel-session.js +92 -23
  28. package/dist/lib/tunnel.types.d.ts +3 -1
  29. package/dist/vendor/tunnel-client/client.d.ts +11 -0
  30. package/dist/vendor/tunnel-client/client.js +383 -56
  31. package/dist/vendor/tunnel-client/config.d.ts +11 -3
  32. package/dist/vendor/tunnel-client/config.js +11 -3
  33. package/dist/vendor/tunnel-client/types.d.ts +26 -1
  34. package/dist/vendor/tunnel-client/types.js +1 -0
  35. package/dist/vendor/tunnel-client/ws-compat.d.ts +3 -2
  36. package/dist/vendor/tunnel-client/ws-compat.js +3 -2
  37. package/dist/version.d.ts +1 -1
  38. package/dist/version.js +1 -1
  39. package/package.json +2 -1
  40. package/skills/testsprite-onboard.skill.md +74 -59
  41. package/skills/testsprite-verify.codex.md +82 -97
  42. package/skills/testsprite-verify.skill.md +62 -15
@@ -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
@@ -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,13 @@ 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
+ ...waitTimeoutTelemetry,
297
311
  durationMs: Date.now() - telemetryStartedAt,
298
312
  ...telemetryGlobals(),
299
313
  local: telemetryLocal,
@@ -305,11 +319,15 @@ catch (err) {
305
319
  const mode = isOutputMode(rawMode) ? rawMode : 'text';
306
320
  const output = new Output(mode);
307
321
  if (err instanceof ApiError) {
322
+ const message = err.code === 'UNSUPPORTED' &&
323
+ err.getDetail('reason') === 'tunnel-unsupported-for-backend-test'
324
+ ? '--local only supports frontend tests today. Re-run without --local, or point the test at a reachable base URL.'
325
+ : err.message;
308
326
  if (mode === 'json') {
309
327
  const envelope = {
310
328
  error: {
311
329
  code: err.code,
312
- message: err.message,
330
+ message,
313
331
  nextAction: err.nextAction,
314
332
  requestId: err.requestId,
315
333
  details: err.details,
@@ -318,7 +336,7 @@ catch (err) {
318
336
  process.stderr.write(`${JSON.stringify(envelope, null, 2)}\n`);
319
337
  }
320
338
  else {
321
- process.stderr.write(`Error: ${err.message}\n`);
339
+ process.stderr.write(`Error: ${message}\n`);
322
340
  if (err.nextAction)
323
341
  process.stderr.write(`${err.nextAction}\n`);
324
342
  if (err.requestId && err.requestId !== 'local')
@@ -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,7 +209,7 @@ 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(),
@@ -209,7 +217,7 @@ export function makeHttpClient(opts, deps = {}) {
209
217
  onTransition: opts.verbose ? (msg) => stderr(`[verbose] ${msg}`) : undefined,
210
218
  requestTimeoutMs,
211
219
  shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
212
- });
220
+ };
213
221
  }
214
222
  const credentialsPath = deps.credentialsPath ?? defaultCredentialsPath();
215
223
  const config = loadConfig({
@@ -225,7 +233,7 @@ export function makeHttpClient(opts, deps = {}) {
225
233
  if (!config.apiKey)
226
234
  throw ApiError.authRequired();
227
235
  assertValidApiKey(config.apiKey);
228
- return new HttpClient({
236
+ return {
229
237
  baseUrl: facadeBaseUrl(config.apiUrl),
230
238
  apiKey: config.apiKey,
231
239
  fetchImpl: deps.fetchImpl,
@@ -244,7 +252,7 @@ export function makeHttpClient(opts, deps = {}) {
244
252
  }),
245
253
  requestTimeoutMs,
246
254
  shutdownSignal: deps.shutdownSignal ?? globalShutdown.signal,
247
- });
255
+ };
248
256
  }
249
257
  function formatDebug(event) {
250
258
  return `[debug ${new Date().toISOString()}] ${JSON.stringify(event)}`;
@@ -16,6 +16,10 @@ export type CredentialsFile = Record<string, ProfileEntry>;
16
16
  export interface CredentialsOptions {
17
17
  path?: string;
18
18
  }
19
+ type CredentialsWritePermissionError = NodeJS.ErrnoException & {
20
+ code: 'EPERM' | 'EACCES' | 'EROFS';
21
+ };
22
+ export declare function isCredentialsWritePermissionError(error: unknown): error is CredentialsWritePermissionError;
19
23
  interface RestrictiveModeOptions {
20
24
  platform?: NodeJS.Platform;
21
25
  env?: NodeJS.ProcessEnv;
@@ -34,6 +34,19 @@ export function assertValidProfileName(profile) {
34
34
  export function defaultCredentialsPath() {
35
35
  return join(homedir(), '.testsprite', 'credentials');
36
36
  }
37
+ // Keep the original errno object and distinguish write permissions from errors
38
+ // while reading profiles, recovering locks, or tightening file permissions.
39
+ const writePermissionErrors = new WeakSet();
40
+ export function isCredentialsWritePermissionError(error) {
41
+ return error instanceof Error && writePermissionErrors.has(error);
42
+ }
43
+ function rethrowCredentialsWriteError(error) {
44
+ if (isErrnoException(error) &&
45
+ (error.code === 'EPERM' || error.code === 'EACCES' || error.code === 'EROFS')) {
46
+ writePermissionErrors.add(error);
47
+ }
48
+ throw error;
49
+ }
37
50
  const FILE_KEY_TO_FIELD = {
38
51
  api_key: 'apiKey',
39
52
  api_url: 'apiUrl',
@@ -195,7 +208,13 @@ function resolvePath(options) {
195
208
  return options.path ?? defaultCredentialsPath();
196
209
  }
197
210
  function mutateCredentialsFile(path, mutate) {
198
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
211
+ try {
212
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- `path` is the credentials-file path this module already operates on (default `~/.testsprite/credentials`, or the caller-supplied `CredentialsOptions.path`), not new external input; same risk profile as the baselined fs calls in this file.
213
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
214
+ }
215
+ catch (error) {
216
+ rethrowCredentialsWriteError(error);
217
+ }
199
218
  const lock = acquireCredentialsLock(path);
200
219
  try {
201
220
  const file = readCredentialsFile({ path });
@@ -211,8 +230,28 @@ function mutateCredentialsFile(path, mutate) {
211
230
  }
212
231
  function writeCredentialsAtomic(path, file) {
213
232
  const tmp = `${path}.tmp.${process.pid}`;
214
- writeFileSync(tmp, serializeCredentials(file), { mode: 0o600, encoding: 'utf8' });
215
- renameSync(tmp, path);
233
+ try {
234
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- `tmp` is `${path}.tmp.${pid}`, derived from the same internal credentials-file path; same baselined risk profile as the other fs calls in this file.
235
+ writeFileSync(tmp, serializeCredentials(file), { mode: 0o600, encoding: 'utf8' });
236
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- both operands derive from the internal credentials-file path (see above).
237
+ renameSync(tmp, path);
238
+ }
239
+ catch (error) {
240
+ try {
241
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- best-effort cleanup of the temp file this function just created; same internal path.
242
+ unlinkSync(tmp);
243
+ }
244
+ catch (cleanupError) {
245
+ if (!isErrnoException(cleanupError) || cleanupError.code !== 'ENOENT') {
246
+ // Do not mark this as a permission error eligible for session-only setup:
247
+ // the temporary file can still contain the API key.
248
+ throw new Error(`Temporary credentials could not be cleaned up at ${tmp}.`, {
249
+ cause: cleanupError,
250
+ });
251
+ }
252
+ }
253
+ rethrowCredentialsWriteError(error);
254
+ }
216
255
  ensureRestrictiveMode(path);
217
256
  }
218
257
  function acquireCredentialsLock(path) {
@@ -238,7 +277,7 @@ function acquireCredentialsLock(path) {
238
277
  }
239
278
  catch (error) {
240
279
  if (!isErrnoException(error) || error.code !== 'EEXIST') {
241
- throw error;
280
+ rethrowCredentialsWriteError(error);
242
281
  }
243
282
  reclaimStaleCredentialsLock(lockPath);
244
283
  if (Date.now() >= deadline) {
@@ -124,7 +124,7 @@ export interface RequestOptions<T = unknown> {
124
124
  *
125
125
  * Wired by the typed run helpers only (`triggerRun`, `triggerRunWithMeta`,
126
126
  * `triggerRerun`, `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`,
127
- * `listTestRuns`); generic `get`/`post`/... callers stay opt-in.
127
+ * `listTestRuns`, `cancelRun`); generic `get`/`post`/... callers stay opt-in.
128
128
  * sourceRef: response-schemas.ts.
129
129
  */
130
130
  schema?: v.GenericSchema<unknown, T>;
@@ -175,6 +175,15 @@ export interface RequestOptions<T = unknown> {
175
175
  */
176
176
  retry?: boolean;
177
177
  }
178
+ /**
179
+ * 429 reasons that name a STANDING condition rather than a passing throttle —
180
+ * e.g. the per-user cap on live tunnel bindings. Retrying cannot succeed until
181
+ * the caller frees the resource, so the retry budget is skipped and the
182
+ * server's nextAction (e.g. `testsprite tunnel stop`) surfaces immediately.
183
+ */
184
+ export declare const STANDING_RATE_LIMIT_REASONS: ReadonlySet<string>;
185
+ /** True for a RATE_LIMITED error whose envelope names a standing condition. */
186
+ export declare function isStandingRateLimit(err: ApiError): boolean;
178
187
  /**
179
188
  * Result of a successful HTTP request, including the parsed body and the
180
189
  * `x-request-id` that was sent (useful for surfacing in happy-path output).
@@ -311,7 +320,10 @@ export declare class HttpClient {
311
320
  * than `pageSize` rows while still yielding a non-null `nextCursor`.
312
321
  * That means "none in THIS window", not end-of-history.
313
322
  */
314
- listTestRuns(testId: string, query: ListRunsQuery): Promise<ListRunsResponse>;
323
+ listTestRuns(testId: string, query: ListRunsQuery, options?: {
324
+ signal?: AbortSignal;
325
+ retry?: boolean;
326
+ }): Promise<ListRunsResponse>;
315
327
  /**
316
328
  * GET /api/cli/v1/runs/{runId}
317
329
  * Fetch the current state of a run. When `waitSeconds` is provided