@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
@@ -67,6 +67,12 @@ export interface HttpClientOptions {
67
67
  onServerVersion?: (info: {
68
68
  minVersion?: string;
69
69
  }) => void;
70
+ /**
71
+ * Environment the client reads the optional `TESTSPRITE_CLIENT` tag from
72
+ * (see `client-tag.ts`) to build its User-Agent. Defaults to `process.env`;
73
+ * injectable so tests never depend on the developer's shell.
74
+ */
75
+ env?: NodeJS.ProcessEnv;
70
76
  /**
71
77
  * Per-request wall-clock timeout in milliseconds applied to every outgoing
72
78
  * fetch. The signal fires independently of any caller-supplied signal — the
@@ -124,7 +130,7 @@ export interface RequestOptions<T = unknown> {
124
130
  *
125
131
  * Wired by the typed run helpers only (`triggerRun`, `triggerRunWithMeta`,
126
132
  * `triggerRerun`, `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`,
127
- * `listTestRuns`); generic `get`/`post`/... callers stay opt-in.
133
+ * `listTestRuns`, `cancelRun`); generic `get`/`post`/... callers stay opt-in.
128
134
  * sourceRef: response-schemas.ts.
129
135
  */
130
136
  schema?: v.GenericSchema<unknown, T>;
@@ -175,6 +181,15 @@ export interface RequestOptions<T = unknown> {
175
181
  */
176
182
  retry?: boolean;
177
183
  }
184
+ /**
185
+ * 429 reasons that name a STANDING condition rather than a passing throttle —
186
+ * e.g. the per-user cap on live tunnel bindings. Retrying cannot succeed until
187
+ * the caller frees the resource, so the retry budget is skipped and the
188
+ * server's nextAction (e.g. `testsprite tunnel stop`) surfaces immediately.
189
+ */
190
+ export declare const STANDING_RATE_LIMIT_REASONS: ReadonlySet<string>;
191
+ /** True for a RATE_LIMITED error whose envelope names a standing condition. */
192
+ export declare function isStandingRateLimit(err: ApiError): boolean;
178
193
  /**
179
194
  * Result of a successful HTTP request, including the parsed body and the
180
195
  * `x-request-id` that was sent (useful for surfacing in happy-path output).
@@ -196,6 +211,7 @@ export declare class HttpClient {
196
211
  private readonly requestTimeoutMs;
197
212
  private readonly shutdownSignal?;
198
213
  private readonly maxResponseBytes;
214
+ private readonly userAgent;
199
215
  constructor(options: HttpClientOptions);
200
216
  /** The resolved facade base URL (trailing slash trimmed). Read-only —
201
217
  * callers that bypass the client for a side-channel request (e.g. the
@@ -311,7 +327,10 @@ export declare class HttpClient {
311
327
  * than `pageSize` rows while still yielding a non-null `nextCursor`.
312
328
  * That means "none in THIS window", not end-of-history.
313
329
  */
314
- listTestRuns(testId: string, query: ListRunsQuery): Promise<ListRunsResponse>;
330
+ listTestRuns(testId: string, query: ListRunsQuery, options?: {
331
+ signal?: AbortSignal;
332
+ retry?: boolean;
333
+ }): Promise<ListRunsResponse>;
315
334
  /**
316
335
  * GET /api/cli/v1/runs/{runId}
317
336
  * Fetch the current state of a run. When `waitSeconds` is provided
package/dist/lib/http.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import * as v from 'valibot';
3
3
  import { ApiError, InterruptError, RequestTimeoutError, TransportError } from './errors.js';
4
- import { VERSION } from '../version.js';
5
- import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TESTLIST_RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, TUNNEL_MINT_RESPONSE_SCHEMA, TUNNEL_STATUS_RESPONSE_SCHEMA, } from './response-schemas.js';
4
+ import { buildUserAgent } from './client-tag.js';
5
+ import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, CANCEL_RUN_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TESTLIST_RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, TUNNEL_MINT_RESPONSE_SCHEMA, TUNNEL_STATUS_RESPONSE_SCHEMA, } from './response-schemas.js';
6
6
  /**
7
7
  * Default per-request timeout (120s). Comfortably covers every metadata/read
8
8
  * request and every <=25s long-poll request (`?waitSeconds` is capped at 25
@@ -39,6 +39,20 @@ const MAX_ATTEMPTS_INTERNAL = 2;
39
39
  // Cap server-directed RATE_LIMITED waits so a hostile or misconfigured
40
40
  // `Retry-After` (e.g. 86400) can't hang the CLI inside the retry sleep.
41
41
  const MAX_RATE_LIMITED_DELAY_MS = 60_000;
42
+ /**
43
+ * 429 reasons that name a STANDING condition rather than a passing throttle —
44
+ * e.g. the per-user cap on live tunnel bindings. Retrying cannot succeed until
45
+ * the caller frees the resource, so the retry budget is skipped and the
46
+ * server's nextAction (e.g. `testsprite tunnel stop`) surfaces immediately.
47
+ */
48
+ export const STANDING_RATE_LIMIT_REASONS = new Set(['tunnel_binding_limit']);
49
+ /** True for a RATE_LIMITED error whose envelope names a standing condition. */
50
+ export function isStandingRateLimit(err) {
51
+ if (err.code !== 'RATE_LIMITED')
52
+ return false;
53
+ const reason = err.getDetail('reason', (v) => typeof v === 'string');
54
+ return reason !== undefined && STANDING_RATE_LIMIT_REASONS.has(reason);
55
+ }
42
56
  const CONFLICT_DELAY_MS = 1000;
43
57
  const INTERNAL_DELAY_MS = 500;
44
58
  // Upper bound on the size of a successful JSON response body the client will
@@ -65,10 +79,13 @@ export class HttpClient {
65
79
  requestTimeoutMs;
66
80
  shutdownSignal;
67
81
  maxResponseBytes;
82
+ userAgent;
68
83
  constructor(options) {
69
84
  this.baseUrl = trimTrailingSlash(options.baseUrl);
70
85
  this.apiKey = options.apiKey;
71
86
  this.shutdownSignal = options.shutdownSignal;
87
+ // Resolved once: the tag is process-wide configuration, not per-request.
88
+ this.userAgent = buildUserAgent(options.env ?? process.env);
72
89
  this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
73
90
  this.sleep = options.sleep ?? defaultSleep;
74
91
  this.random = options.random ?? Math.random;
@@ -259,7 +276,7 @@ export class HttpClient {
259
276
  * than `pageSize` rows while still yielding a non-null `nextCursor`.
260
277
  * That means "none in THIS window", not end-of-history.
261
278
  */
262
- async listTestRuns(testId, query) {
279
+ async listTestRuns(testId, query, options = {}) {
263
280
  const q = {};
264
281
  if (query.cursor !== undefined)
265
282
  q.cursor = query.cursor;
@@ -269,8 +286,12 @@ export class HttpClient {
269
286
  q.source = query.source;
270
287
  if (query.since !== undefined)
271
288
  q.since = query.since;
289
+ if (query.environment !== undefined)
290
+ q.environment = query.environment;
272
291
  return this.get(`/tests/${encodeURIComponent(testId)}/runs`, {
273
292
  query: q,
293
+ signal: options.signal,
294
+ retry: options.retry,
274
295
  schema: LIST_RUNS_RESPONSE_SCHEMA,
275
296
  });
276
297
  }
@@ -366,6 +387,7 @@ export class HttpClient {
366
387
  async cancelRun(runId, options) {
367
388
  return this.post(`/runs/${encodeURIComponent(runId)}/cancel`, {
368
389
  signal: options?.signal,
390
+ schema: CANCEL_RUN_RESPONSE_SCHEMA,
369
391
  retryOnConflict: false,
370
392
  });
371
393
  }
@@ -699,7 +721,10 @@ export class HttpClient {
699
721
  durationMs,
700
722
  });
701
723
  const retryOnConflict = options.retryOnConflict !== false;
702
- const retryOnRateLimit = options.retryOnRateLimit !== false;
724
+ // A standing-condition 429 skips the retry budget outright: its
725
+ // Retry-After says when a retry COULD first succeed if the caller
726
+ // frees the resource, not that the condition clears on its own.
727
+ const retryOnRateLimit = options.retryOnRateLimit !== false && !isStandingRateLimit(apiError);
703
728
  const decision = allowRetry
704
729
  ? apiRetryDecision(apiError.code, attempt, retryAfterSec, this.random, retryOnConflict, retryOnRateLimit)
705
730
  : { retry: false, delayMs: 0 };
@@ -741,7 +766,7 @@ export class HttpClient {
741
766
  const headers = {
742
767
  'x-request-id': requestId,
743
768
  accept: 'application/json',
744
- 'user-agent': `testsprite-cli/${VERSION}`,
769
+ 'user-agent': this.userAgent,
745
770
  };
746
771
  // The CLI v1 facade authenticates via `x-api-key`.
747
772
  // (securitySchemes.ApiKeyAuth). Sending only Authorization Bearer would be
@@ -775,7 +800,7 @@ export class HttpClient {
775
800
  return new Promise((resolve, reject) => {
776
801
  const onAbort = () => reject(signal.reason);
777
802
  signal.addEventListener('abort', onAbort, { once: true });
778
- this.sleep(ms).then(() => {
803
+ this.sleep(ms, signal).then(() => {
779
804
  signal.removeEventListener('abort', onAbort);
780
805
  resolve();
781
806
  }, err => {
@@ -1153,8 +1178,20 @@ function backoffDelay(attempt, random) {
1153
1178
  const jitter = Math.floor(random() * RETRY_JITTER_MS);
1154
1179
  return Math.min(base + jitter, RETRY_MAX_DELAY_MS);
1155
1180
  }
1156
- function defaultSleep(ms) {
1157
- return new Promise(resolve => setTimeout(resolve, ms));
1181
+ function defaultSleep(ms, signal) {
1182
+ if (signal?.aborted)
1183
+ return Promise.reject(signal.reason);
1184
+ return new Promise((resolve, reject) => {
1185
+ const onAbort = () => {
1186
+ clearTimeout(timer);
1187
+ reject(signal?.reason);
1188
+ };
1189
+ const timer = setTimeout(() => {
1190
+ signal?.removeEventListener('abort', onAbort);
1191
+ resolve();
1192
+ }, ms);
1193
+ signal?.addEventListener('abort', onAbort, { once: true });
1194
+ });
1158
1195
  }
1159
1196
  function isAbortError(err) {
1160
1197
  if (err instanceof Error && err.name === 'AbortError')
@@ -69,6 +69,38 @@ export declare function parseLocalPort(raw: string): number;
69
69
  * misunderstanding to correct immediately, not a request to forward.
70
70
  */
71
71
  export declare function normalizeLocalHost(raw: string | undefined): LoopbackHost;
72
+ /**
73
+ * `normalizeLocalHost` for a command whose alternative to `--local` is `--url`
74
+ * (`project create/update`, `project env create/update`) rather than
75
+ * `--target-url`, so the refusal names the flag that command actually has.
76
+ */
77
+ export declare function normalizeStoredLocalHost(raw: string | undefined): LoopbackHost;
78
+ /** The target `--local <port> [--local-host]` names on a project or environment write. */
79
+ export interface StoredLocalTarget {
80
+ host: LoopbackHost;
81
+ port: number;
82
+ }
83
+ /**
84
+ * Parse the `--local` / `--local-host` / `--url` trio a stored-target write
85
+ * takes. `--local` and `--url` are two spellings of one field, so both is a
86
+ * contradiction; `--local-host` only means something next to `--local`; the
87
+ * port is validated strictly because it becomes part of a URL runs are billed
88
+ * against. Returns the local target, or `undefined` when `--url` (or nothing)
89
+ * was given.
90
+ */
91
+ export declare function parseStoredLocalTarget(opts: {
92
+ local?: string;
93
+ localHost?: string;
94
+ url?: string;
95
+ }): StoredLocalTarget | undefined;
96
+ /**
97
+ * Refuse a stored-target write whose loopback port has nothing listening —
98
+ * the same check `project create --local` runs, so a typo in the port is
99
+ * caught before a row exists anywhere. `skipPreflight` is a pure no-op.
100
+ */
101
+ export declare function assertStoredLocalTargetListening(target: StoredLocalTarget, opts: {
102
+ skipPreflight?: boolean;
103
+ }, deps?: LocalPortProbeDeps): Promise<void>;
72
104
  /** `http://<host>:<port>`, with IPv6 bracketed as the URL grammar requires. */
73
105
  export declare function buildLocalTargetUrl(host: LoopbackHost, port: number): string;
74
106
  /**
@@ -73,6 +73,83 @@ export function normalizeLocalHost(raw) {
73
73
  }
74
74
  return match;
75
75
  }
76
+ /**
77
+ * `normalizeLocalHost` for a command whose alternative to `--local` is `--url`
78
+ * (`project create/update`, `project env create/update`) rather than
79
+ * `--target-url`, so the refusal names the flag that command actually has.
80
+ */
81
+ export function normalizeStoredLocalHost(raw) {
82
+ try {
83
+ return normalizeLocalHost(raw);
84
+ }
85
+ catch (err) {
86
+ if (err instanceof ApiError && typeof err.details?.reason === 'string') {
87
+ throw localValidationError('local-host', err.details.reason.replace('--target-url', '--url'), err.details.accepted);
88
+ }
89
+ throw err;
90
+ }
91
+ }
92
+ /**
93
+ * Parse the `--local` / `--local-host` / `--url` trio a stored-target write
94
+ * takes. `--local` and `--url` are two spellings of one field, so both is a
95
+ * contradiction; `--local-host` only means something next to `--local`; the
96
+ * port is validated strictly because it becomes part of a URL runs are billed
97
+ * against. Returns the local target, or `undefined` when `--url` (or nothing)
98
+ * was given.
99
+ */
100
+ export function parseStoredLocalTarget(opts) {
101
+ if (opts.local !== undefined && opts.url !== undefined) {
102
+ throw flagPairError('--local and --url are mutually exclusive');
103
+ }
104
+ if (opts.localHost !== undefined && opts.local === undefined) {
105
+ throw flagPairError('--local-host requires --local');
106
+ }
107
+ if (opts.local === undefined)
108
+ return undefined;
109
+ if (!/^\d+$/.test(opts.local)) {
110
+ throw flagPairError('--local must be a port number between 1 and 65535');
111
+ }
112
+ return { host: normalizeStoredLocalHost(opts.localHost), port: parseLocalPort(opts.local) };
113
+ }
114
+ function flagPairError(message) {
115
+ return ApiError.fromEnvelope({
116
+ error: {
117
+ code: 'VALIDATION_ERROR',
118
+ message: 'Invalid request.',
119
+ nextAction: message,
120
+ requestId: 'local',
121
+ details: { reason: 'missing_required_flag' },
122
+ },
123
+ });
124
+ }
125
+ /**
126
+ * Refuse a stored-target write whose loopback port has nothing listening —
127
+ * the same check `project create --local` runs, so a typo in the port is
128
+ * caught before a row exists anywhere. `skipPreflight` is a pure no-op.
129
+ */
130
+ export async function assertStoredLocalTargetListening(target, opts, deps = {}) {
131
+ if (opts.skipPreflight)
132
+ return;
133
+ const outcome = await probeLocalPort(target.host, target.port, deps);
134
+ if (outcome.verdict === 'refuse') {
135
+ const targetUrl = buildLocalTargetUrl(target.host, target.port);
136
+ throw ApiError.fromEnvelope({
137
+ error: {
138
+ code: 'VALIDATION_ERROR',
139
+ message: `Nothing is listening on ${targetUrl}. Start your app first, or pass --skip-preflight.`,
140
+ nextAction: 'Verify --local and --local-host match the app you want to test.',
141
+ requestId: 'local',
142
+ details: {
143
+ field: 'local',
144
+ reason: 'local-port-not-listening',
145
+ host: target.host,
146
+ port: target.port,
147
+ probeReason: outcome.reason,
148
+ },
149
+ },
150
+ });
151
+ }
152
+ }
76
153
  /** `http://<host>:<port>`, with IPv6 bracketed as the URL grammar requires. */
77
154
  export function buildLocalTargetUrl(host, port) {
78
155
  const authority = host.includes(':') ? `[${host}]` : host;
@@ -21,6 +21,22 @@ export declare function isOutputMode(value: unknown): value is OutputMode;
21
21
  * helper so the validation is uniform.
22
22
  */
23
23
  export declare function resolveOutputMode(raw: unknown): OutputMode;
24
+ /**
25
+ * Input to {@link Output.error} — the same 5-key shape as the hand-built
26
+ * envelopes in `index.ts`'s ApiError / InterruptError / RequestTimeoutError
27
+ * catch branches (`{error:{code,message,nextAction,requestId,details}}`).
28
+ * Only `code` and `message` are required; the rest default to the
29
+ * client-local values (`''`, `'local'`, `{}`) so every `--output json` error
30
+ * — regardless of which catch branch produced it — renders the identical
31
+ * envelope shape.
32
+ */
33
+ export interface ErrorEnvelopeInput {
34
+ code: string;
35
+ message: string;
36
+ nextAction?: string;
37
+ requestId?: string;
38
+ details?: Record<string, unknown>;
39
+ }
24
40
  export interface OutputStreams {
25
41
  /**
26
42
  * Line-oriented stdout writer. Each call is one logical line; the
@@ -66,5 +82,15 @@ export declare class Output {
66
82
  * contract.
67
83
  */
68
84
  writeChunk(text: string): Promise<void>;
69
- error(message: string): void;
85
+ /**
86
+ * Render a terminal error. JSON mode always emits the SAME 5-key envelope
87
+ * shape as the ApiError / InterruptError / RequestTimeoutError branches
88
+ * hand-build in `index.ts`'s catch (`{error:{code,message,nextAction,
89
+ * requestId,details}}`) — before this, the only two callers of
90
+ * this method (the plain-CLIError and uncaught-exception catch branches)
91
+ * fell through to a bare `{"error":"<message>"}` string, breaking the
92
+ * envelope contract that machine consumers (`--output json` scripts/CI/
93
+ * agents) rely on for every other error path.
94
+ */
95
+ error(input: ErrorEnvelopeInput): void;
70
96
  }
@@ -66,12 +66,31 @@ export class Output {
66
66
  async writeChunk(text) {
67
67
  await this.rawStdoutWrite(text);
68
68
  }
69
- error(message) {
69
+ /**
70
+ * Render a terminal error. JSON mode always emits the SAME 5-key envelope
71
+ * shape as the ApiError / InterruptError / RequestTimeoutError branches
72
+ * hand-build in `index.ts`'s catch (`{error:{code,message,nextAction,
73
+ * requestId,details}}`) — before this, the only two callers of
74
+ * this method (the plain-CLIError and uncaught-exception catch branches)
75
+ * fell through to a bare `{"error":"<message>"}` string, breaking the
76
+ * envelope contract that machine consumers (`--output json` scripts/CI/
77
+ * agents) rely on for every other error path.
78
+ */
79
+ error(input) {
70
80
  if (this.mode === 'json') {
71
- this.stderrWrite(JSON.stringify({ error: message }, null, 2));
81
+ const envelope = {
82
+ error: {
83
+ code: input.code,
84
+ message: input.message,
85
+ nextAction: input.nextAction ?? '',
86
+ requestId: input.requestId ?? 'local',
87
+ details: input.details ?? {},
88
+ },
89
+ };
90
+ this.stderrWrite(JSON.stringify(envelope, null, 2));
72
91
  return;
73
92
  }
74
- this.stderrWrite(`Error: ${message}`);
93
+ this.stderrWrite(`Error: ${input.message}`);
75
94
  }
76
95
  }
77
96
  /**
@@ -6,7 +6,8 @@
6
6
  * `undefined` output or an opaque TypeError deep inside a command. These
7
7
  * schemas are wired (opt-in, via `RequestOptions.schema`) into the typed
8
8
  * HttpClient helpers only: `triggerRun`, `triggerRunWithMeta`, `triggerRerun`,
9
- * `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`, `listTestRuns`.
9
+ * `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`, `listTestRuns`,
10
+ * `cancelRun`.
10
11
  * The generic `get`/`post`/`put`/`patch`/`delete` paths stay schema-free.
11
12
  *
12
13
  * Resilience rules (additive server changes must never hard-fail the CLI):
@@ -32,11 +33,13 @@
32
33
  * interface it mirrors, so schema/interface drift fails `tsc` in this file.
33
34
  */
34
35
  import * as v from 'valibot';
35
- import type { BatchRerunResponse, BatchRunFreshResponse, ListRunsResponse, RerunResponse, RunResponse, TriggerRunResponse } from './runs.types.js';
36
+ import type { BatchRerunResponse, BatchRunFreshResponse, CancelRunResponse, ListRunsResponse, RerunResponse, RunResponse, TriggerRunResponse } from './runs.types.js';
36
37
  import type { CliTestListRunResponse } from './testlist.types.js';
37
38
  import type { TunnelMintResponse, TunnelStatusResponse } from './tunnel.types.js';
38
39
  /** Mirrors `RunResponse` (runs.types.ts): `GET /api/cli/v1/runs/{runId}`. */
39
40
  export declare const RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, RunResponse>;
41
+ /** Mirrors `CancelRunResponse` (runs.types.ts): the run envelope plus cancel metadata. */
42
+ export declare const CANCEL_RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, CancelRunResponse>;
40
43
  /** Mirrors `TriggerRunResponse` (runs.types.ts): `POST /tests/{testId}/runs`. */
41
44
  export declare const TRIGGER_RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, TriggerRunResponse>;
42
45
  /** Mirrors `RerunResponse` (runs.types.ts): `POST /tests/{testId}/runs/rerun`. */
@@ -6,7 +6,8 @@
6
6
  * `undefined` output or an opaque TypeError deep inside a command. These
7
7
  * schemas are wired (opt-in, via `RequestOptions.schema`) into the typed
8
8
  * HttpClient helpers only: `triggerRun`, `triggerRunWithMeta`, `triggerRerun`,
9
- * `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`, `listTestRuns`.
9
+ * `triggerBatchRerun`, `triggerBatchRunFresh`, `getRun`, `listTestRuns`,
10
+ * `cancelRun`.
10
11
  * The generic `get`/`post`/`put`/`patch`/`delete` paths stay schema-free.
11
12
  *
12
13
  * Resilience rules (additive server changes must never hard-fail the CLI):
@@ -43,6 +44,18 @@ import * as v from 'valibot';
43
44
  function openWireLiteral() {
44
45
  return v.custom(value => typeof value === 'string');
45
46
  }
47
+ /**
48
+ * Mirrors `RunEnvironmentRef` (runs.types.ts): the environment a run resolved to.
49
+ * Optional + nullable everywhere it appears: absent on an older backend, `null`
50
+ * when the row carries no stamp — both mean "unknown" to every renderer.
51
+ */
52
+ const RUN_ENVIRONMENT_REF_SCHEMA = v.looseObject({
53
+ // Either half may be null: a backfilled row whose environment was deleted
54
+ // keeps the denormalised name but no id, and a pre-name row keeps the id only.
55
+ id: v.nullable(v.string()),
56
+ name: v.nullable(v.string()),
57
+ });
58
+ const OPTIONAL_ENVIRONMENT_SCHEMA = v.optional(v.nullable(RUN_ENVIRONMENT_REF_SCHEMA));
46
59
  // ---------------------------------------------------------------------------
47
60
  // GET /runs/{runId}
48
61
  // ---------------------------------------------------------------------------
@@ -86,6 +99,8 @@ export const RUN_RESPONSE_SCHEMA = v.looseObject({
86
99
  // when either is null (rule 3).
87
100
  codeVersion: v.nullish(v.string(), null),
88
101
  targetUrl: v.nullish(v.string(), null),
102
+ // The run's environment — optional with no default (rule 3, optional branch).
103
+ environment: OPTIONAL_ENVIRONMENT_SCHEMA,
89
104
  createdFrom: v.nullish(v.string(), null),
90
105
  failedStepIndex: v.nullish(v.number(), null),
91
106
  failureKind: v.nullish(v.string(), null),
@@ -133,6 +148,24 @@ export const RUN_RESPONSE_SCHEMA = v.looseObject({
133
148
  steps: v.optional(v.nullable(v.array(RUN_STEP_DTO_SCHEMA))),
134
149
  });
135
150
  // ---------------------------------------------------------------------------
151
+ // POST /runs/{runId}/cancel
152
+ // ---------------------------------------------------------------------------
153
+ /** Mirrors `CancelRunRefund` (runs.types.ts): optional V3 frontend refund result. */
154
+ const CANCEL_RUN_REFUND_SCHEMA = v.looseObject({
155
+ status: openWireLiteral(),
156
+ amount: v.optional(v.number()),
157
+ });
158
+ /** Mirrors `CancelRunResponse` (runs.types.ts): the run envelope plus cancel metadata. */
159
+ export const CANCEL_RUN_RESPONSE_SCHEMA = v.intersect([
160
+ RUN_RESPONSE_SCHEMA,
161
+ v.looseObject({
162
+ alreadyCancelled: v.boolean(),
163
+ // Older backends, V2 runs, and backend-test runs omit this field. No
164
+ // default: absence must stay absent so JSON output passes through unchanged.
165
+ refund: v.optional(CANCEL_RUN_REFUND_SCHEMA),
166
+ }),
167
+ ]);
168
+ // ---------------------------------------------------------------------------
136
169
  // POST /tests/{testId}/runs
137
170
  // ---------------------------------------------------------------------------
138
171
  /** Mirrors `TriggerRunResponse` (runs.types.ts): `POST /tests/{testId}/runs`. */
@@ -142,6 +175,8 @@ export const TRIGGER_RUN_RESPONSE_SCHEMA = v.looseObject({
142
175
  enqueuedAt: v.string(),
143
176
  codeVersion: v.string(),
144
177
  targetUrl: v.string(),
178
+ // The run's environment — optional with no default (rule 3, optional branch).
179
+ environment: OPTIONAL_ENVIRONMENT_SCHEMA,
145
180
  // Server-built portal links (backend ≥ the run-links change). Optional
146
181
  // with no default (rule 3): an older backend omits them, and a V3 run
147
182
  // the server could not link stays ABSENT — the renderer prints a
@@ -287,6 +322,8 @@ const RUN_HISTORY_ITEM_SCHEMA = v.looseObject({
287
322
  // G1b fields: optional on the wire for back-compat with older backends.
288
323
  targetUrl: v.optional(v.nullable(v.string())),
289
324
  targetUrlSource: v.optional(v.nullable(openWireLiteral())),
325
+ // The run's environment — optional with no default.
326
+ environment: OPTIONAL_ENVIRONMENT_SCHEMA,
290
327
  });
291
328
  /** Mirrors `ListRunsResponse` (runs.types.ts): `GET /tests/{testId}/runs`. */
292
329
  export const LIST_RUNS_RESPONSE_SCHEMA = v.looseObject({
@@ -339,6 +376,7 @@ export const TUNNEL_MINT_RESPONSE_SCHEMA = v.looseObject({
339
376
  secret: v.pipe(v.string(), v.minLength(1)),
340
377
  controlUrl: v.pipe(v.string(), v.minLength(1)),
341
378
  tunnelAddr: v.pipe(v.string(), v.minLength(1)),
379
+ tunnelTlsAddr: v.optional(v.pipe(v.string(), v.minLength(1))),
342
380
  expiresAt: v.string(),
343
381
  });
344
382
  /** Mirrors `TunnelStatusResponse` (tunnel.types.ts): `GET /tunnel/{clientId}`. */
@@ -22,6 +22,21 @@ export interface TriggerRunBody {
22
22
  * dropping the field.
23
23
  */
24
24
  tunnelClientId?: string;
25
+ /**
26
+ * DEV-1305: the NAME of the project environment whose credentials, auto-auth
27
+ * and OTP settings this run should use (`unique(project_id, name)` server
28
+ * side). Absent → the project's default environment, exactly as before.
29
+ * Composes with `targetUrl`/`tunnelClientId`: those pick WHERE the browser
30
+ * goes, this picks WHOSE credentials it logs in with.
31
+ */
32
+ environment?: string;
33
+ }
34
+ /** The environment a run resolved to — its credentials, its config, its address. */
35
+ export interface RunEnvironmentRef {
36
+ /** `test_environment.id`; null when the row keeps only the denormalised name. */
37
+ id: string | null;
38
+ /** Environment name at seed time; null on an id-only row. */
39
+ name: string | null;
25
40
  }
26
41
  /**
27
42
  * Body sent to `POST /api/cli/v1/tests/{testId}/runs/rerun`.
@@ -34,6 +49,8 @@ export interface RerunRequest {
34
49
  autoHeal?: boolean;
35
50
  /** BE only: rerun only the named test without expanding the producer/teardown closure. */
36
51
  skipDependencies?: boolean;
52
+ /** See `TriggerRunBody.environment` — the named environment to replay against. */
53
+ environment?: string;
37
54
  }
38
55
  /** One closure member returned in `RerunResponse.closure.members[]`. */
39
56
  export interface RerunClosureMember {
@@ -103,6 +120,8 @@ export interface BatchRerunRequest {
103
120
  testIds: string[];
104
121
  autoHeal?: boolean;
105
122
  skipDependencies?: boolean;
123
+ /** See `TriggerRunBody.environment` — applied to every test in the batch. */
124
+ environment?: string;
106
125
  }
107
126
  /** One accepted run in the batch rerun response. */
108
127
  export interface BatchRerunAccepted {
@@ -166,6 +185,11 @@ export interface TriggerRunResponse {
166
185
  codeVersion: string;
167
186
  /** Resolved target URL (project default when --target-url absent). */
168
187
  targetUrl: string;
188
+ /**
189
+ * The environment this run resolved to. Absent on an older backend; `null`
190
+ * when the server resolved no environment row.
191
+ */
192
+ environment?: RunEnvironmentRef | null;
169
193
  /**
170
194
  * Portal deep link for the run's test, built by the server for the store
171
195
  * that dispatched it. Present-or-absent (never null): an older backend, a
@@ -244,6 +268,11 @@ export interface RunResponse {
244
268
  * (`RunEnvelope.targetUrl` is `[string, 'null']`).
245
269
  */
246
270
  targetUrl: string | null;
271
+ /**
272
+ * The environment this run resolved to. Absent on an older backend (or a
273
+ * V2-served run); `null` when the row names no environment.
274
+ */
275
+ environment?: RunEnvironmentRef | null;
247
276
  createdFrom: string | null;
248
277
  failedStepIndex: number | null;
249
278
  failureKind: string | null;
@@ -288,6 +317,12 @@ export interface RunResponse {
288
317
  */
289
318
  steps?: RunStepDto[] | null;
290
319
  }
320
+ /** Credit outcome returned when cancellation applies V3 frontend billing rules. */
321
+ export interface CancelRunRefund {
322
+ status: 'refunded' | 'not_charged' | 'failed';
323
+ /** Original charged amount returned to the workspace. Present when refunded. */
324
+ amount?: number;
325
+ }
291
326
  /**
292
327
  * Response from `POST /api/cli/v1/runs/{runId}/cancel`.
293
328
  * Same shape as `GET /runs/{runId}` (`status: "cancelled"`, verdict
@@ -296,6 +331,11 @@ export interface RunResponse {
296
331
  */
297
332
  export interface CancelRunResponse extends RunResponse {
298
333
  alreadyCancelled: boolean;
334
+ /**
335
+ * Present only when the server evaluated a V3 frontend run refund. Older
336
+ * backends, V2 runs, and backend-test runs omit it.
337
+ */
338
+ refund?: CancelRunRefund;
299
339
  }
300
340
  /** Terminal states from the RunStatus union. */
301
341
  export declare const TERMINAL_RUN_STATUSES: ReadonlySet<RunStatus>;
@@ -340,11 +380,15 @@ export interface RunHistoryItem {
340
380
  targetUrl?: string | null;
341
381
  /**
342
382
  * G1b — provenance of `targetUrl`.
343
- * - `'run'`: stamped at run-trigger time (authoritative).
383
+ * - `'run'`: stamped at run-trigger time (authoritative; V2).
344
384
  * - `'unresolved'`: backend could not resolve a URL for this run.
345
- * - `null` / absent: pre-G1b backend; treat as unknown.
385
+ * - `null`: a V3 run — the environment in `environment` IS the target and
386
+ * `targetUrl` is its address, so there is no separate provenance.
387
+ * - absent: pre-G1b backend; treat as unknown.
346
388
  */
347
389
  targetUrlSource?: 'run' | 'unresolved' | null;
390
+ /** The environment this run resolved to. Absent on older backends. */
391
+ environment?: RunEnvironmentRef | null;
348
392
  }
349
393
  /**
350
394
  * Pre-cutover metadata block present when the test has no CLI-tracked
@@ -385,6 +429,8 @@ export interface ListRunsQuery {
385
429
  source?: RunSource;
386
430
  /** ISO timestamp (after client-side duration parsing). */
387
431
  since?: string;
432
+ /** DEV-1306: only runs whose credentials came from this environment (by name). */
433
+ environment?: string;
388
434
  }
389
435
  /**
390
436
  * Body sent to `POST /api/cli/v1/tests/batch/run`.
@@ -395,6 +441,8 @@ export interface BatchRunFreshRequest {
395
441
  projectId: string;
396
442
  testIds?: string[];
397
443
  source: 'cli';
444
+ /** See `TriggerRunBody.environment` — applied to every test in the batch. */
445
+ environment?: string;
398
446
  }
399
447
  /** One accepted run in the batch fresh-run response. */
400
448
  export interface BatchRunFreshAccepted {
@@ -24,7 +24,7 @@
24
24
  * - Reject IPv6 link-local (`fe80::/10`), unique-local (`fc00::/7`), and
25
25
  * deprecated site-local (`fec0::/10`)
26
26
  */
27
- type TargetUrlHintContext = 'runtime' | 'bootstrap';
27
+ type TargetUrlHintContext = 'runtime' | 'bootstrap' | 'local-project-create';
28
28
  export interface TargetUrlCaller {
29
29
  /** CLI flag name without the leading `--`, used in the error envelope. */
30
30
  field: string;