@testsprite/testsprite-cli 0.16.0 → 0.18.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 (206) hide show
  1. package/README.md +52 -147
  2. package/dist/commands/agent.d.ts +12 -4
  3. package/dist/commands/agent.js +48 -63
  4. package/dist/commands/auth.d.ts +6 -10
  5. package/dist/commands/auth.js +40 -56
  6. package/dist/commands/ci.d.ts +23 -100
  7. package/dist/commands/ci.js +293 -487
  8. package/dist/commands/conversation.d.ts +27 -0
  9. package/dist/commands/conversation.js +741 -0
  10. package/dist/commands/doctor.d.ts +5 -1
  11. package/dist/commands/doctor.js +129 -34
  12. package/dist/commands/init.d.ts +4 -45
  13. package/dist/commands/init.js +108 -66
  14. package/dist/commands/project-env.d.ts +62 -2
  15. package/dist/commands/project-env.js +434 -43
  16. package/dist/commands/project-sign-in.d.ts +0 -48
  17. package/dist/commands/project-sign-in.js +1 -229
  18. package/dist/commands/project.d.ts +19 -186
  19. package/dist/commands/project.js +108 -926
  20. package/dist/commands/result.d.ts +10 -0
  21. package/dist/commands/result.js +216 -0
  22. package/dist/commands/schedule.d.ts +0 -29
  23. package/dist/commands/schedule.js +28 -87
  24. package/dist/commands/test.d.ts +301 -1838
  25. package/dist/commands/test.js +1880 -13917
  26. package/dist/commands/testlist.d.ts +130 -5
  27. package/dist/commands/testlist.js +300 -342
  28. package/dist/commands/tunnel.d.ts +3 -3
  29. package/dist/commands/tunnel.js +23 -20
  30. package/dist/commands/usage.d.ts +12 -45
  31. package/dist/commands/usage.js +50 -131
  32. package/dist/index.js +191 -110
  33. package/dist/lib/agent-detect.js +9 -5
  34. package/dist/lib/agent-targets.d.ts +21 -2
  35. package/dist/lib/agent-targets.js +88 -11
  36. package/dist/lib/args.d.ts +13 -0
  37. package/dist/lib/args.js +49 -0
  38. package/dist/lib/basic-auth.d.ts +3 -0
  39. package/dist/lib/basic-auth.js +15 -0
  40. package/dist/lib/billing-refusal.js +4 -3
  41. package/dist/lib/ci-linkage.d.ts +4 -82
  42. package/dist/lib/ci-linkage.js +4 -157
  43. package/dist/lib/ci-run.js +1 -1
  44. package/dist/lib/client-factory.d.ts +12 -4
  45. package/dist/lib/client-factory.js +41 -30
  46. package/dist/lib/commit-signal.d.ts +65 -0
  47. package/dist/lib/commit-signal.js +305 -0
  48. package/dist/lib/concurrency-limiter.d.ts +6 -0
  49. package/dist/lib/concurrency-limiter.js +29 -0
  50. package/dist/lib/config.js +10 -5
  51. package/dist/lib/conflict-reason.d.ts +9 -3
  52. package/dist/lib/conflict-reason.js +6 -3
  53. package/dist/lib/conversation/answers.d.ts +9 -0
  54. package/dist/lib/conversation/answers.js +49 -0
  55. package/dist/lib/conversation/api.d.ts +75 -0
  56. package/dist/lib/conversation/api.js +151 -0
  57. package/dist/lib/conversation/change.d.ts +31 -0
  58. package/dist/lib/conversation/change.js +124 -0
  59. package/dist/lib/conversation/context.d.ts +29 -0
  60. package/dist/lib/conversation/context.js +82 -0
  61. package/dist/lib/conversation/environment.d.ts +16 -0
  62. package/dist/lib/conversation/environment.js +21 -0
  63. package/dist/lib/conversation/follow.d.ts +24 -0
  64. package/dist/lib/conversation/follow.js +42 -0
  65. package/dist/lib/conversation/render.d.ts +33 -0
  66. package/dist/lib/conversation/render.js +318 -0
  67. package/dist/lib/conversation/title.d.ts +2 -0
  68. package/dist/lib/conversation/title.js +18 -0
  69. package/dist/lib/conversation/types.d.ts +158 -0
  70. package/dist/lib/conversation/types.js +6 -0
  71. package/dist/lib/credentials.js +67 -11
  72. package/dist/lib/cron.d.ts +1 -1
  73. package/dist/lib/cron.js +2 -2
  74. package/dist/lib/dispatch-stop.d.ts +20 -0
  75. package/dist/lib/dispatch-stop.js +30 -0
  76. package/dist/lib/download.d.ts +100 -0
  77. package/dist/lib/download.js +408 -0
  78. package/dist/lib/dry-run/fetch.d.ts +10 -0
  79. package/dist/lib/dry-run/fetch.js +20 -0
  80. package/dist/lib/dry-run/samples.d.ts +6 -34
  81. package/dist/lib/dry-run/samples.js +375 -747
  82. package/dist/lib/environment-tunnel.d.ts +19 -30
  83. package/dist/lib/environment-tunnel.js +168 -202
  84. package/dist/lib/errors.d.ts +20 -4
  85. package/dist/lib/errors.js +36 -16
  86. package/dist/lib/facade.d.ts +7 -29
  87. package/dist/lib/facade.js +7 -36
  88. package/dist/lib/failing-fe-resolver.d.ts +13 -58
  89. package/dist/lib/failing-fe-resolver.js +47 -132
  90. package/dist/lib/first-suite-hint.d.ts +20 -30
  91. package/dist/lib/first-suite-hint.js +57 -72
  92. package/dist/lib/gh-output.d.ts +76 -21
  93. package/dist/lib/gh-output.js +171 -90
  94. package/dist/lib/git-utils.d.ts +56 -0
  95. package/dist/lib/git-utils.js +212 -0
  96. package/dist/lib/github-context.d.ts +2 -0
  97. package/dist/lib/github-context.js +40 -8
  98. package/dist/lib/history-retention.d.ts +6 -2
  99. package/dist/lib/history-retention.js +10 -7
  100. package/dist/lib/http.d.ts +58 -134
  101. package/dist/lib/http.js +354 -291
  102. package/dist/lib/interrupt.d.ts +14 -8
  103. package/dist/lib/interrupt.js +28 -10
  104. package/dist/lib/junit-report.d.ts +57 -4
  105. package/dist/lib/junit-report.js +202 -32
  106. package/dist/lib/local-target.d.ts +8 -7
  107. package/dist/lib/local-target.js +14 -13
  108. package/dist/lib/output.d.ts +2 -41
  109. package/dist/lib/output.js +13 -51
  110. package/dist/lib/pagination.d.ts +2 -5
  111. package/dist/lib/pagination.js +2 -5
  112. package/dist/lib/presigned-url.d.ts +22 -0
  113. package/dist/lib/presigned-url.js +90 -0
  114. package/dist/lib/prompt.js +36 -2
  115. package/dist/lib/proxy.js +2 -1
  116. package/dist/lib/redact.d.ts +2 -2
  117. package/dist/lib/redact.js +3 -4
  118. package/dist/lib/removed-commands.d.ts +18 -0
  119. package/dist/lib/removed-commands.js +170 -0
  120. package/dist/lib/render-error.d.ts +31 -6
  121. package/dist/lib/render-error.js +88 -25
  122. package/dist/lib/response-schemas.d.ts +38 -30
  123. package/dist/lib/response-schemas.js +207 -207
  124. package/dist/lib/result/api.d.ts +24 -0
  125. package/dist/lib/result/api.js +28 -0
  126. package/dist/lib/result/evidence.d.ts +73 -0
  127. package/dist/lib/result/evidence.js +422 -0
  128. package/dist/lib/result/render.d.ts +20 -0
  129. package/dist/lib/result/render.js +194 -0
  130. package/dist/lib/result/types.d.ts +122 -0
  131. package/dist/lib/result/types.js +19 -0
  132. package/dist/lib/run-output.d.ts +275 -0
  133. package/dist/lib/run-output.js +227 -0
  134. package/dist/lib/run-render.d.ts +101 -0
  135. package/dist/lib/run-render.js +183 -0
  136. package/dist/lib/run-wait.d.ts +192 -0
  137. package/dist/lib/run-wait.js +452 -0
  138. package/dist/lib/runs.types.d.ts +118 -367
  139. package/dist/lib/runs.types.js +0 -14
  140. package/dist/lib/secret-file.d.ts +1 -1
  141. package/dist/lib/secret-file.js +11 -2
  142. package/dist/lib/skill-nudge.d.ts +7 -27
  143. package/dist/lib/skill-nudge.js +9 -37
  144. package/dist/lib/target-path.d.ts +15 -0
  145. package/dist/lib/target-path.js +35 -0
  146. package/dist/lib/target-url-advisory.d.ts +19 -0
  147. package/dist/lib/target-url-advisory.js +31 -0
  148. package/dist/lib/target-url-preflight.d.ts +9 -0
  149. package/dist/lib/target-url-preflight.js +214 -106
  150. package/dist/lib/target-url.d.ts +8 -8
  151. package/dist/lib/target-url.js +14 -24
  152. package/dist/lib/telemetry.d.ts +35 -15
  153. package/dist/lib/telemetry.js +38 -9
  154. package/dist/lib/terminal-text.d.ts +41 -0
  155. package/dist/lib/terminal-text.js +127 -0
  156. package/dist/lib/testlist.types.d.ts +16 -8
  157. package/dist/lib/testlist.types.js +1 -1
  158. package/dist/lib/text-equality.d.ts +2 -0
  159. package/dist/lib/text-equality.js +5 -0
  160. package/dist/lib/text-file.d.ts +16 -0
  161. package/dist/lib/text-file.js +41 -0
  162. package/dist/lib/text-table.d.ts +46 -0
  163. package/dist/lib/text-table.js +72 -4
  164. package/dist/lib/ticker.d.ts +9 -2
  165. package/dist/lib/ticker.js +16 -3
  166. package/dist/lib/transport-failure.d.ts +22 -0
  167. package/dist/lib/transport-failure.js +126 -0
  168. package/dist/lib/tunnel-session.d.ts +8 -2
  169. package/dist/lib/tunnel-session.js +24 -11
  170. package/dist/lib/update-check.js +3 -2
  171. package/dist/lib/url-template.d.ts +43 -0
  172. package/dist/lib/url-template.js +151 -0
  173. package/dist/lib/validate.d.ts +0 -64
  174. package/dist/lib/validate.js +2 -131
  175. package/dist/lib/version-notice.js +4 -3
  176. package/dist/lib/wait-exit.d.ts +37 -2
  177. package/dist/lib/wait-exit.js +88 -30
  178. package/dist/lib/workspace-status.js +10 -2
  179. package/dist/version.d.ts +1 -1
  180. package/dist/version.js +1 -1
  181. package/package.json +2 -3
  182. package/skills/testsprite-ci.skill.md +52 -23
  183. package/skills/testsprite-onboard.skill.md +70 -153
  184. package/skills/testsprite-verify.codex.md +54 -58
  185. package/skills/testsprite-verify.skill.md +189 -358
  186. package/dist/lib/browser.d.ts +0 -6
  187. package/dist/lib/browser.js +0 -54
  188. package/dist/lib/bundle.d.ts +0 -234
  189. package/dist/lib/bundle.js +0 -781
  190. package/dist/lib/deprecate.d.ts +0 -32
  191. package/dist/lib/deprecate.js +0 -39
  192. package/dist/lib/flaky.d.ts +0 -91
  193. package/dist/lib/flaky.js +0 -71
  194. package/dist/lib/plan-poll.d.ts +0 -171
  195. package/dist/lib/plan-poll.js +0 -441
  196. package/dist/lib/plans.types.d.ts +0 -130
  197. package/dist/lib/plans.types.js +0 -31
  198. package/dist/lib/poll.d.ts +0 -100
  199. package/dist/lib/poll.js +0 -290
  200. package/dist/lib/rate-throttle.d.ts +0 -49
  201. package/dist/lib/rate-throttle.js +0 -75
  202. package/dist/lib/run-progress.d.ts +0 -41
  203. package/dist/lib/run-progress.js +0 -56
  204. package/dist/lib/v3-advisory.d.ts +0 -55
  205. package/dist/lib/v3-advisory.js +0 -74
  206. package/schemas/plan.schema.json +0 -61
package/dist/lib/http.js CHANGED
@@ -1,15 +1,17 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import * as v from 'valibot';
3
- import { ApiError, InterruptError, RequestTimeoutError, TransportError } from './errors.js';
3
+ import { ApiError, InterruptError, isErrorCode, RequestTimeoutError, TransportError, localValidationError, } from './errors.js';
4
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_LIST_RESPONSE_SCHEMA, TUNNEL_MINT_RESPONSE_SCHEMA, TUNNEL_STATUS_RESPONSE_SCHEMA, EXECUTION_REPORT_RESPONSE_SCHEMA, } from './response-schemas.js';
5
+ import { classifyFatalTransportFailure } from './transport-failure.js';
6
+ import { BATCH_RUN_FRESH_RESPONSE_SCHEMA, PROJECT_RUN_RESPONSE_SCHEMA, CANCEL_RUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TESTLIST_RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, TUNNEL_LIST_RESPONSE_SCHEMA, TUNNEL_MINT_RESPONSE_SCHEMA, TUNNEL_STATUS_RESPONSE_SCHEMA, EXECUTION_REPORT_RESPONSE_SCHEMA, } from './response-schemas.js';
7
+ import { sleepUnlessInterrupted } from './poll-support.js';
6
8
  /**
7
9
  * Default per-request timeout (120s). Comfortably covers every metadata/read
8
10
  * request and every <=25s long-poll request (`?waitSeconds` is capped at 25
9
11
  * by the polling layer), while still failing fast on a dead backend.
10
12
  *
11
13
  * The 15-minute test-execution ceiling is enforced separately by the `--timeout`
12
- * / polling path (`poll.ts`) which supplies its own `AbortSignal` per iteration.
14
+ * / whole-run waiting path (`run-wait.ts`) which supplies its own `AbortSignal` per iteration.
13
15
  * That path is unaffected — each 25s long-poll request still falls well within
14
16
  * this 120s per-request guard.
15
17
  *
@@ -36,6 +38,8 @@ const MAX_ATTEMPTS_UNAVAILABLE = 4;
36
38
  const MAX_ATTEMPTS_RATE_LIMITED = 3;
37
39
  const MAX_ATTEMPTS_CONFLICT = 2;
38
40
  const MAX_ATTEMPTS_INTERNAL = 2;
41
+ const MAX_REDIRECTS = 20;
42
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
39
43
  // Cap server-directed RATE_LIMITED waits so a hostile or misconfigured
40
44
  // `Retry-After` (e.g. 86400) can't hang the CLI inside the retry sleep.
41
45
  const MAX_RATE_LIMITED_DELAY_MS = 60_000;
@@ -62,11 +66,10 @@ const CONFLICT_DELAY_MS = 1000;
62
66
  const INTERNAL_DELAY_MS = 500;
63
67
  // Upper bound on the size of a successful JSON response body the client will
64
68
  // buffer into memory. `response.json()` reads the ENTIRE body before parsing,
65
- // with no limit, so a large `test result --history` page or a run with a long
66
- // `steps[]` array (getRun `includeSteps`) would grow the heap in proportion to
67
- // the payload. 64 MiB sits far above any legitimate metadata/history/steps
68
- // response yet still bounds a pathological — or hostile — one. Override per
69
- // client via `HttpClientOptions.maxResponseBytes`.
69
+ // with no limit, so a large list page or a result with a long `steps[]` array
70
+ // would grow the heap in proportion to the payload. 64 MiB sits far above any
71
+ // legitimate metadata/history/steps response yet still bounds a pathological —
72
+ // or hostile — one. Override per client via `HttpClientOptions.maxResponseBytes`.
70
73
  const MAX_RESPONSE_BYTES_DEFAULT = 64 * 1024 * 1024;
71
74
  // Cap on how many valibot issues a shape-mismatch INTERNAL envelope carries in
72
75
  // `details.issues` (path + message each). Keeps the envelope readable and
@@ -144,25 +147,26 @@ export class HttpClient {
144
147
  return this.requestWithMeta('DELETE', path, options).then(r => r.body);
145
148
  }
146
149
  /**
147
- * Like `get` / `post` / etc. but returns the full `RequestResult` including
150
+ * Like `post` / `delete` but returns the full `RequestResult` including
148
151
  * `requestId` and `status`, so callers can surface the requestId in
149
- * happy-path output.
152
+ * happy-path output. The run triggers and the tunnel mint and delete use them.
150
153
  */
151
- async getWithMeta(path, options = {}) {
152
- return this.requestWithMeta('GET', path, options);
153
- }
154
154
  async postWithMeta(path, options = {}) {
155
155
  return this.requestWithMeta('POST', path, options);
156
156
  }
157
- async putWithMeta(path, options = {}) {
158
- return this.requestWithMeta('PUT', path, options);
159
- }
160
- async patchWithMeta(path, options = {}) {
161
- return this.requestWithMeta('PATCH', path, options);
162
- }
163
157
  async deleteWithMeta(path, options = {}) {
164
158
  return this.requestWithMeta('DELETE', path, options);
165
159
  }
160
+ /** Launch exactly one execution for this project, with server-owned pacing. */
161
+ async triggerProjectRun(projectId, body, options) {
162
+ return this.postWithMeta(`/projects/${encodeURIComponent(projectId)}/runs`, {
163
+ body,
164
+ headers: { 'idempotency-key': options.idempotencyKey },
165
+ signal: options.signal,
166
+ schema: PROJECT_RUN_RESPONSE_SCHEMA,
167
+ retryOnConflict: false,
168
+ });
169
+ }
166
170
  /**
167
171
  * POST /api/cli/v1/tests/{testId}/runs
168
172
  * Trigger a run and return the queued-run envelope.
@@ -184,14 +188,6 @@ export class HttpClient {
184
188
  /**
185
189
  * Like `triggerRun` but returns the full `RequestResult` so the caller
186
190
  * can surface the `requestId` in happy-path CLI output.
187
- *
188
- * `retryOnRateLimit` defaults to `true` so single `test run` and
189
- * `test create --run` retain the standard HTTP-layer 429 retry budget.
190
- *
191
- * Pass `retryOnRateLimit: false` ONLY at the batch fan-out call site
192
- * (`runBatchRun` / `triggerOne`) where the outer loop is the single owner
193
- * of rate-limit handling — preventing the HTTP layer from adding up to 3
194
- * extra retries per outer attempt, which would multiply POSTs per spec (e.g. 50×3 = 150/min).
195
191
  */
196
192
  async triggerRunWithMeta(testId, body, options) {
197
193
  return this.postWithMeta(`/tests/${encodeURIComponent(testId)}/runs`, {
@@ -200,45 +196,8 @@ export class HttpClient {
200
196
  signal: options.signal,
201
197
  schema: TRIGGER_RUN_RESPONSE_SCHEMA,
202
198
  retryOnConflict: false,
203
- // Default true: single `test run` / `test create --run` retain 429 retry.
204
- // Batch call site passes false to keep outer-loop as sole rate-limit owner.
205
- retryOnRateLimit: options.retryOnRateLimit ?? true,
206
199
  });
207
200
  }
208
- /**
209
- * POST /api/cli/v1/tests/{testId}/runs/rerun
210
- * Trigger a rerun (replay) for a single test. FE: verbatim script replay, billed at
211
- * 0.5 credits (same as a fresh run; legacy V2 accounts: free). BE: dependency-closure
212
- * re-run, billed at 0.2 credits. Returns `runId` + optional `closure` (BE).
213
- *
214
- * `retryOnConflict: false` — 409 on rerun means the test is already in-flight,
215
- * a persistent condition. Retrying would race against the running test.
216
- */
217
- async triggerRerun(testId, body, options) {
218
- return this.postWithMeta(`/tests/${encodeURIComponent(testId)}/runs/rerun`, {
219
- body,
220
- headers: { 'idempotency-key': options.idempotencyKey },
221
- signal: options.signal,
222
- schema: RERUN_RESPONSE_SCHEMA,
223
- retryOnConflict: false,
224
- }).then(r => withoutDeprecationAdvisories(r.body));
225
- }
226
- /**
227
- * POST /api/cli/v1/tests/batch/rerun
228
- * Trigger a batch rerun across multiple tests (mixed FE/BE allowed).
229
- * BE closure is deduped server-side per project.
230
- *
231
- * `retryOnConflict: false` — 409 on batch rerun is persistent ("in flight").
232
- */
233
- async triggerBatchRerun(body, options) {
234
- return this.postWithMeta('/tests/batch/rerun', {
235
- body,
236
- headers: { 'idempotency-key': options.idempotencyKey },
237
- signal: options.signal,
238
- schema: BATCH_RERUN_RESPONSE_SCHEMA,
239
- retryOnConflict: false,
240
- }).then(r => withoutDeprecationAdvisories(r.body));
241
- }
242
201
  /**
243
202
  * POST /api/cli/v1/tests/batch/run
244
203
  * Trigger a fresh wave-ordered batch run across all (or a subset of) BE tests
@@ -275,61 +234,24 @@ export class HttpClient {
275
234
  }).then(r => r.body);
276
235
  }
277
236
  /**
278
- * GET /api/cli/v1/tests/{testId}/runs
279
- * List a test's prior run history, newest-first.
280
- *
281
- * Limit-before-filter caveat: a `source`-filtered page may return fewer
282
- * than `pageSize` rows while still yielding a non-null `nextCursor`.
283
- * That means "none in THIS window", not end-of-history.
284
- */
285
- async listTestRuns(testId, query, options = {}) {
286
- const q = {};
287
- if (query.cursor !== undefined)
288
- q.cursor = query.cursor;
289
- if (query.pageSize !== undefined)
290
- q.pageSize = query.pageSize;
291
- if (query.source !== undefined)
292
- q.source = query.source;
293
- if (query.since !== undefined)
294
- q.since = query.since;
295
- if (query.environment !== undefined)
296
- q.environment = query.environment;
297
- return this.get(`/tests/${encodeURIComponent(testId)}/runs`, {
298
- query: q,
299
- signal: options.signal,
300
- retry: options.retry,
301
- schema: LIST_RUNS_RESPONSE_SCHEMA,
302
- });
303
- }
304
- /**
305
- * GET /api/cli/v1/runs/{runId}
306
- * Fetch the current state of a run. When `waitSeconds` is provided
307
- * (1–25) the server performs a bounded long-poll and returns when the
308
- * run is terminal or when `waitSeconds` elapses, whichever comes
309
- * first. On `400 VALIDATION_ERROR` (server doesn't support
310
- * `waitSeconds`) the caller should retry without the param and switch
311
- * to client-side backoff — see `src/lib/poll.ts`.
312
- *
313
- * When `includeSteps` is `true`, the server appends the full ordered
314
- * `steps[]` array (M3.4 piece-4). Default (absent/false) is byte-
315
- * identical to the M3.3 summary shape — the polling path is unaffected.
237
+ * GET /api/cli/v1/runs/{resultId}
238
+ * Fetch an individual result card, including steps and artifacts. Optional
239
+ * waitSeconds is retained for callers of this existing result endpoint.
240
+ * Whole-execution waiting uses GET /results?run= through run-wait.ts.
316
241
  */
317
- async getRun(runId, options) {
242
+ async getRun(resultId, options) {
318
243
  const query = {};
319
244
  if (options?.waitSeconds !== undefined) {
320
245
  query.waitSeconds = options.waitSeconds;
321
246
  }
322
- if (options?.includeSteps === true) {
323
- query.includeSteps = true;
324
- }
325
- return this.get(`/runs/${encodeURIComponent(runId)}`, {
247
+ return this.get(`/runs/${encodeURIComponent(resultId)}`, {
326
248
  query: Object.keys(query).length > 0 ? query : undefined,
327
249
  signal: options?.signal,
328
250
  schema: RUN_RESPONSE_SCHEMA,
329
251
  });
330
252
  }
331
253
  /**
332
- * POST /api/cli/v1/tunnel — mint a tunnel client for `test run --local`.
254
+ * POST /api/cli/v1/tunnel — mint a tunnel client for a run on a local environment.
333
255
  *
334
256
  * The ONLY response on this surface that carries a secret. Deliberately NOT
335
257
  * sent with an `Idempotency-Key`: the interceptor persists the response body
@@ -381,8 +303,8 @@ export class HttpClient {
381
303
  * execution. `ready: false` asks the caller to poll again; the server keeps
382
304
  * building the report meanwhile.
383
305
  */
384
- async getExecutionReport(executionId, options = {}) {
385
- return this.get(`/tests/executions/${encodeURIComponent(executionId)}/report`, { signal: options.signal, retry: options.retry, schema: EXECUTION_REPORT_RESPONSE_SCHEMA });
306
+ async getExecutionReport(runId, options = {}) {
307
+ return this.get(`/tests/executions/${encodeURIComponent(runId)}/report`, { signal: options.signal, retry: options.retry, schema: EXECUTION_REPORT_RESPONSE_SCHEMA });
386
308
  }
387
309
  /**
388
310
  * DELETE /api/cli/v1/tunnel/{clientId} — destroy a binding. 204, idempotent.
@@ -396,74 +318,22 @@ export class HttpClient {
396
318
  signal: options.signal,
397
319
  allowNoContent: true,
398
320
  retryOnConflict: false,
321
+ replaySafe: true,
399
322
  });
400
323
  }
401
324
  /**
402
325
  * POST /api/cli/v1/runs/{runId}/cancel
403
- * User-initiated cancel of a queued/running run. No
404
- * body, no `Idempotency-Key` — the endpoint is naturally idempotent:
405
- * re-cancel → 200 `alreadyCancelled: true`; already-terminal (passed/
406
- * failed/blocked) → 409 CONFLICT; unknown/cross-tenant runId → 404.
407
- *
408
- * `retryOnConflict: false` — same rationale as `triggerRun`: a 409 here is
409
- * a truthful terminal answer ("already finished"), not a transient
410
- * snapshot conflict to paper over with a retry.
326
+ * Cancel the entire execution without enumerating its results. Repeated and
327
+ * terminal cancellation returns HTTP 200 with alreadyCancelled/alreadyFinished;
328
+ * unknown and cross-tenant execution IDs return 404. Per-result refund outcomes
329
+ * are returned by the server. No request body or idempotency key is required.
411
330
  */
412
331
  async cancelRun(runId, options) {
413
332
  return this.post(`/runs/${encodeURIComponent(runId)}/cancel`, {
414
333
  signal: options?.signal,
415
334
  schema: CANCEL_RUN_RESPONSE_SCHEMA,
416
335
  retryOnConflict: false,
417
- });
418
- }
419
- /**
420
- * POST /api/cli/v1/projects/{projectId}/plans/generate
421
- * Start whichever generation stage the project is missing next. The body
422
- * is empty by contract — the server decides which rung fires. 202 both
423
- * for `accepted` (a stage started) and `nothing_to_start` (proposals are
424
- * already staged; the facade's no-restart guard refuses a duplicate
425
- * append because it would wipe the batch and re-bill 2 credits).
426
- *
427
- * `retryOnConflict: false` — a 409 here is `stage_in_flight`, a flow
428
- * signal the ladder answers by attaching and polling, never a transient
429
- * snapshot conflict to paper over with a retry.
430
- */
431
- async generatePlans(projectId, options) {
432
- return this.post(`/projects/${encodeURIComponent(projectId)}/plans/generate`, {
433
- body: {},
434
- headers: { 'idempotency-key': options.idempotencyKey },
435
- signal: options.signal,
436
- retryOnConflict: false,
437
- });
438
- }
439
- /**
440
- * GET /api/cli/v1/projects/{projectId}/plans
441
- * Pure read: the facade-synthesized generation status, the staged
442
- * proposal list (stable proposalIds — what `accept --only` consumes),
443
- * and a best-effort credits block. When `waitSeconds` (1–25) is
444
- * provided the server long-polls: one request per window, answered
445
- * early on any change.
446
- */
447
- async getPlans(projectId, options) {
448
- return this.get(`/projects/${encodeURIComponent(projectId)}/plans`, {
449
- query: options?.waitSeconds !== undefined ? { waitSeconds: options.waitSeconds } : undefined,
450
- signal: options?.signal,
451
- });
452
- }
453
- /**
454
- * POST /api/cli/v1/projects/{projectId}/plans/accept
455
- * Convert staged proposals into real test cases. `only` is ALWAYS an
456
- * explicit, non-empty id list — the caller enforces the two §3.3 safety
457
- * rules (full list when the user didn't subset; an empty selection is a
458
- * client-side validation error because `[]` is server-destructive:
459
- * it means "reject everything" and clears the staged batch).
460
- */
461
- async acceptPlans(projectId, only, options) {
462
- return this.post(`/projects/${encodeURIComponent(projectId)}/plans/accept`, {
463
- body: { only },
464
- headers: { 'idempotency-key': options.idempotencyKey },
465
- signal: options.signal,
466
- retryOnConflict: false,
336
+ replaySafe: true,
467
337
  });
468
338
  }
469
339
  /**
@@ -518,8 +388,7 @@ export class HttpClient {
518
388
  let response;
519
389
  // Compose the per-request timeout signal with any caller-supplied signal.
520
390
  // The fetch aborts on whichever fires first. This ensures every one-shot
521
- // request (test create/update/delete/list/get, auth whoami, code put/get,
522
- // plan put) has a client-side deadline even when the caller supplies no
391
+ // request (test list/get, auth status, …) has a client-side deadline even when the caller supplies no
523
392
  // signal. The polling path supplies its own deadline-aware signal per
524
393
  // iteration — this timeout (120s default) is safely larger than any single
525
394
  // long-poll window (<=25s via ?waitSeconds), so it never bites polling.
@@ -540,18 +409,18 @@ export class HttpClient {
540
409
  // `AbortSignal.any` here was measured to register ~330K dependent-signal
541
410
  // trackings against that one long-lived signal over a single request-heavy
542
411
  // test file — the same `FinalizationRegistry` backlog mechanism already
543
- // fixed once in `poll.ts`, just recreated per-request instead of
412
+ // fixed in the polling signal lifecycle, just recreated per-request instead of
544
413
  // per-poll-iteration. `cleanupAbortComposition` MUST be called once the
545
414
  // request settles (below, alongside `requestTimeout.clear()`).
546
415
  const { signal: effectiveSignal, cleanup: cleanupAbortComposition } = composeAbortSignals(composedSignals);
547
416
  try {
548
417
  try {
549
- response = await this.fetchImpl(url, {
418
+ response = await this.fetchSameOrigin(url, {
550
419
  method,
551
420
  headers: this.buildHeaders(requestId, options),
552
421
  body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
553
422
  signal: effectiveSignal,
554
- });
423
+ }, requestId);
555
424
  }
556
425
  catch (err) {
557
426
  // Distinguish a client-side request timeout from a caller-supplied abort.
@@ -577,33 +446,42 @@ export class HttpClient {
577
446
  // rather than re-wrapping it as a TransportError.
578
447
  if (err instanceof RequestTimeoutError)
579
448
  throw err;
580
- const message = err instanceof Error ? err.message : String(err);
581
- this.debug({
582
- kind: 'error',
583
- method,
584
- url,
585
- attempt,
586
- requestId,
587
- errorCode: 'TRANSPORT',
588
- durationMs: Date.now() - startedAt,
589
- });
590
- const decision = allowTransportRetry
591
- ? transportRetryDecision(attempt, this.random)
592
- : { retry: false, delayMs: 0 };
593
- if (!decision.retry)
594
- throw new TransportError(message, requestId);
595
- this.transition(`Network error on ${shortPath(path)} — retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
596
- this.debug({
597
- kind: 'retry',
449
+ // Retrying a refused redirect could repeat an already accepted mutation.
450
+ if (err instanceof RedirectError)
451
+ throw err;
452
+ // An untrusted TLS certificate or a proxy 407 fails the same way on
453
+ // every attempt. Fail now, before the retry decision, so no request
454
+ // (read, keyed write or replay-safe call) spends its backoff budget on
455
+ // it, and name the fix instead of "temporarily unavailable".
456
+ const fatal = classifyFatalTransportFailure(err, url);
457
+ if (fatal !== undefined) {
458
+ this.debug({
459
+ kind: 'error',
460
+ method,
461
+ url,
462
+ attempt,
463
+ requestId,
464
+ errorCode: 'TRANSPORT',
465
+ durationMs: Date.now() - startedAt,
466
+ });
467
+ throw new TransportError(fatal.message, requestId, {
468
+ nextAction: fatal.nextAction,
469
+ details: { cause: fatal.cause },
470
+ });
471
+ }
472
+ const delayMs = this.transportRetryDelayOrThrow({
473
+ message: err instanceof Error ? err.message : String(err),
474
+ transition: 'Network error',
598
475
  method,
599
476
  url,
477
+ path,
600
478
  attempt,
601
479
  requestId,
602
- errorCode: 'TRANSPORT',
603
- delayMs: decision.delayMs,
480
+ startedAt,
481
+ allowTransportRetry,
604
482
  });
605
483
  requestTimeout.clear();
606
- await this.sleepBeforeRetry(decision.delayMs);
484
+ await this.sleepBeforeRetry(delayMs, options.signal);
607
485
  continue;
608
486
  }
609
487
  const durationMs = Date.now() - startedAt;
@@ -622,38 +500,61 @@ export class HttpClient {
622
500
  durationMs,
623
501
  });
624
502
  let raw;
625
- try {
626
- if (response.status === 204 && options.allowNoContent === true) {
627
- // Only explicitly bodyless endpoints may bypass the historical
628
- // JSON-envelope contract. Every other 204 still falls through
629
- // to JSON.parse('') and becomes a typed malformed-response error.
630
- raw = undefined;
503
+ // Only explicitly bodyless endpoints may bypass the historical
504
+ // JSON-envelope contract. Every other 204 still falls through to
505
+ // JSON.parse('') and becomes a typed malformed-response error.
506
+ if (response.status !== 204 || options.allowNoContent !== true) {
507
+ // Read and parse are separate steps with separate failure classes.
508
+ // Reading can fail after the headers arrived — the connection is
509
+ // reset or closed mid-body (`TypeError: terminated` from undici) —
510
+ // which is a network failure, retried under the same transport
511
+ // rules as a failed fetch. Only a body that was read in full and
512
+ // still is not JSON is a malformed response.
513
+ let text;
514
+ try {
515
+ text = await readBoundedText(response, this.maxResponseBytes, requestId);
631
516
  }
632
- else {
633
- // Bounded read, then parse — assigning to `raw` rather than returning
634
- // here keeps the schema validation below on the success path.
635
- const text = await readBoundedText(response, this.maxResponseBytes, requestId);
517
+ catch (err) {
518
+ // Interrupt passthrough (see the fetch catch above).
519
+ if (err instanceof InterruptError)
520
+ throw err;
521
+ // A bounded-read rejection (PAYLOAD_TOO_LARGE) — or any typed
522
+ // ApiError — is a real, actionable outcome; surface it unchanged.
523
+ if (err instanceof ApiError)
524
+ throw err;
525
+ // A timeout/abort can fire mid-body-read (headers received, stream stalls).
526
+ this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
527
+ if (err instanceof RequestTimeoutError)
528
+ throw err;
529
+ const delayMs = this.transportRetryDelayOrThrow({
530
+ message: `connection closed while reading the response body: ${err instanceof Error ? err.message : String(err)}`,
531
+ transition: 'Connection dropped mid-response',
532
+ method,
533
+ url,
534
+ path,
535
+ attempt,
536
+ requestId,
537
+ startedAt,
538
+ allowTransportRetry,
539
+ });
540
+ requestTimeout.clear();
541
+ await this.sleepBeforeRetry(delayMs, options.signal);
542
+ continue;
543
+ }
544
+ try {
545
+ // Assigning to `raw` rather than returning here keeps the schema
546
+ // validation below on the success path.
636
547
  raw = JSON.parse(text);
637
548
  }
638
- }
639
- catch (err) {
640
- // Interrupt passthrough (see the fetch catch above).
641
- if (err instanceof InterruptError)
642
- throw err;
643
- // A bounded-read rejection (PAYLOAD_TOO_LARGE) — or any typed ApiError —
644
- // is a real, actionable outcome; surface it unchanged rather than
645
- // masking it as a malformed-body error below.
646
- if (err instanceof ApiError)
647
- throw err;
648
- // A timeout/abort can fire mid-body-read (headers received, stream stalls).
649
- this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
650
- // Otherwise the successful response body was not valid JSON — a
651
- // misconfigured endpoint, a proxy / captive-portal / login page that
652
- // returns HTML with a 200 status, or an empty body. Surface a typed
653
- // error carrying the requestId instead of letting the raw SyntaxError
654
- // escape to index.ts, where it would print a bare `{"error":"..."}`
655
- // and break the --output json envelope contract.
656
- throw malformedResponseError(response, requestId, err);
549
+ catch (err) {
550
+ // The successful response body was not valid JSON — a
551
+ // misconfigured endpoint, a proxy / captive-portal / login page
552
+ // that returns HTML with a 200 status, or an empty body. Surface a
553
+ // typed error carrying the requestId instead of letting the raw
554
+ // SyntaxError escape to index.ts, where it would print a bare
555
+ // `{"error":"..."}` and break the --output json envelope contract.
556
+ throw malformedResponseError(response, requestId, err);
557
+ }
657
558
  }
658
559
  if (options.schema !== undefined) {
659
560
  const parsed = v.safeParse(options.schema, raw);
@@ -680,24 +581,48 @@ export class HttpClient {
680
581
  }
681
582
  return { body: raw, requestId, status: response.status };
682
583
  }
683
- let rawBody;
584
+ let errorBody;
684
585
  try {
685
- rawBody = await safeReadJson(response);
586
+ errorBody = await readErrorResponseBody(response);
686
587
  }
687
588
  catch (err) {
688
589
  // Interrupt passthrough (see the fetch catch above).
689
590
  if (err instanceof InterruptError)
690
591
  throw err;
691
- // safeReadJson rethrows aborts/timeouts (it swallows only non-abort parse
692
- // errors), so a timeout fired mid-body-read on a non-OK response lands here.
592
+ // readErrorResponseBody rethrows aborts/timeouts (it swallows only
593
+ // non-abort read/parse errors), so a timeout fired mid-body-read on a
594
+ // non-OK response lands here.
693
595
  this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
694
596
  throw err;
695
597
  }
598
+ const rawBody = errorBody.json;
599
+ // The API answers every 4xx with a JSON body. A 4xx whose body is not
600
+ // JSON came from something in between (a proxy, firewall or captive
601
+ // portal page). Mapping its status would tell the user the key is bad
602
+ // (403), the credits ran out (402), the resource is gone (404) or the
603
+ // CLI is too old (426) for a request the API never saw. 408 and 429
604
+ // keep their retry handling below.
605
+ if (errorBody.notJson && isNonApiCandidateStatus(response.status)) {
606
+ this.debug({
607
+ kind: 'error',
608
+ method,
609
+ url,
610
+ attempt,
611
+ status: response.status,
612
+ requestId,
613
+ errorCode: 'TRANSPORT',
614
+ durationMs,
615
+ });
616
+ throw nonApiResponseError(response, requestId, url);
617
+ }
696
618
  // Edge proxies / load balancers return 408/502/504 without our error
697
619
  // envelope on transient outages. These are transport-level retries,
698
620
  // not facade errors — fold them in here so we get the bounded backoff
699
- // budget instead of a single INTERNAL bail.
700
- if (rawBody === null && isTransportEdgeStatus(response.status)) {
621
+ // budget instead of a single INTERNAL bail. A JSON edge body (e.g. an
622
+ // API Gateway `{"message":"Endpoint request timed out"}`) is still not
623
+ // our envelope, so it takes this path too and the keyless-write gate
624
+ // below applies.
625
+ if (isTransportEdgeStatus(response.status) && !hasCatalogErrorCode(rawBody)) {
701
626
  this.debug({
702
627
  kind: 'error',
703
628
  method,
@@ -725,12 +650,12 @@ export class HttpClient {
725
650
  delayMs: decision.delayMs,
726
651
  });
727
652
  requestTimeout.clear();
728
- await this.sleepBeforeRetry(decision.delayMs);
653
+ await this.sleepBeforeRetry(decision.delayMs, options.signal);
729
654
  continue;
730
655
  }
731
656
  const retryAfterSec = parseRetryAfter(response.headers.get('retry-after'));
732
657
  // Clamp server-directed Retry-After to [1s, 300s] and surface on the
733
- // thrown error so outer callers (e.g. runBatchRun outer retry loop)
658
+ // thrown error so outer callers (e.g. the `run wait` retry loop)
734
659
  // can honor it without re-reading the now-consumed HTTP response.
735
660
  const retryAfterMsForError = retryAfterSec !== undefined
736
661
  ? Math.min(Math.max(retryAfterSec, 1), 300) * 1000
@@ -754,7 +679,12 @@ export class HttpClient {
754
679
  // Retry-After says when a retry COULD first succeed if the caller
755
680
  // frees the resource, not that the condition clears on its own.
756
681
  const retryOnRateLimit = options.retryOnRateLimit !== false && !isStandingRateLimit(apiError);
757
- const decision = allowRetry
682
+ // A 5xx can land after the server committed the write, so a keyless
683
+ // write is not replayed on one (the same rule #256 applies to
684
+ // transport failures). 429 / 409 are refusals and still retry.
685
+ const serverFault = apiError.code === 'INTERNAL' || apiError.code === 'UNAVAILABLE';
686
+ const replaySafe = allowTransportRetry || options.replaySafe === true;
687
+ const decision = allowRetry && (replaySafe || !serverFault)
758
688
  ? apiRetryDecision(apiError.code, attempt, retryAfterSec, this.random, retryOnConflict, retryOnRateLimit)
759
689
  : { retry: false, delayMs: 0 };
760
690
  if (!decision.retry)
@@ -779,7 +709,7 @@ export class HttpClient {
779
709
  delayMs: decision.delayMs,
780
710
  });
781
711
  requestTimeout.clear();
782
- await this.sleepBeforeRetry(decision.delayMs);
712
+ await this.sleepBeforeRetry(decision.delayMs, options.signal);
783
713
  }
784
714
  finally {
785
715
  requestTimeout.clear();
@@ -791,6 +721,55 @@ export class HttpClient {
791
721
  }
792
722
  }
793
723
  }
724
+ /** Follow redirects explicitly so credentials never leave the original origin. */
725
+ async fetchSameOrigin(url, init, requestId) {
726
+ const origin = new URL(url).origin;
727
+ let currentUrl = url;
728
+ let currentInit = { ...init, redirect: 'manual' };
729
+ for (let redirects = 0;; redirects += 1) {
730
+ const response = await this.fetchImpl(currentUrl, currentInit);
731
+ const location = response.headers.get('location');
732
+ if (!REDIRECT_STATUSES.has(response.status) || location === null)
733
+ return response;
734
+ // Release every intermediate body, including rejected redirects, while
735
+ // keeping the caller's single timeout/signal across the entire chain.
736
+ await response.body?.cancel();
737
+ let target;
738
+ try {
739
+ target = new URL(location, currentUrl);
740
+ }
741
+ catch {
742
+ throw new RedirectError(`Invalid redirect target from ${origin}.`, requestId);
743
+ }
744
+ if (target.origin !== origin) {
745
+ throw new RedirectError(`Refused cross-origin redirect from ${origin} to ${target.origin}.`, requestId);
746
+ }
747
+ if (target.username || target.password) {
748
+ throw new RedirectError(`Refused redirect containing credentials at ${origin}.`, requestId);
749
+ }
750
+ if (redirects >= MAX_REDIRECTS) {
751
+ throw new RedirectError(`Too many redirects from ${origin}.`, requestId);
752
+ }
753
+ // Match Fetch's HTTP-redirect method/body rules. Retained bodies are
754
+ // JSON strings, so 307/308 replay does not require buffering a stream.
755
+ const method = currentInit.method?.toUpperCase() ?? 'GET';
756
+ if (((response.status === 301 || response.status === 302) && method === 'POST') ||
757
+ (response.status === 303 && method !== 'GET' && method !== 'HEAD')) {
758
+ const headers = new Headers(currentInit.headers);
759
+ for (const name of [
760
+ 'content-encoding',
761
+ 'content-language',
762
+ 'content-location',
763
+ 'content-type',
764
+ 'content-length',
765
+ ]) {
766
+ headers.delete(name);
767
+ }
768
+ currentInit = { ...currentInit, method: 'GET', body: undefined, headers };
769
+ }
770
+ currentUrl = target.href;
771
+ }
772
+ }
794
773
  buildHeaders(requestId, options) {
795
774
  const headers = {
796
775
  'x-request-id': requestId,
@@ -814,33 +793,74 @@ export class HttpClient {
814
793
  return headers;
815
794
  }
816
795
  /**
817
- * Retry-delay sleep that bails the moment the shutdown signal fires: a
818
- * RATE_LIMITED `Retry-After: 60` or a transport backoff must not delay the
819
- * honest-detach exit by up to a minute — reject with the InterruptError
820
- * reason immediately. Mirrors poll.ts::sleepUnlessInterrupted.
796
+ * Retry-delay sleep that ends the moment the shutdown signal or the caller's
797
+ * own signal for this request fires, rejecting with that signal's reason: a
798
+ * RATE_LIMITED `Retry-After: 60` or a transport backoff must neither delay
799
+ * the honest-detach exit by up to a minute nor outlast a deadline the caller
800
+ * set (`run wait --timeout`). An interrupt outranks the caller's signal when
801
+ * both have fired. The race itself is poll-support.ts::sleepUnlessInterrupted,
802
+ * over the two signals composed into one.
821
803
  */
822
- sleepBeforeRetry(ms) {
823
- const signal = this.shutdownSignal;
824
- if (signal == null)
804
+ async sleepBeforeRetry(ms, callerSignal) {
805
+ const sources = [this.shutdownSignal, callerSignal].filter((source) => source != null);
806
+ if (sources.length === 0)
825
807
  return this.sleep(ms);
826
- if (signal.aborted)
827
- return Promise.reject(signal.reason);
828
- return new Promise((resolve, reject) => {
829
- const onAbort = () => reject(signal.reason);
830
- signal.addEventListener('abort', onAbort, { once: true });
831
- this.sleep(ms, signal).then(() => {
832
- signal.removeEventListener('abort', onAbort);
833
- resolve();
834
- }, err => {
835
- signal.removeEventListener('abort', onAbort);
836
- reject(err instanceof Error ? err : new Error(String(err)));
837
- });
838
- });
808
+ const reason = () => this.shutdownSignal?.aborted ? this.shutdownSignal.reason : callerSignal?.reason;
809
+ if (sources.some(source => source.aborted))
810
+ throw reason();
811
+ // Manual composition, as for every request (see `composeAbortSignals`).
812
+ const { signal, cleanup } = composeAbortSignals(sources);
813
+ try {
814
+ await sleepUnlessInterrupted(this.sleep, ms, signal);
815
+ }
816
+ catch (err) {
817
+ // A fired signal rejects with its own reason; any other failure of the
818
+ // sleep is passed on as it came.
819
+ throw signal.aborted ? reason() : err;
820
+ }
821
+ finally {
822
+ cleanup();
823
+ }
839
824
  }
840
825
  debug(event) {
841
826
  if (this.onDebug)
842
827
  this.onDebug(event);
843
828
  }
829
+ /**
830
+ * Shared handling for a transport failure — the fetch itself rejected, or
831
+ * the connection dropped while the body was being read. Records the failure,
832
+ * then either throws {@link TransportError} (retries not allowed for this
833
+ * request, or the transport budget is spent) or announces the retry and
834
+ * returns the backoff delay for the caller to sleep before `continue`.
835
+ */
836
+ transportRetryDelayOrThrow(args) {
837
+ const { method, url, attempt, requestId } = args;
838
+ this.debug({
839
+ kind: 'error',
840
+ method,
841
+ url,
842
+ attempt,
843
+ requestId,
844
+ errorCode: 'TRANSPORT',
845
+ durationMs: Date.now() - args.startedAt,
846
+ });
847
+ const decision = args.allowTransportRetry
848
+ ? transportRetryDecision(attempt, this.random)
849
+ : { retry: false, delayMs: 0 };
850
+ if (!decision.retry)
851
+ throw new TransportError(args.message, requestId);
852
+ this.transition(`${args.transition} on ${shortPath(args.path)} — retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
853
+ this.debug({
854
+ kind: 'retry',
855
+ method,
856
+ url,
857
+ attempt,
858
+ requestId,
859
+ errorCode: 'TRANSPORT',
860
+ delayMs: decision.delayMs,
861
+ });
862
+ return decision.delayMs;
863
+ }
844
864
  transition(msg) {
845
865
  if (this.onTransition)
846
866
  this.onTransition(msg);
@@ -854,6 +874,12 @@ export class HttpClient {
854
874
  return this.requestWithMeta(method, path, options).then(r => r.body);
855
875
  }
856
876
  }
877
+ class RedirectError extends TransportError {
878
+ nextAction = 'Check the configured API endpoint and its redirect configuration. This request was not retried.';
879
+ constructor(message, requestId) {
880
+ super(message, requestId);
881
+ }
882
+ }
857
883
  function trimTrailingSlash(url) {
858
884
  return url.endsWith('/') ? url.slice(0, -1) : url;
859
885
  }
@@ -866,7 +892,28 @@ function shortPath(pathOrUrl) {
866
892
  return pathOrUrl;
867
893
  }
868
894
  }
895
+ /**
896
+ * `new URL()` resolves `.` and `..` path segments (including their
897
+ * percent-encoded forms), so an id or name of `..` would silently climb out
898
+ * of its route (`DELETE /projects/<id>/env/..` becomes `DELETE /projects/<id>/`).
899
+ * Refuse such a segment before any request is built.
900
+ */
901
+ function assertNoDotSegments(path) {
902
+ for (const segment of path.split('/')) {
903
+ let decoded = segment;
904
+ try {
905
+ decoded = decodeURIComponent(segment);
906
+ }
907
+ catch {
908
+ // Malformed escape: URL parsing will not treat it as a dot segment.
909
+ }
910
+ if (decoded === '.' || decoded === '..') {
911
+ throw localValidationError('value', `"${decoded}" is not a valid id or name: it would escape the route ("." and ".." are not allowed)`, undefined, 'field');
912
+ }
913
+ }
914
+ }
869
915
  export function buildUrl(baseUrl, path, query) {
916
+ assertNoDotSegments(path);
870
917
  const normalizedPath = path.startsWith('/') ? path : `/${path}`;
871
918
  const url = new URL(`${trimTrailingSlash(baseUrl)}${normalizedPath}`);
872
919
  if (query) {
@@ -896,12 +943,11 @@ function newRequestId() {
896
943
  * cleanup pass. Under a request-heavy path (retries, a wide closure/batch
897
944
  * fan-out, RATE_LIMITED backoff) this reproduces — per HTTP request instead
898
945
  * of per poll-iteration — the exact backlog mechanism already fixed once in
899
- * `poll.ts` (`JSFinalizationRegistry::Cleanup` → `KeepDuringJob` →
946
+ * the former per-result poller (`JSFinalizationRegistry::Cleanup` → `KeepDuringJob` →
900
947
  * `OrderedHashSet::Add` pegging the CPU once the deferred backlog is finally
901
- * walked). Measured directly: the RATE_LIMITED closure-fanout scenario in
902
- * `test.rerun.spec.ts` alone drives ~330K `AbortSignal.any` calls against the
903
- * one process-lifetime `globalShutdown.signal` over the life of that single
904
- * test file.
948
+ * walked). Measured directly: a single RATE_LIMITED fan-out test file drove
949
+ * ~330K `AbortSignal.any` calls against the one process-lifetime
950
+ * `globalShutdown.signal`.
905
951
  *
906
952
  * This performs the identical "first one wins, propagate its `.reason`"
907
953
  * composition with a plain `AbortController` and ordinary
@@ -964,9 +1010,9 @@ function unrefTimer(timer) {
964
1010
  if (typeof unref === 'function')
965
1011
  unref.call(timer);
966
1012
  }
967
- async function safeReadJson(response) {
1013
+ async function readErrorResponseBody(response) {
968
1014
  try {
969
- return await response.json();
1015
+ return { json: await response.json(), notJson: false };
970
1016
  }
971
1017
  catch (err) {
972
1018
  // Don't swallow interrupts, aborts, or timeouts as a null body — the caller
@@ -975,9 +1021,30 @@ async function safeReadJson(response) {
975
1021
  throw err;
976
1022
  if (isAbortError(err) || isTimeoutError(err))
977
1023
  throw err;
978
- return null;
1024
+ // A JSON parse failure is a SyntaxError. Anything else is a body that
1025
+ // failed to arrive, which keeps the status mapping it always had.
1026
+ return { json: null, notJson: err instanceof Error && err.name === 'SyntaxError' };
979
1027
  }
980
1028
  }
1029
+ /** A 4xx that the API would have answered with JSON; 408 and 429 keep their retries. */
1030
+ function isNonApiCandidateStatus(status) {
1031
+ return status >= 400 && status < 500 && status !== 408 && status !== 429;
1032
+ }
1033
+ /**
1034
+ * Exit-10 error for a 4xx whose body is not JSON. It is a `TransportError`
1035
+ * with no `httpStatus`, like a bare edge 502: the status belongs to whatever
1036
+ * answered in front of the API, so nothing downstream reads it as the API's
1037
+ * verdict. The status and content type stay in `details`.
1038
+ */
1039
+ function nonApiResponseError(response, requestId, url) {
1040
+ const contentType = response.headers.get('content-type');
1041
+ return new TransportError(`Something between this machine and the TestSprite API answered HTTP ${response.status} ` +
1042
+ `(content-type: ${contentType ?? 'none'}) instead of the API; the API key was not rejected.`, requestId, {
1043
+ nextAction: 'A proxy, firewall or captive portal probably answered. Check HTTPS_PROXY, ' +
1044
+ `or ask your network admin to allow ${new URL(url).host}, then retry.`,
1045
+ details: { httpStatus: response.status, contentType },
1046
+ });
1047
+ }
981
1048
  /**
982
1049
  * Build a typed error for a successful response whose body could not be parsed
983
1050
  * as JSON.
@@ -1005,8 +1072,8 @@ export function malformedResponseError(response, requestId, cause) {
1005
1072
  message: `The server returned a non-JSON response${contentTypeNote} for an HTTP ${response.status}. ` +
1006
1073
  `This usually means the endpoint is not the TestSprite API — a proxy, captive portal, or ` +
1007
1074
  `login page can return HTML with a success status.`,
1008
- nextAction: 'Check that --endpoint-url / TESTSPRITE_API_URL points at the TestSprite API ' +
1009
- '(default https://api.testsprite.com), then retry.',
1075
+ nextAction: 'Check HTTPS_PROXY and that nothing on this network answers in place of the ' +
1076
+ 'TestSprite API, then retry.',
1010
1077
  requestId,
1011
1078
  details: {
1012
1079
  httpStatus: response.status,
@@ -1019,10 +1086,10 @@ export function malformedResponseError(response, requestId, cause) {
1019
1086
  * Read a successful response body as text, bounded to `maxBytes`.
1020
1087
  *
1021
1088
  * `response.json()` buffers the ENTIRE body into memory before parsing, with no
1022
- * upper limit — a large `test result --history` page, or a run with a long
1023
- * `steps[]` array (getRun `includeSteps`), grows the heap in proportion to the
1024
- * payload. This reads the body incrementally and stops once the accumulated
1025
- * size crosses `maxBytes`, so a pathological (or hostile) response fails fast
1089
+ * upper limit — a large list page, or a result with a long `steps[]` array,
1090
+ * grows the heap in proportion to the payload. This reads the body
1091
+ * incrementally and stops once the accumulated size crosses `maxBytes`, so a
1092
+ * pathological (or hostile) response fails fast
1026
1093
  * with a typed PAYLOAD_TOO_LARGE error instead of exhausting memory.
1027
1094
  *
1028
1095
  * A declared `Content-Length` over the cap is rejected before any body is read.
@@ -1096,8 +1163,8 @@ function responseTooLargeError(requestId, maxBytes, observedBytes) {
1096
1163
  code: 'PAYLOAD_TOO_LARGE',
1097
1164
  message: `The server response exceeded the client-side ${limitMiB} MiB limit and was not ` +
1098
1165
  `buffered, to avoid unbounded memory use.`,
1099
- nextAction: 'Narrow the result set and retry — e.g. a smaller --page-size, a tighter --since ' +
1100
- 'window, or scope --history to a single run.',
1166
+ nextAction: 'Ask for fewer items and retry, e.g. with a smaller --page-size or --limit, or a ' +
1167
+ 'narrower --status, where the command offers them.',
1101
1168
  requestId,
1102
1169
  details: {
1103
1170
  maxBytes,
@@ -1126,13 +1193,26 @@ export function parseRetryAfter(headerValue) {
1126
1193
  function isTransportEdgeStatus(status) {
1127
1194
  return status === 408 || status === 502 || status === 504;
1128
1195
  }
1196
+ /**
1197
+ * True when the body carries a catalog error code (`{error:{code}}` or a bare
1198
+ * `{code}`), i.e. the facade answered rather than an edge proxy.
1199
+ */
1200
+ function hasCatalogErrorCode(body) {
1201
+ if (typeof body !== 'object' || body === null)
1202
+ return false;
1203
+ const obj = body;
1204
+ const errorObj = typeof obj.error === 'object' && obj.error !== null
1205
+ ? obj.error
1206
+ : obj;
1207
+ return isErrorCode(errorObj.code);
1208
+ }
1129
1209
  function transportRetryDecision(attempt, random) {
1130
1210
  if (attempt >= MAX_ATTEMPTS_TRANSPORT)
1131
1211
  return { retry: false, delayMs: 0 };
1132
1212
  return { retry: true, delayMs: backoffDelay(attempt, random) };
1133
1213
  }
1134
1214
  function canRetryTransport(method, options) {
1135
- return isIdempotentMethod(method) || hasIdempotencyKey(options.headers);
1215
+ return (options.replaySafe === true || isIdempotentMethod(method) || hasIdempotencyKey(options.headers));
1136
1216
  }
1137
1217
  function isIdempotentMethod(method) {
1138
1218
  const normalized = method.toUpperCase();
@@ -1176,9 +1256,10 @@ function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict
1176
1256
  // self-heal by upgrading, so fail fast with the upgrade guidance.
1177
1257
  return { retry: false, delayMs: 0 };
1178
1258
  case 'CONFLICT':
1179
- // Read paths (e.g. GET /failure) retry once: 409 = mid-mutation snapshot.
1180
- // Write paths (e.g. POST /runs) must NOT retry: 409 = another run is in
1181
- // flight (persistent), retrying would enqueue a second run.
1259
+ // A 409 is retried once by default: a transient server-side conflict.
1260
+ // A caller whose 409 is persistent (a run trigger: another run is already
1261
+ // in flight) passes `retryOnConflict: false`, since retrying would
1262
+ // enqueue a second run.
1182
1263
  if (!retryOnConflict)
1183
1264
  return { retry: false, delayMs: 0 };
1184
1265
  if (attempt >= MAX_ATTEMPTS_CONFLICT)
@@ -1244,22 +1325,4 @@ function isTimeoutError(err) {
1244
1325
  }
1245
1326
  return false;
1246
1327
  }
1247
- /**
1248
- * Drop server-sent `feature: 'deprecation'` advisories from a rerun response.
1249
- * The CLI owns the deprecation signal itself (one stderr line plus the JSON
1250
- * `deprecations` key), so passing the server's through would announce the same
1251
- * thing twice. Matched on the machine-readable `feature`, never on message
1252
- * text; other advisories (autoHeal) are kept and an emptied list is removed.
1253
- */
1254
- function withoutDeprecationAdvisories(body) {
1255
- if (!body.advisories)
1256
- return body;
1257
- const kept = body.advisories.filter(a => a.feature !== 'deprecation');
1258
- if (kept.length === body.advisories.length)
1259
- return body;
1260
- const next = { ...body, advisories: kept };
1261
- if (kept.length === 0)
1262
- delete next.advisories;
1263
- return next;
1264
- }
1265
1328
  //# sourceMappingURL=http.js.map