@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
@@ -1,100 +0,0 @@
1
- /**
2
- * Shared polling utility for `test run --wait` and `test wait`.
3
- *
4
- * Polling protocol:
5
- *
6
- * 1. **Long-poll preferred** (server supports `?waitSeconds`):
7
- * Pass `waitSeconds = min(remaining, 25)` on each GET. The server returns when
8
- * the run is terminal OR after `waitSeconds` elapses with the latest row.
9
- *
10
- * 2. **Exponential backoff fallback** (server returns 400 VALIDATION_ERROR on
11
- * `waitSeconds` — older backend / local emulator): backoff 2s→4s→8s→15s
12
- * with ±20% jitter, capped at 15s. Honors `Retry-After` if returned.
13
- *
14
- * 404 `details.reason: "not_yet_visible"` → honor Retry-After 1s, retry once.
15
- * 404 `details.reason: "not_found"` → throw immediately (exit 4, no retry).
16
- * 429 RATE_LIMITED → honor Retry-After (server emits this code for the
17
- * shared throttle envelope; LAMBDA_THROTTLED is the upstream NestJS
18
- * exception class but the CLI wire-code is RATE_LIMITED per
19
- * the CLI error spec). Up to 3 attempts via `http.ts`, then throw (exit 11).
20
- * 5xx → single retry honoring Retry-After, second 5xx throws (exit 9).
21
- * Deadline exceeded → throw `TimeoutError`.
22
- */
23
- import type { ShutdownHandle } from './interrupt.js';
24
- import type { RunResponse } from './runs.types.js';
25
- export { isTerminalStatus } from './runs.types.js';
26
- /**
27
- * Minimal interface that `pollRunUntilTerminal` requires from the HTTP client.
28
- * Using a structural interface (rather than the concrete `HttpClient`) makes
29
- * it easy to supply a lightweight mock in tests without implementing the full
30
- * class.
31
- */
32
- export interface RunClient {
33
- getRun(runId: string, options?: {
34
- waitSeconds?: number;
35
- signal?: AbortSignal;
36
- }): Promise<RunResponse>;
37
- }
38
- /** Thrown when the polling deadline is hit. */
39
- export declare class TimeoutError extends Error {
40
- readonly runId: string;
41
- constructor(runId: string, timeoutSeconds: number);
42
- }
43
- export interface PollOptions {
44
- /** Maximum number of seconds to wait for a terminal status. */
45
- timeoutSeconds: number;
46
- /** Called after every successful GET poll (terminal or not). */
47
- onTick?: (run: RunResponse, elapsedMs: number) => void;
48
- /**
49
- * Optional callback for user-relevant state transitions during polling.
50
- * Emits messages for polling-mode switches and "not yet visible" retries
51
- * without the full debug firehose. Wired to stderr at `--verbose` level.
52
- */
53
- onTransition?: (msg: string) => void;
54
- /**
55
- * Injectable sleep function. Defaults to `setTimeout`-based sleep.
56
- * Inject a mock in tests to avoid real delays.
57
- */
58
- sleep?: (ms: number) => Promise<void>;
59
- /**
60
- * Optional escape hatch invoked after every **non-terminal** run tick.
61
- * Lets the caller resolve a terminal `RunResponse` from an alternate
62
- * source when the run-surface row itself will never finalize.
63
- *
64
- * The motivating case: backend-test run rows are written
65
- * `queued` then orphaned server-side (`finalizeRun` is FE-only), so the
66
- * run-row poll would always hit `--timeout` → exit 7 even on a passing BE
67
- * test. The handler supplies a fallback that reads the testId-scoped
68
- * verdict (`GET /tests/{id}/result`) and returns a synthesized terminal
69
- * `RunResponse` once the test record reports terminal.
70
- *
71
- * Return a terminal `RunResponse` to finish the poll, or `null`/`undefined`
72
- * to keep polling the run row. Only ever called on non-terminal ticks, so
73
- * the FE path (where the run row finalizes normally) is unaffected.
74
- *
75
- * `signal` aborts at the remaining `--timeout`; thread it through any HTTP
76
- * the callback makes so a stalled alternate lookup can't overrun the
77
- * user's deadline (the per-request HTTP timeout is much larger).
78
- */
79
- resolveAlternate?: (run: RunResponse, elapsedMs: number, signal: AbortSignal) => Promise<RunResponse | null>;
80
- /**
81
- * Graceful-detach coordinator. While the poll runs, the
82
- * scope is armed: a SIGINT/SIGTERM aborts `shutdown.signal` with an
83
- * `InterruptError` instead of killing the process, and this loop surfaces
84
- * it immediately — the in-flight long-poll fetch aborts (composed into the
85
- * per-iteration signal) and every backoff/retry sleep bails early. The
86
- * caller's catch block renders the honest partial + re-attach hint.
87
- * Absent (tests, non-wait callers): behavior is unchanged.
88
- */
89
- shutdown?: ShutdownHandle;
90
- }
91
- /**
92
- * Poll `GET /api/cli/v1/runs/{runId}` until the run reaches a terminal
93
- * status or the deadline is exceeded.
94
- *
95
- * @returns The final `RunResponse` when terminal.
96
- * @throws `TimeoutError` when `timeoutSeconds` elapses before terminal.
97
- * @throws `ApiError` for `NOT_FOUND` (exit 4), `RATE_LIMITED` (exit 11),
98
- * and unrecoverable server errors.
99
- */
100
- export declare function pollRunUntilTerminal(client: RunClient, runId: string, options: PollOptions): Promise<RunResponse>;
package/dist/lib/poll.js DELETED
@@ -1,290 +0,0 @@
1
- /**
2
- * Shared polling utility for `test run --wait` and `test wait`.
3
- *
4
- * Polling protocol:
5
- *
6
- * 1. **Long-poll preferred** (server supports `?waitSeconds`):
7
- * Pass `waitSeconds = min(remaining, 25)` on each GET. The server returns when
8
- * the run is terminal OR after `waitSeconds` elapses with the latest row.
9
- *
10
- * 2. **Exponential backoff fallback** (server returns 400 VALIDATION_ERROR on
11
- * `waitSeconds` — older backend / local emulator): backoff 2s→4s→8s→15s
12
- * with ±20% jitter, capped at 15s. Honors `Retry-After` if returned.
13
- *
14
- * 404 `details.reason: "not_yet_visible"` → honor Retry-After 1s, retry once.
15
- * 404 `details.reason: "not_found"` → throw immediately (exit 4, no retry).
16
- * 429 RATE_LIMITED → honor Retry-After (server emits this code for the
17
- * shared throttle envelope; LAMBDA_THROTTLED is the upstream NestJS
18
- * exception class but the CLI wire-code is RATE_LIMITED per
19
- * the CLI error spec). Up to 3 attempts via `http.ts`, then throw (exit 11).
20
- * 5xx → single retry honoring Retry-After, second 5xx throws (exit 9).
21
- * Deadline exceeded → throw `TimeoutError`.
22
- */
23
- import { ApiError, InterruptError } from './errors.js';
24
- import { defaultSleep, isAbortError, sleepUnlessInterrupted } from './poll-support.js';
25
- import { isTerminalStatus } from './runs.types.js';
26
- export { isTerminalStatus } from './runs.types.js';
27
- /** Thrown when the polling deadline is hit. */
28
- export class TimeoutError extends Error {
29
- runId;
30
- constructor(runId, timeoutSeconds) {
31
- super(`Timed out after ${timeoutSeconds}s waiting for run ${runId}`);
32
- this.name = 'TimeoutError';
33
- this.runId = runId;
34
- }
35
- }
36
- const LONG_POLL_WAIT_SECONDS = 25;
37
- /** Backoff schedule for the non-long-poll fallback path (ms). */
38
- const BACKOFF_SCHEDULE_MS = [2000, 4000, 8000, 15000];
39
- /**
40
- * Poll `GET /api/cli/v1/runs/{runId}` until the run reaches a terminal
41
- * status or the deadline is exceeded.
42
- *
43
- * @returns The final `RunResponse` when terminal.
44
- * @throws `TimeoutError` when `timeoutSeconds` elapses before terminal.
45
- * @throws `ApiError` for `NOT_FOUND` (exit 4), `RATE_LIMITED` (exit 11),
46
- * and unrecoverable server errors.
47
- */
48
- export async function pollRunUntilTerminal(client, runId, options) {
49
- // Arm the graceful-detach scope for the duration of the poll:
50
- // while armed, a termination signal aborts instead of hard-killing the
51
- // process, and the wait-path catch blocks own the honest detach UX.
52
- const disarm = options.shutdown?.arm();
53
- try {
54
- return await pollLoop(client, runId, options);
55
- }
56
- catch (err) {
57
- if (err instanceof InterruptError && options.shutdown?.signal.aborted) {
58
- err.runWaitContext = true;
59
- }
60
- throw err;
61
- }
62
- finally {
63
- disarm?.();
64
- }
65
- }
66
- async function pollLoop(client, runId, options) {
67
- const { timeoutSeconds, resolveAlternate } = options;
68
- const shutdownSignal = options.shutdown?.signal;
69
- const rawSleep = options.sleep ?? defaultSleep;
70
- // Every sleep site (retryAfterSeconds, backoff schedule, not_yet_visible,
71
- // 5xx retry) bails immediately on interrupt — a Ctrl-C must not sit out a
72
- // 15s backoff before it is noticed.
73
- const sleep = (ms) => sleepUnlessInterrupted(rawSleep, ms, shutdownSignal);
74
- const startMs = Date.now();
75
- const deadlineMs = startMs + timeoutSeconds * 1000;
76
- // Hoisted ONCE per poll *session* rather than re-minted every iteration.
77
- // The abort target here — deadlineMs + a transport cushion — is a fixed
78
- // absolute instant that does not change from one iteration to the next
79
- // (remainingMs shrinks, but remainingMs + TRANSPORT_CUSHION_MS measured
80
- // from "now" always lands on the same deadlineMs + cushion point). Minting
81
- // a fresh AbortController + setTimeout + `AbortSignal.any` composite every
82
- // iteration was therefore pure churn with no behavioral purpose: on a
83
- // `--wait` fan-out over many concurrent runIds, each polling for many
84
- // iterations, this created thousands of composite signals per invocation.
85
- // Every `AbortSignal.any` call registers an internal dependency listener
86
- // on the long-lived `shutdownSignal`, tracked via a WeakRef +
87
- // FinalizationRegistry so the listener can be reclaimed once the derived
88
- // signal is garbage-collected without leaking on the long-lived source —
89
- // but under a high allocation rate with no macrotask yield between
90
- // iterations (`TestDeps.sleep` in tests resolves via a bare microtask),
91
- // V8 can fall behind on running that reclamation incrementally, and the
92
- // eventual cleanup pass then has to walk a large backlog in one go
93
- // (`JSFinalizationRegistry::Cleanup` → `KeepDuringJob` →
94
- // `OrderedHashSet::Add`), pegging the CPU for minutes. One controller,
95
- // one timer, and one composed signal — created once, reused for every
96
- // iteration and every retry, cleared once when the session ends —
97
- // removes that per-iteration scaling factor entirely; the deadline
98
- // semantics are unchanged, since the abort target was already the same
99
- // absolute instant on every iteration.
100
- const TRANSPORT_CUSHION_MS = 2000;
101
- const deadlineController = new AbortController();
102
- const deadlineTimer = setTimeout(() => deadlineController.abort(), deadlineMs - startMs + TRANSPORT_CUSHION_MS);
103
- const sessionSignal = shutdownSignal != null
104
- ? AbortSignal.any([deadlineController.signal, shutdownSignal])
105
- : deadlineController.signal;
106
- // Same hoisting rationale for the `resolveAlternate` abort target
107
- // (deadlineMs, no cushion — also a fixed absolute instant). Allocated
108
- // lazily so callers that never pass `resolveAlternate` pay nothing for it.
109
- let altAbort;
110
- let altTimer;
111
- let altSignal;
112
- if (resolveAlternate) {
113
- altAbort = new AbortController();
114
- const controller = altAbort;
115
- altTimer = setTimeout(() => controller.abort(), deadlineMs - startMs);
116
- altSignal =
117
- shutdownSignal != null ? AbortSignal.any([altAbort.signal, shutdownSignal]) : altAbort.signal;
118
- }
119
- try {
120
- return await pollIterations(client, runId, options, {
121
- startMs,
122
- deadlineMs,
123
- sessionSignal,
124
- altSignal,
125
- sleep,
126
- });
127
- }
128
- finally {
129
- clearTimeout(deadlineTimer);
130
- if (altTimer !== undefined)
131
- clearTimeout(altTimer);
132
- }
133
- }
134
- async function pollIterations(client, runId, options, ctx) {
135
- const { timeoutSeconds, onTick, onTransition, resolveAlternate } = options;
136
- const shutdownSignal = options.shutdown?.signal;
137
- const { startMs, deadlineMs, sessionSignal, altSignal, sleep } = ctx;
138
- // Track whether the server supports ?waitSeconds. Start optimistic.
139
- let useBackoff = false;
140
- let backoffIndex = 0;
141
- let consecutiveErrors = 0;
142
- // 404 not_yet_visible retry budget (one soft retry per event).
143
- let notYetVisibleRetries = 0;
144
- while (true) {
145
- // Interrupt outranks the deadline: a Ctrl-C that raced the timeout must
146
- // surface as the honest detach, not as a generic TimeoutError.
147
- if (shutdownSignal?.aborted)
148
- throw shutdownSignal.reason;
149
- const now = Date.now();
150
- if (now >= deadlineMs) {
151
- throw new TimeoutError(runId, timeoutSeconds);
152
- }
153
- const remainingMs = deadlineMs - now;
154
- const remainingSeconds = Math.ceil(remainingMs / 1000);
155
- let run;
156
- try {
157
- if (useBackoff) {
158
- run = await client.getRun(runId, { signal: sessionSignal });
159
- }
160
- else {
161
- const waitSeconds = Math.min(remainingSeconds, LONG_POLL_WAIT_SECONDS);
162
- run = await client.getRun(runId, { waitSeconds, signal: sessionSignal });
163
- }
164
- // Successful GET resets the consecutive-error counter.
165
- consecutiveErrors = 0;
166
- notYetVisibleRetries = 0;
167
- }
168
- catch (err) {
169
- // Interrupt classification precedes the timeout mapping: the composed
170
- // signal makes the fetch reject on Ctrl-C, and that abort must surface
171
- // as the InterruptError — not as a spurious TimeoutError.
172
- if (err instanceof InterruptError)
173
- throw err;
174
- if (shutdownSignal?.aborted)
175
- throw shutdownSignal.reason;
176
- // An AbortError from the session controller means the deadline passed
177
- // while the fetch was in flight — surface as TimeoutError.
178
- if (isAbortError(err)) {
179
- throw new TimeoutError(runId, timeoutSeconds);
180
- }
181
- if (!(err instanceof ApiError))
182
- throw err;
183
- // 400 VALIDATION_ERROR on waitSeconds → fall back to backoff.
184
- if (err.code === 'VALIDATION_ERROR' && !useBackoff) {
185
- useBackoff = true;
186
- onTransition?.(`Server does not support long-poll (?waitSeconds) — switching to exponential backoff mode`);
187
- // Retry immediately (no sleep) on the first switch.
188
- continue;
189
- }
190
- // 404 not_yet_visible → retry once after 1s (clamped to remaining deadline).
191
- if (err.code === 'NOT_FOUND' &&
192
- err.getDetail('reason') === 'not_yet_visible' &&
193
- notYetVisibleRetries === 0) {
194
- notYetVisibleRetries += 1;
195
- onTransition?.(`Server reports run ${runId} not yet visible — retrying in 1s`);
196
- const remaining = deadlineMs - Date.now();
197
- await sleep(Math.min(1000, Math.max(0, remaining)));
198
- continue;
199
- }
200
- // 404 not_found (cross-tenant or stale runId) → exit immediately.
201
- if (err.code === 'NOT_FOUND') {
202
- throw err;
203
- }
204
- // RATE_LIMITED (429) — honor Retry-After; max 3 retries total from
205
- // the http.ts retry table, but we also want to track here so if
206
- // http.ts already exhausted retries and re-throws, we propagate.
207
- if (err.code === 'RATE_LIMITED') {
208
- throw err; // http.ts already honored Retry-After + capped at 3.
209
- }
210
- // 5xx (INTERNAL / UNAVAILABLE) — single retry.
211
- if (err.code === 'INTERNAL' || err.code === 'UNAVAILABLE') {
212
- consecutiveErrors += 1;
213
- if (consecutiveErrors >= 2)
214
- throw err; // second error propagates.
215
- // http.ts already applied one retry for INTERNAL/UNAVAILABLE;
216
- // if we reach here it means http.ts gave up. We absorb one
217
- // additional attempt at the polling layer.
218
- const retryAfterSec = err.getDetail('retryAfterSec', (v) => typeof v === 'number');
219
- const backoffMs = retryAfterSec !== undefined ? retryAfterSec * 1000 : 1000;
220
- const remaining = deadlineMs - Date.now();
221
- await sleep(Math.min(backoffMs, Math.max(0, remaining)));
222
- continue;
223
- }
224
- // Everything else propagates.
225
- throw err;
226
- }
227
- const elapsedMs = Date.now() - startMs;
228
- onTick?.(run, elapsedMs);
229
- if (isTerminalStatus(run.status)) {
230
- return run;
231
- }
232
- // Non-terminal run tick. Give the caller a chance to resolve a terminal
233
- // verdict from an alternate source (e.g. the backend testId-scoped
234
- // result when the run-surface row never finalizes).
235
- if (resolveAlternate) {
236
- // Bound the alternate lookup by the REMAINING --timeout (not the much
237
- // larger per-request HTTP timeout) so a stalled fallback read can't
238
- // overrun the user's deadline.
239
- const altRemainingMs = deadlineMs - Date.now();
240
- if (altRemainingMs <= 0) {
241
- throw new TimeoutError(runId, timeoutSeconds);
242
- }
243
- // The alternate lookup aborts on interrupt too; its errors are swallowed
244
- // by the fallback (best-effort), so the loop-top interrupt check above
245
- // surfaces the InterruptError on the next iteration. `altSignal` is the
246
- // hoisted per-session signal (allocated once, above, whenever
247
- // `resolveAlternate` is present) — reused across every non-terminal
248
- // tick rather than re-composed each time.
249
- const alternate = await resolveAlternate(run, elapsedMs, altSignal);
250
- // Enforce the hard cap: reject a terminal alternate that only arrived
251
- // at/after the deadline, same as the run-row long-poll path below.
252
- if (Date.now() >= deadlineMs) {
253
- throw new TimeoutError(runId, timeoutSeconds);
254
- }
255
- if (alternate) {
256
- return alternate;
257
- }
258
- }
259
- // Honor server-supplied retryAfterSeconds when present.
260
- // Clamp to remaining deadline so --timeout is a hard cap even when the
261
- // server hint is larger than the time left.
262
- if (run.retryAfterSeconds !== undefined && run.retryAfterSeconds > 0) {
263
- const remaining = deadlineMs - Date.now();
264
- await sleep(Math.min(run.retryAfterSeconds * 1000, Math.max(0, remaining)));
265
- continue;
266
- }
267
- // Long-poll path: server already waited up to waitSeconds for us;
268
- // loop immediately (no extra client-side sleep).
269
- if (!useBackoff) {
270
- // Check deadline before looping.
271
- if (Date.now() >= deadlineMs) {
272
- throw new TimeoutError(runId, timeoutSeconds);
273
- }
274
- continue;
275
- }
276
- // Backoff fallback path. Clamp to remaining deadline so --timeout is a
277
- // hard cap even when the schedule delay exceeds the time left.
278
- const rawDelay = backoffScheduleDelay(backoffIndex);
279
- backoffIndex = Math.min(backoffIndex + 1, BACKOFF_SCHEDULE_MS.length - 1);
280
- const remaining = deadlineMs - Date.now();
281
- await sleep(Math.min(rawDelay, Math.max(0, remaining)));
282
- }
283
- }
284
- /** Returns a jittered delay from the backoff schedule (±20%). */
285
- function backoffScheduleDelay(index) {
286
- const base = BACKOFF_SCHEDULE_MS[Math.min(index, BACKOFF_SCHEDULE_MS.length - 1)];
287
- const jitter = base * 0.2 * (Math.random() * 2 - 1); // ±20%
288
- return Math.max(0, Math.round(base + jitter));
289
- }
290
- //# sourceMappingURL=poll.js.map
@@ -1,49 +0,0 @@
1
- /**
2
- * Sliding-window rate throttle for the `create-batch --run` fan-out.
3
- *
4
- * Tracks the wall-clock timestamps of `acquire()` calls inside a rolling
5
- * time window (`windowMs`). When the number of acquired slots in the window
6
- * reaches `maxPerWindow`, `acquire()` returns the number of milliseconds the
7
- * caller should sleep before proceeding, such that the oldest slot in the
8
- * window will have aged out by the time the caller resumes.
9
- *
10
- * This is intentionally a simple in-process sliding-window counter — it does
11
- * NOT coordinate across separate CLI processes. Cross-process collisions are
12
- * handled by the per-trigger `RATE_LIMITED` retry path in `runBatchRun`.
13
- *
14
- * @example
15
- * const throttle = new RateThrottle(50, 60_000);
16
- * const waitMs = throttle.acquire();
17
- * if (waitMs > 0) await sleep(waitMs);
18
- * // … fire the trigger …
19
- */
20
- export declare class RateThrottle {
21
- private readonly maxPerWindow;
22
- private readonly windowMs;
23
- /** Timestamps (Date.now()) of each acquired slot, oldest first. */
24
- private readonly slots;
25
- private readonly now;
26
- constructor(maxPerWindow: number, windowMs: number, now?: () => number);
27
- /**
28
- * Request a slot in the rate window.
29
- *
30
- * Prunes expired slots (older than `windowMs` ago), then:
31
- * - If there is headroom (slots in window < maxPerWindow): records the
32
- * current timestamp and returns `0` (no delay needed).
33
- * - If the window is full: returns the delay in milliseconds until the
34
- * oldest slot ages out. Does NOT record a new slot — the caller must
35
- * call `acquire()` again after sleeping to claim the freed slot.
36
- *
37
- * This means callers should loop:
38
- *
39
- * ```ts
40
- * let wait: number;
41
- * while ((wait = throttle.acquire()) > 0) {
42
- * await sleep(wait);
43
- * }
44
- * ```
45
- *
46
- * Returns `0` when a slot was successfully acquired.
47
- */
48
- acquire(): number;
49
- }
@@ -1,75 +0,0 @@
1
- /**
2
- * Sliding-window rate throttle for the `create-batch --run` fan-out.
3
- *
4
- * Tracks the wall-clock timestamps of `acquire()` calls inside a rolling
5
- * time window (`windowMs`). When the number of acquired slots in the window
6
- * reaches `maxPerWindow`, `acquire()` returns the number of milliseconds the
7
- * caller should sleep before proceeding, such that the oldest slot in the
8
- * window will have aged out by the time the caller resumes.
9
- *
10
- * This is intentionally a simple in-process sliding-window counter — it does
11
- * NOT coordinate across separate CLI processes. Cross-process collisions are
12
- * handled by the per-trigger `RATE_LIMITED` retry path in `runBatchRun`.
13
- *
14
- * @example
15
- * const throttle = new RateThrottle(50, 60_000);
16
- * const waitMs = throttle.acquire();
17
- * if (waitMs > 0) await sleep(waitMs);
18
- * // … fire the trigger …
19
- */
20
- export class RateThrottle {
21
- maxPerWindow;
22
- windowMs;
23
- /** Timestamps (Date.now()) of each acquired slot, oldest first. */
24
- slots = [];
25
- now;
26
- constructor(maxPerWindow, windowMs, now) {
27
- if (maxPerWindow < 1)
28
- throw new Error('maxPerWindow must be ≥ 1');
29
- if (windowMs < 1)
30
- throw new Error('windowMs must be ≥ 1');
31
- this.maxPerWindow = maxPerWindow;
32
- this.windowMs = windowMs;
33
- this.now = now ?? Date.now;
34
- }
35
- /**
36
- * Request a slot in the rate window.
37
- *
38
- * Prunes expired slots (older than `windowMs` ago), then:
39
- * - If there is headroom (slots in window < maxPerWindow): records the
40
- * current timestamp and returns `0` (no delay needed).
41
- * - If the window is full: returns the delay in milliseconds until the
42
- * oldest slot ages out. Does NOT record a new slot — the caller must
43
- * call `acquire()` again after sleeping to claim the freed slot.
44
- *
45
- * This means callers should loop:
46
- *
47
- * ```ts
48
- * let wait: number;
49
- * while ((wait = throttle.acquire()) > 0) {
50
- * await sleep(wait);
51
- * }
52
- * ```
53
- *
54
- * Returns `0` when a slot was successfully acquired.
55
- */
56
- acquire() {
57
- const ts = this.now();
58
- const cutoff = ts - this.windowMs;
59
- // Prune slots older than the window.
60
- while (this.slots.length > 0 && this.slots[0] <= cutoff) {
61
- this.slots.shift();
62
- }
63
- if (this.slots.length < this.maxPerWindow) {
64
- // Slot available — record and proceed.
65
- this.slots.push(ts);
66
- return 0;
67
- }
68
- // Window full — compute how long until the oldest slot ages out.
69
- const oldestTs = this.slots[0];
70
- const ageoutMs = oldestTs + this.windowMs - ts;
71
- // Add a 50 ms buffer so we land solidly after the cutoff.
72
- return Math.max(0, ageoutMs + 50);
73
- }
74
- }
75
- //# sourceMappingURL=rate-throttle.js.map
@@ -1,41 +0,0 @@
1
- import type { RunResponse } from './runs.types.js';
2
- import type { Ticker } from './ticker.js';
3
- /**
4
- * The in-place progress line for a polled run.
5
- *
6
- * Deliberately NO `completed/total` counter: on both the V2 and V3 read paths
7
- * `stepSummary.total` and `.completed` are computed from the same array of
8
- * already-finished step rows (a row is inserted only once its step has a
9
- * verdict), so the two can never differ — `0/0 steps` at the start and `N/N`
10
- * thereafter carried no information. Show the recorded count, or nothing.
11
- *
12
- * `tag` is inserted verbatim after the run id — the caller picks the bracket
13
- * style (`(testId)` for batch members, `[role]` for closure members) so the
14
- * two kinds of tag stay visually distinct.
15
- */
16
- export declare function formatRunProgressLine(run: RunResponse, elapsedMs: number, tag?: string): string;
17
- export interface LiveRunProgress {
18
- /** Feed a poll result; renders immediately and becomes the refresher's snapshot. */
19
- onTick(run: RunResponse, elapsedMs: number): void;
20
- /** Stop the 1s refresher. Idempotent; call before the ticker's final line. */
21
- stop(): void;
22
- }
23
- export interface LiveRunProgressOptions {
24
- /**
25
- * Whether to run the between-polls refresher. Defaults to
26
- * `ticker.redrawsInPlace` — a ticker that prints a NEW line per `update()`
27
- * (non-TTY, NO_COLOR) must not be redrawn once a second.
28
- */
29
- enabled?: boolean;
30
- intervalMs?: number;
31
- now?: () => number;
32
- setIntervalFn?: (cb: () => void, ms: number) => NodeJS.Timeout;
33
- clearIntervalFn?: (handle: NodeJS.Timeout) => void;
34
- }
35
- /**
36
- * Wraps a {@link Ticker} so the elapsed counter keeps moving between polls.
37
- * In long-poll mode a `getRun` returns every ~25s, so a ticker driven only by
38
- * `onTick` freezes for the whole wait; this re-renders the LAST snapshot
39
- * every second with the wall-clock time that has passed since it arrived.
40
- */
41
- export declare function createLiveRunProgress(ticker: Ticker, opts?: LiveRunProgressOptions, tag?: string): LiveRunProgress;
@@ -1,56 +0,0 @@
1
- /**
2
- * The in-place progress line for a polled run.
3
- *
4
- * Deliberately NO `completed/total` counter: on both the V2 and V3 read paths
5
- * `stepSummary.total` and `.completed` are computed from the same array of
6
- * already-finished step rows (a row is inserted only once its step has a
7
- * verdict), so the two can never differ — `0/0 steps` at the start and `N/N`
8
- * thereafter carried no information. Show the recorded count, or nothing.
9
- *
10
- * `tag` is inserted verbatim after the run id — the caller picks the bracket
11
- * style (`(testId)` for batch members, `[role]` for closure members) so the
12
- * two kinds of tag stay visually distinct.
13
- */
14
- export function formatRunProgressLine(run, elapsedMs, tag) {
15
- const elapsed = Math.round(elapsedMs / 1000);
16
- const total = run.stepSummary?.total ?? 0;
17
- const head = tag === undefined ? `Run ${run.runId}` : `Run ${run.runId} ${tag}`;
18
- const steps = total > 0 ? ` · ${total} step${total === 1 ? '' : 's'}` : '';
19
- return `${head} — ${run.status}${steps} · ${elapsed}s`;
20
- }
21
- /**
22
- * Wraps a {@link Ticker} so the elapsed counter keeps moving between polls.
23
- * In long-poll mode a `getRun` returns every ~25s, so a ticker driven only by
24
- * `onTick` freezes for the whole wait; this re-renders the LAST snapshot
25
- * every second with the wall-clock time that has passed since it arrived.
26
- */
27
- export function createLiveRunProgress(ticker, opts = {}, tag) {
28
- const now = opts.now ?? Date.now;
29
- const setIntervalFn = opts.setIntervalFn ?? setInterval;
30
- const clearIntervalFn = opts.clearIntervalFn ?? clearInterval;
31
- const enabled = opts.enabled ?? ticker.redrawsInPlace;
32
- let snapshot;
33
- let handle;
34
- if (enabled) {
35
- handle = setIntervalFn(() => {
36
- if (!snapshot)
37
- return;
38
- ticker.update(formatRunProgressLine(snapshot.run, snapshot.elapsedMs + (now() - snapshot.at), tag));
39
- }, opts.intervalMs ?? 1000);
40
- // Never let the refresher keep the process alive on its own.
41
- handle.unref?.();
42
- }
43
- return {
44
- onTick(run, elapsedMs) {
45
- snapshot = { run, elapsedMs, at: now() };
46
- ticker.update(formatRunProgressLine(run, elapsedMs, tag));
47
- },
48
- stop() {
49
- if (handle !== undefined) {
50
- clearIntervalFn(handle);
51
- handle = undefined;
52
- }
53
- },
54
- };
55
- }
56
- //# sourceMappingURL=run-progress.js.map
@@ -1,55 +0,0 @@
1
- /**
2
- * Shared V3-routing text surfaces.
3
- *
4
- * `V3_ROUTING_ADVISORY`/`emitV3RoutingAdvisory` back `auth status` and
5
- * `doctor`: `v3Enabled` on the `/me` response is the authoritative routing
6
- * bit, and when it is on, some commands behave differently while the V3
7
- * gaps stay open — the advisory names them. Copy lives here so both
8
- * commands stay in sync.
9
- *
10
- * `targetUrlAdvisoryText`/`emitTargetUrlMismatchAdvisory` back the
11
- * `--target-url` point-of-use advisory in `commands/test.ts` — a different,
12
- * response-driven mechanism (see its own docblock below) that does not
13
- * depend on `v3Enabled` at all.
14
- */
15
- /** One-word routing label for the text card. */
16
- export declare function routingLabel(v3Enabled: boolean): 'v3' | 'v2';
17
- /**
18
- * Consolidated advisory (stderr) emitted when V3 routing is on.
19
- *
20
- * Only genuinely-open gaps belong here. Two originally-listed items have
21
- * shipped and were removed: `test cancel` works on V3 runs, and `test delete`
22
- * mirrors into Postgres instead of leaving a runnable, billable row behind.
23
- * An advisory that warns about fixed behavior is worse than none — it teaches
24
- * users to distrust the whole block, and it sends them chasing a failure that
25
- * cannot happen.
26
- */
27
- export declare const V3_ROUTING_ADVISORY: string[];
28
- /** Write the advisory to a stderr sink, one line per call. */
29
- export declare function emitV3RoutingAdvisory(stderr: (line: string) => void): void;
30
- /**
31
- * Point-of-use advisory for `test run --target-url`, redesigned to be
32
- * response-driven rather than assumption-driven. The original
33
- * version probed `GET /me` for `v3Enabled` and warned on that ASSUMPTION —
34
- * but the backend is the ground truth here, not a proxy for it. V3
35
- * deliberately returns `targetUrl: ''` rather than echoing an override it
36
- * did not apply ("so the response doesn't claim a target we didn't use"),
37
- * while V2 echoes the real applied value. So the advisory now fires purely
38
- * from comparing what the caller asked for against what the trigger
39
- * response reports — it self-corrects the day the backend applies the
40
- * override, needs no `v3Enabled` lookup (and so no extra `/me` round trip,
41
- * no `X-CLI-Command` tagging machinery), and is exact rather than inferred.
42
- *
43
- * Deliberately type-agnostic in its wording (no "on the V3 path" claim):
44
- * a mismatch is reported purely from the observed response, regardless of
45
- * why the backend didn't apply the override.
46
- */
47
- export declare function targetUrlAdvisoryText(requested: string, applied: string): string;
48
- /**
49
- * Compare the requested `--target-url` against what the trigger response
50
- * reports and write the advisory when they differ. No-op when they match
51
- * (the override was applied, or the caller didn't supply one — callers are
52
- * expected to gate the `requested` argument on `opts.targetUrl !== undefined`
53
- * themselves so this stays a pure comparison).
54
- */
55
- export declare function emitTargetUrlMismatchAdvisory(stderr: (line: string) => void, requested: string, applied: string): void;