@testsprite/testsprite-cli 0.1.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.
- package/LICENSE +201 -0
- package/README.md +190 -0
- package/dist/assets/agent-skill/testsprite-verify.codex.md +119 -0
- package/dist/assets/agent-skill/testsprite-verify.skill.md +423 -0
- package/dist/commands/agent.d.ts +51 -0
- package/dist/commands/agent.js +552 -0
- package/dist/commands/auth.d.ts +38 -0
- package/dist/commands/auth.js +247 -0
- package/dist/commands/init.d.ts +63 -0
- package/dist/commands/init.js +350 -0
- package/dist/commands/project.d.ts +72 -0
- package/dist/commands/project.js +400 -0
- package/dist/commands/test.d.ts +1245 -0
- package/dist/commands/test.js +6214 -0
- package/dist/commands/usage.d.ts +63 -0
- package/dist/commands/usage.js +156 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +146 -0
- package/dist/lib/agent-targets.d.ts +50 -0
- package/dist/lib/agent-targets.js +99 -0
- package/dist/lib/bundle.d.ts +178 -0
- package/dist/lib/bundle.js +600 -0
- package/dist/lib/client-factory.d.ts +72 -0
- package/dist/lib/client-factory.js +120 -0
- package/dist/lib/config.d.ts +24 -0
- package/dist/lib/config.js +30 -0
- package/dist/lib/credentials.d.ts +17 -0
- package/dist/lib/credentials.js +122 -0
- package/dist/lib/dry-run/fetch.d.ts +18 -0
- package/dist/lib/dry-run/fetch.js +52 -0
- package/dist/lib/dry-run/samples.d.ts +50 -0
- package/dist/lib/dry-run/samples.js +676 -0
- package/dist/lib/errors.d.ts +118 -0
- package/dist/lib/errors.js +388 -0
- package/dist/lib/facade.d.ts +48 -0
- package/dist/lib/facade.js +104 -0
- package/dist/lib/failing-fe-resolver.d.ts +60 -0
- package/dist/lib/failing-fe-resolver.js +103 -0
- package/dist/lib/http.d.ts +255 -0
- package/dist/lib/http.js +608 -0
- package/dist/lib/output.d.ts +55 -0
- package/dist/lib/output.js +70 -0
- package/dist/lib/pagination.d.ts +56 -0
- package/dist/lib/pagination.js +81 -0
- package/dist/lib/poll.d.ts +88 -0
- package/dist/lib/poll.js +221 -0
- package/dist/lib/prompt.d.ts +8 -0
- package/dist/lib/prompt.js +97 -0
- package/dist/lib/rate-throttle.d.ts +49 -0
- package/dist/lib/rate-throttle.js +75 -0
- package/dist/lib/render-error.d.ts +15 -0
- package/dist/lib/render-error.js +44 -0
- package/dist/lib/runs.types.d.ts +344 -0
- package/dist/lib/runs.types.js +25 -0
- package/dist/lib/target-url.d.ts +25 -0
- package/dist/lib/target-url.js +127 -0
- package/dist/lib/ticker.d.ts +37 -0
- package/dist/lib/ticker.js +63 -0
- package/dist/lib/validate.d.ts +82 -0
- package/dist/lib/validate.js +165 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +2 -0
- package/package.json +65 -0
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Help-text footer pointing at the global options surface so users
|
|
3
|
+
* looking at any subcommand `--help` don't miss `--dry-run`, `--output`,
|
|
4
|
+
* `--profile`, `--endpoint-url`, `--debug`.
|
|
5
|
+
*/
|
|
6
|
+
export const GLOBAL_OPTS_HINT = '\nGlobal options (--dry-run, --output, --profile, --endpoint-url, --verbose, --debug):' +
|
|
7
|
+
'\n testsprite --help';
|
|
8
|
+
export function isOutputMode(value) {
|
|
9
|
+
return value === 'json' || value === 'text';
|
|
10
|
+
}
|
|
11
|
+
export class Output {
|
|
12
|
+
mode;
|
|
13
|
+
stdoutWrite;
|
|
14
|
+
stderrWrite;
|
|
15
|
+
rawStdoutWrite;
|
|
16
|
+
constructor(mode = 'text', streams = {}) {
|
|
17
|
+
this.mode = mode;
|
|
18
|
+
this.stdoutWrite =
|
|
19
|
+
streams.stdout ??
|
|
20
|
+
(line => {
|
|
21
|
+
console.log(line);
|
|
22
|
+
});
|
|
23
|
+
this.stderrWrite =
|
|
24
|
+
streams.stderr ??
|
|
25
|
+
(line => {
|
|
26
|
+
console.error(line);
|
|
27
|
+
});
|
|
28
|
+
this.rawStdoutWrite = streams.rawStdout ?? defaultRawStdout;
|
|
29
|
+
}
|
|
30
|
+
print(data, textRenderer) {
|
|
31
|
+
if (this.mode === 'json' || !textRenderer) {
|
|
32
|
+
this.stdoutWrite(JSON.stringify(data, null, 2));
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
this.stdoutWrite(textRenderer(data));
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Write a chunk of bytes to stdout verbatim. Awaits any
|
|
39
|
+
* Promise the rawStdout writer returns so a slow downstream
|
|
40
|
+
* consumer pauses the upstream reader instead of buffering chunks
|
|
41
|
+
* in memory. See `OutputStreams.rawStdout` for the backpressure
|
|
42
|
+
* contract.
|
|
43
|
+
*/
|
|
44
|
+
async writeChunk(text) {
|
|
45
|
+
await this.rawStdoutWrite(text);
|
|
46
|
+
}
|
|
47
|
+
error(message) {
|
|
48
|
+
if (this.mode === 'json') {
|
|
49
|
+
this.stderrWrite(JSON.stringify({ error: message }, null, 2));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
this.stderrWrite(`Error: ${message}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Default rawStdout writer. Honors stdout backpressure: when
|
|
57
|
+
* `process.stdout.write` returns `false` the OS buffer is full, so
|
|
58
|
+
* resolve only when `'drain'` fires. Without this an upstream stream
|
|
59
|
+
* reader keeps pulling chunks into memory — the documented streaming
|
|
60
|
+
* guarantee for `test code get` would silently degrade into "buffered
|
|
61
|
+
* download piped to a slow consumer."
|
|
62
|
+
*/
|
|
63
|
+
function defaultRawStdout(text) {
|
|
64
|
+
if (process.stdout.write(text))
|
|
65
|
+
return;
|
|
66
|
+
return new Promise(resolve => {
|
|
67
|
+
process.stdout.once('drain', () => resolve());
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
//# sourceMappingURL=output.js.map
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { HttpClient } from './http.js';
|
|
2
|
+
/**
|
|
3
|
+
* Page shape returned by every list endpoint per
|
|
4
|
+
* the CLI OpenAPI spec §components.schemas.ProjectList /
|
|
5
|
+
* TestList / TestStepList.
|
|
6
|
+
*/
|
|
7
|
+
export interface Page<T> {
|
|
8
|
+
items: T[];
|
|
9
|
+
nextToken: string | null;
|
|
10
|
+
}
|
|
11
|
+
export interface PaginationFlags {
|
|
12
|
+
/** Service page-size hint. Per OpenAPI: 1–100, default 25. */
|
|
13
|
+
pageSize?: number;
|
|
14
|
+
/** Opaque cursor from a previous response. */
|
|
15
|
+
startingToken?: string;
|
|
16
|
+
/** Client-side cap on total items returned across pages. */
|
|
17
|
+
maxItems?: number;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Validates and normalizes pagination flags. Per the CLI OpenAPI spec
|
|
21
|
+
* §components.parameters.PageSize the hard cap is 100. Values above the
|
|
22
|
+
* cap are now rejected with exit 5 rather than silently clamped, giving
|
|
23
|
+
* callers fast feedback that their flag value is out of range. Sub-1 /
|
|
24
|
+
* NaN values also throw. `maxItems` is validated but not capped (it is a
|
|
25
|
+
* client-side cursor, not a server parameter).
|
|
26
|
+
*
|
|
27
|
+
* NOTE: `runResultHistory` previously did its own silent clamp via
|
|
28
|
+
* `Math.min(Math.max(1, n), 100)` — that was unified to this path by the
|
|
29
|
+
* same fix wave (B-E2E-01 fix 7).
|
|
30
|
+
*/
|
|
31
|
+
export declare function validatePaginationFlags(flags: PaginationFlags): PaginationFlags;
|
|
32
|
+
export interface FetchPageArgs {
|
|
33
|
+
pageSize: number;
|
|
34
|
+
cursor: string | undefined;
|
|
35
|
+
}
|
|
36
|
+
export type FetchPage<T> = (args: FetchPageArgs) => Promise<Page<T>>;
|
|
37
|
+
/**
|
|
38
|
+
* Calls `fetchPage` repeatedly, honoring `--max-items` and
|
|
39
|
+
* `--starting-token`. Behavior matches AWS CLI auto-paging:
|
|
40
|
+
*
|
|
41
|
+
* - If neither `pageSize` nor `maxItems` is set, follows pages until
|
|
42
|
+
* `nextToken` is null. Default service page size (25) is used.
|
|
43
|
+
* - If `pageSize` is set, uses it as the per-call hint.
|
|
44
|
+
* - If `maxItems` is set, stops once the total exceeds it.
|
|
45
|
+
* - The returned `nextToken` is whatever the server said on the
|
|
46
|
+
* last page consumed — not necessarily `null`. Callers that paged
|
|
47
|
+
* out via `--max-items` see a non-null token they can pass back
|
|
48
|
+
* in `--starting-token` to resume.
|
|
49
|
+
*/
|
|
50
|
+
export declare function paginate<T>(fetchPage: FetchPage<T>, flags?: PaginationFlags): Promise<Page<T>>;
|
|
51
|
+
/**
|
|
52
|
+
* Drop-in helper for commands that take a single page and surface
|
|
53
|
+
* the cursor verbatim (no auto-follow). Used when the caller passed
|
|
54
|
+
* an explicit `--page-size` and didn't ask for `--max-items`.
|
|
55
|
+
*/
|
|
56
|
+
export declare function fetchSinglePage<T>(client: HttpClient, path: string, pageSize: number, cursor: string | undefined, extraQuery?: Record<string, string | number | boolean | undefined>): Promise<Page<T>>;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { localValidationError } from './errors.js';
|
|
2
|
+
const HARD_PAGE_SIZE_CAP = 100;
|
|
3
|
+
const DEFAULT_PAGE_SIZE = 25;
|
|
4
|
+
/**
|
|
5
|
+
* Validates and normalizes pagination flags. Per the CLI OpenAPI spec
|
|
6
|
+
* §components.parameters.PageSize the hard cap is 100. Values above the
|
|
7
|
+
* cap are now rejected with exit 5 rather than silently clamped, giving
|
|
8
|
+
* callers fast feedback that their flag value is out of range. Sub-1 /
|
|
9
|
+
* NaN values also throw. `maxItems` is validated but not capped (it is a
|
|
10
|
+
* client-side cursor, not a server parameter).
|
|
11
|
+
*
|
|
12
|
+
* NOTE: `runResultHistory` previously did its own silent clamp via
|
|
13
|
+
* `Math.min(Math.max(1, n), 100)` — that was unified to this path by the
|
|
14
|
+
* same fix wave (B-E2E-01 fix 7).
|
|
15
|
+
*/
|
|
16
|
+
export function validatePaginationFlags(flags) {
|
|
17
|
+
const out = { ...flags };
|
|
18
|
+
if (out.pageSize !== undefined) {
|
|
19
|
+
if (!Number.isFinite(out.pageSize) || out.pageSize < 1) {
|
|
20
|
+
throw localValidationError('page-size', `must be a positive integer between 1 and ${HARD_PAGE_SIZE_CAP}`);
|
|
21
|
+
}
|
|
22
|
+
if (out.pageSize > HARD_PAGE_SIZE_CAP) {
|
|
23
|
+
throw localValidationError('page-size', `must be between 1 and ${HARD_PAGE_SIZE_CAP} (got ${out.pageSize})`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (out.maxItems !== undefined) {
|
|
27
|
+
if (!Number.isFinite(out.maxItems) || out.maxItems < 1) {
|
|
28
|
+
throw localValidationError('maxItems', 'must be a positive integer');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Calls `fetchPage` repeatedly, honoring `--max-items` and
|
|
35
|
+
* `--starting-token`. Behavior matches AWS CLI auto-paging:
|
|
36
|
+
*
|
|
37
|
+
* - If neither `pageSize` nor `maxItems` is set, follows pages until
|
|
38
|
+
* `nextToken` is null. Default service page size (25) is used.
|
|
39
|
+
* - If `pageSize` is set, uses it as the per-call hint.
|
|
40
|
+
* - If `maxItems` is set, stops once the total exceeds it.
|
|
41
|
+
* - The returned `nextToken` is whatever the server said on the
|
|
42
|
+
* last page consumed — not necessarily `null`. Callers that paged
|
|
43
|
+
* out via `--max-items` see a non-null token they can pass back
|
|
44
|
+
* in `--starting-token` to resume.
|
|
45
|
+
*/
|
|
46
|
+
export async function paginate(fetchPage, flags = {}) {
|
|
47
|
+
validatePaginationFlags(flags);
|
|
48
|
+
const pageSize = flags.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
49
|
+
const maxItems = flags.maxItems;
|
|
50
|
+
const items = [];
|
|
51
|
+
let cursor = flags.startingToken;
|
|
52
|
+
let lastNextToken = null;
|
|
53
|
+
while (true) {
|
|
54
|
+
const remaining = maxItems !== undefined ? maxItems - items.length : Infinity;
|
|
55
|
+
if (remaining <= 0)
|
|
56
|
+
break;
|
|
57
|
+
const callPageSize = Number.isFinite(remaining) ? Math.min(pageSize, remaining) : pageSize;
|
|
58
|
+
const page = await fetchPage({ pageSize: callPageSize, cursor });
|
|
59
|
+
lastNextToken = page.nextToken;
|
|
60
|
+
for (const item of page.items) {
|
|
61
|
+
if (maxItems !== undefined && items.length >= maxItems)
|
|
62
|
+
break;
|
|
63
|
+
items.push(item);
|
|
64
|
+
}
|
|
65
|
+
if (page.nextToken === null)
|
|
66
|
+
break;
|
|
67
|
+
cursor = page.nextToken;
|
|
68
|
+
}
|
|
69
|
+
return { items, nextToken: lastNextToken };
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Drop-in helper for commands that take a single page and surface
|
|
73
|
+
* the cursor verbatim (no auto-follow). Used when the caller passed
|
|
74
|
+
* an explicit `--page-size` and didn't ask for `--max-items`.
|
|
75
|
+
*/
|
|
76
|
+
export async function fetchSinglePage(client, path, pageSize, cursor, extraQuery = {}) {
|
|
77
|
+
return client.get(path, {
|
|
78
|
+
query: { ...extraQuery, pageSize, cursor },
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=pagination.js.map
|
|
@@ -0,0 +1,88 @@
|
|
|
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 { RunResponse } from './runs.types.js';
|
|
24
|
+
/**
|
|
25
|
+
* Minimal interface that `pollRunUntilTerminal` requires from the HTTP client.
|
|
26
|
+
* Using a structural interface (rather than the concrete `HttpClient`) makes
|
|
27
|
+
* it easy to supply a lightweight mock in tests without implementing the full
|
|
28
|
+
* class.
|
|
29
|
+
*/
|
|
30
|
+
export interface RunClient {
|
|
31
|
+
getRun(runId: string, options?: {
|
|
32
|
+
waitSeconds?: number;
|
|
33
|
+
signal?: AbortSignal;
|
|
34
|
+
}): Promise<RunResponse>;
|
|
35
|
+
}
|
|
36
|
+
/** Thrown when the polling deadline is hit. */
|
|
37
|
+
export declare class TimeoutError extends Error {
|
|
38
|
+
readonly runId: string;
|
|
39
|
+
constructor(runId: string, timeoutSeconds: number);
|
|
40
|
+
}
|
|
41
|
+
export interface PollOptions {
|
|
42
|
+
/** Maximum number of seconds to wait for a terminal status. */
|
|
43
|
+
timeoutSeconds: number;
|
|
44
|
+
/** Called after every successful GET poll (terminal or not). */
|
|
45
|
+
onTick?: (run: RunResponse, elapsedMs: number) => void;
|
|
46
|
+
/**
|
|
47
|
+
* Optional callback for user-relevant state transitions during polling.
|
|
48
|
+
* Emits messages for polling-mode switches and "not yet visible" retries
|
|
49
|
+
* without the full debug firehose. Wired to stderr at `--verbose` level.
|
|
50
|
+
*/
|
|
51
|
+
onTransition?: (msg: string) => void;
|
|
52
|
+
/**
|
|
53
|
+
* Injectable sleep function. Defaults to `setTimeout`-based sleep.
|
|
54
|
+
* Inject a mock in tests to avoid real delays.
|
|
55
|
+
*/
|
|
56
|
+
sleep?: (ms: number) => Promise<void>;
|
|
57
|
+
/**
|
|
58
|
+
* Optional escape hatch invoked after every **non-terminal** run tick.
|
|
59
|
+
* Lets the caller resolve a terminal `RunResponse` from an alternate
|
|
60
|
+
* source when the run-surface row itself will never finalize.
|
|
61
|
+
*
|
|
62
|
+
* The motivating case (dogfood L1888): backend-test run rows are written
|
|
63
|
+
* `queued` then orphaned server-side (`finalizeRun` is FE-only), so the
|
|
64
|
+
* run-row poll would always hit `--timeout` → exit 7 even on a passing BE
|
|
65
|
+
* test. The handler supplies a fallback that reads the testId-scoped
|
|
66
|
+
* verdict (`GET /tests/{id}/result`) and returns a synthesized terminal
|
|
67
|
+
* `RunResponse` once the test record reports terminal.
|
|
68
|
+
*
|
|
69
|
+
* Return a terminal `RunResponse` to finish the poll, or `null`/`undefined`
|
|
70
|
+
* to keep polling the run row. Only ever called on non-terminal ticks, so
|
|
71
|
+
* the FE path (where the run row finalizes normally) is unaffected.
|
|
72
|
+
*
|
|
73
|
+
* `signal` aborts at the remaining `--timeout`; thread it through any HTTP
|
|
74
|
+
* the callback makes so a stalled alternate lookup can't overrun the
|
|
75
|
+
* user's deadline (the per-request HTTP timeout is much larger).
|
|
76
|
+
*/
|
|
77
|
+
resolveAlternate?: (run: RunResponse, elapsedMs: number, signal: AbortSignal) => Promise<RunResponse | null>;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Poll `GET /api/cli/v1/runs/{runId}` until the run reaches a terminal
|
|
81
|
+
* status or the deadline is exceeded.
|
|
82
|
+
*
|
|
83
|
+
* @returns The final `RunResponse` when terminal.
|
|
84
|
+
* @throws `TimeoutError` when `timeoutSeconds` elapses before terminal.
|
|
85
|
+
* @throws `ApiError` for `NOT_FOUND` (exit 4), `RATE_LIMITED` (exit 11),
|
|
86
|
+
* and unrecoverable server errors.
|
|
87
|
+
*/
|
|
88
|
+
export declare function pollRunUntilTerminal(client: RunClient, runId: string, options: PollOptions): Promise<RunResponse>;
|
package/dist/lib/poll.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
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 } from './errors.js';
|
|
24
|
+
import { isTerminalStatus } from './runs.types.js';
|
|
25
|
+
/** Thrown when the polling deadline is hit. */
|
|
26
|
+
export class TimeoutError extends Error {
|
|
27
|
+
runId;
|
|
28
|
+
constructor(runId, timeoutSeconds) {
|
|
29
|
+
super(`Timed out after ${timeoutSeconds}s waiting for run ${runId}`);
|
|
30
|
+
this.name = 'TimeoutError';
|
|
31
|
+
this.runId = runId;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const LONG_POLL_WAIT_SECONDS = 25;
|
|
35
|
+
/** Backoff schedule for the non-long-poll fallback path (ms). */
|
|
36
|
+
const BACKOFF_SCHEDULE_MS = [2000, 4000, 8000, 15000];
|
|
37
|
+
/**
|
|
38
|
+
* Poll `GET /api/cli/v1/runs/{runId}` until the run reaches a terminal
|
|
39
|
+
* status or the deadline is exceeded.
|
|
40
|
+
*
|
|
41
|
+
* @returns The final `RunResponse` when terminal.
|
|
42
|
+
* @throws `TimeoutError` when `timeoutSeconds` elapses before terminal.
|
|
43
|
+
* @throws `ApiError` for `NOT_FOUND` (exit 4), `RATE_LIMITED` (exit 11),
|
|
44
|
+
* and unrecoverable server errors.
|
|
45
|
+
*/
|
|
46
|
+
export async function pollRunUntilTerminal(client, runId, options) {
|
|
47
|
+
const { timeoutSeconds, onTick, onTransition, resolveAlternate } = options;
|
|
48
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
49
|
+
const startMs = Date.now();
|
|
50
|
+
const deadlineMs = startMs + timeoutSeconds * 1000;
|
|
51
|
+
// Track whether the server supports ?waitSeconds. Start optimistic.
|
|
52
|
+
let useBackoff = false;
|
|
53
|
+
let backoffIndex = 0;
|
|
54
|
+
let consecutiveErrors = 0;
|
|
55
|
+
// 404 not_yet_visible retry budget (one soft retry per event).
|
|
56
|
+
let notYetVisibleRetries = 0;
|
|
57
|
+
while (true) {
|
|
58
|
+
const now = Date.now();
|
|
59
|
+
if (now >= deadlineMs) {
|
|
60
|
+
throw new TimeoutError(runId, timeoutSeconds);
|
|
61
|
+
}
|
|
62
|
+
const remainingMs = deadlineMs - now;
|
|
63
|
+
const remainingSeconds = Math.ceil(remainingMs / 1000);
|
|
64
|
+
// Mint a per-iteration AbortController. The signal fires at the remaining
|
|
65
|
+
// deadline plus a small transport cushion (2 s) so a hung fetch does not
|
|
66
|
+
// block the CLI past --timeout.
|
|
67
|
+
const TRANSPORT_CUSHION_MS = 2000;
|
|
68
|
+
const abortController = new AbortController();
|
|
69
|
+
const abortTimer = setTimeout(() => {
|
|
70
|
+
abortController.abort();
|
|
71
|
+
}, remainingMs + TRANSPORT_CUSHION_MS);
|
|
72
|
+
let run;
|
|
73
|
+
try {
|
|
74
|
+
if (useBackoff) {
|
|
75
|
+
run = await client.getRun(runId, { signal: abortController.signal });
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
const waitSeconds = Math.min(remainingSeconds, LONG_POLL_WAIT_SECONDS);
|
|
79
|
+
run = await client.getRun(runId, { waitSeconds, signal: abortController.signal });
|
|
80
|
+
}
|
|
81
|
+
// Successful GET resets the consecutive-error counter.
|
|
82
|
+
consecutiveErrors = 0;
|
|
83
|
+
notYetVisibleRetries = 0;
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
clearTimeout(abortTimer);
|
|
87
|
+
// An AbortError from our per-iteration controller means the deadline
|
|
88
|
+
// passed while the fetch was in flight — surface as TimeoutError.
|
|
89
|
+
if (isAbortError(err)) {
|
|
90
|
+
throw new TimeoutError(runId, timeoutSeconds);
|
|
91
|
+
}
|
|
92
|
+
if (!(err instanceof ApiError))
|
|
93
|
+
throw err;
|
|
94
|
+
// 400 VALIDATION_ERROR on waitSeconds → fall back to backoff.
|
|
95
|
+
if (err.code === 'VALIDATION_ERROR' && !useBackoff) {
|
|
96
|
+
useBackoff = true;
|
|
97
|
+
onTransition?.(`Server does not support long-poll (?waitSeconds) — switching to exponential backoff mode`);
|
|
98
|
+
// Retry immediately (no sleep) on the first switch.
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
// 404 not_yet_visible → retry once after 1s (clamped to remaining deadline).
|
|
102
|
+
if (err.code === 'NOT_FOUND' &&
|
|
103
|
+
err.getDetail('reason') === 'not_yet_visible' &&
|
|
104
|
+
notYetVisibleRetries === 0) {
|
|
105
|
+
notYetVisibleRetries += 1;
|
|
106
|
+
onTransition?.(`Server reports run ${runId} not yet visible — retrying in 1s`);
|
|
107
|
+
const remaining = deadlineMs - Date.now();
|
|
108
|
+
await sleep(Math.min(1000, Math.max(0, remaining)));
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
// 404 not_found (cross-tenant or stale runId) → exit immediately.
|
|
112
|
+
if (err.code === 'NOT_FOUND') {
|
|
113
|
+
throw err;
|
|
114
|
+
}
|
|
115
|
+
// RATE_LIMITED (429) — honor Retry-After; max 3 retries total from
|
|
116
|
+
// the http.ts retry table, but we also want to track here so if
|
|
117
|
+
// http.ts already exhausted retries and re-throws, we propagate.
|
|
118
|
+
if (err.code === 'RATE_LIMITED') {
|
|
119
|
+
throw err; // http.ts already honored Retry-After + capped at 3.
|
|
120
|
+
}
|
|
121
|
+
// 5xx (INTERNAL / UNAVAILABLE) — single retry.
|
|
122
|
+
if (err.code === 'INTERNAL' || err.code === 'UNAVAILABLE') {
|
|
123
|
+
consecutiveErrors += 1;
|
|
124
|
+
if (consecutiveErrors >= 2)
|
|
125
|
+
throw err; // second error propagates.
|
|
126
|
+
// http.ts already applied one retry for INTERNAL/UNAVAILABLE;
|
|
127
|
+
// if we reach here it means http.ts gave up. We absorb one
|
|
128
|
+
// additional attempt at the polling layer.
|
|
129
|
+
const retryAfterSec = err.getDetail('retryAfterSec', (v) => typeof v === 'number');
|
|
130
|
+
const backoffMs = retryAfterSec !== undefined ? retryAfterSec * 1000 : 1000;
|
|
131
|
+
const remaining = deadlineMs - Date.now();
|
|
132
|
+
await sleep(Math.min(backoffMs, Math.max(0, remaining)));
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
// Everything else propagates.
|
|
136
|
+
throw err;
|
|
137
|
+
}
|
|
138
|
+
// fetch completed — cancel the per-iteration abort timer.
|
|
139
|
+
clearTimeout(abortTimer);
|
|
140
|
+
const elapsedMs = Date.now() - startMs;
|
|
141
|
+
onTick?.(run, elapsedMs);
|
|
142
|
+
if (isTerminalStatus(run.status)) {
|
|
143
|
+
return run;
|
|
144
|
+
}
|
|
145
|
+
// Non-terminal run tick. Give the caller a chance to resolve a terminal
|
|
146
|
+
// verdict from an alternate source (e.g. the backend testId-scoped
|
|
147
|
+
// result when the run-surface row never finalizes — dogfood L1888).
|
|
148
|
+
if (resolveAlternate) {
|
|
149
|
+
// Bound the alternate lookup by the REMAINING --timeout (not the much
|
|
150
|
+
// larger per-request HTTP timeout) so a stalled fallback read can't
|
|
151
|
+
// overrun the user's deadline (codex round-2).
|
|
152
|
+
const altRemainingMs = deadlineMs - Date.now();
|
|
153
|
+
if (altRemainingMs <= 0) {
|
|
154
|
+
throw new TimeoutError(runId, timeoutSeconds);
|
|
155
|
+
}
|
|
156
|
+
const altAbort = new AbortController();
|
|
157
|
+
const altTimer = setTimeout(() => altAbort.abort(), altRemainingMs);
|
|
158
|
+
let alternate = null;
|
|
159
|
+
try {
|
|
160
|
+
alternate = await resolveAlternate(run, elapsedMs, altAbort.signal);
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
clearTimeout(altTimer);
|
|
164
|
+
}
|
|
165
|
+
// Enforce the hard cap: reject a terminal alternate that only arrived
|
|
166
|
+
// at/after the deadline, same as the run-row long-poll path below.
|
|
167
|
+
if (Date.now() >= deadlineMs) {
|
|
168
|
+
throw new TimeoutError(runId, timeoutSeconds);
|
|
169
|
+
}
|
|
170
|
+
if (alternate) {
|
|
171
|
+
return alternate;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
// Honor server-supplied retryAfterSeconds when present.
|
|
175
|
+
// Clamp to remaining deadline so --timeout is a hard cap even when the
|
|
176
|
+
// server hint is larger than the time left.
|
|
177
|
+
if (run.retryAfterSeconds !== undefined && run.retryAfterSeconds > 0) {
|
|
178
|
+
const remaining = deadlineMs - Date.now();
|
|
179
|
+
await sleep(Math.min(run.retryAfterSeconds * 1000, Math.max(0, remaining)));
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
// Long-poll path: server already waited up to waitSeconds for us;
|
|
183
|
+
// loop immediately (no extra client-side sleep).
|
|
184
|
+
if (!useBackoff) {
|
|
185
|
+
// Check deadline before looping.
|
|
186
|
+
if (Date.now() >= deadlineMs) {
|
|
187
|
+
throw new TimeoutError(runId, timeoutSeconds);
|
|
188
|
+
}
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
// Backoff fallback path. Clamp to remaining deadline so --timeout is a
|
|
192
|
+
// hard cap even when the schedule delay exceeds the time left.
|
|
193
|
+
const rawDelay = backoffScheduleDelay(backoffIndex);
|
|
194
|
+
backoffIndex = Math.min(backoffIndex + 1, BACKOFF_SCHEDULE_MS.length - 1);
|
|
195
|
+
const remaining = deadlineMs - Date.now();
|
|
196
|
+
await sleep(Math.min(rawDelay, Math.max(0, remaining)));
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
/** Returns a jittered delay from the backoff schedule (±20%). */
|
|
200
|
+
function backoffScheduleDelay(index) {
|
|
201
|
+
const base = BACKOFF_SCHEDULE_MS[Math.min(index, BACKOFF_SCHEDULE_MS.length - 1)];
|
|
202
|
+
const jitter = base * 0.2 * (Math.random() * 2 - 1); // ±20%
|
|
203
|
+
return Math.max(0, Math.round(base + jitter));
|
|
204
|
+
}
|
|
205
|
+
function defaultSleep(ms) {
|
|
206
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Detects an AbortError thrown when an AbortSignal fires.
|
|
210
|
+
* Works for native fetch AbortErrors as well as `AbortController.abort()`
|
|
211
|
+
* from Node 18+ stdlib (both set `name === 'AbortError'`).
|
|
212
|
+
*/
|
|
213
|
+
function isAbortError(err) {
|
|
214
|
+
if (err instanceof Error && err.name === 'AbortError')
|
|
215
|
+
return true;
|
|
216
|
+
if (typeof err === 'object' && err !== null && 'name' in err) {
|
|
217
|
+
return err.name === 'AbortError';
|
|
218
|
+
}
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
221
|
+
//# sourceMappingURL=poll.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Writable } from 'node:stream';
|
|
2
|
+
export interface PromptStreams {
|
|
3
|
+
input?: NodeJS.ReadableStream;
|
|
4
|
+
output?: NodeJS.WritableStream;
|
|
5
|
+
}
|
|
6
|
+
export declare function promptText(question: string, streams?: PromptStreams): Promise<string>;
|
|
7
|
+
export declare function promptSecret(question: string, streams?: PromptStreams): Promise<string>;
|
|
8
|
+
export type { Writable };
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
export async function promptText(question, streams = {}) {
|
|
2
|
+
const input = streams.input ?? process.stdin;
|
|
3
|
+
const output = streams.output ?? process.stdout;
|
|
4
|
+
output.write(question);
|
|
5
|
+
return readLine(input, output, false);
|
|
6
|
+
}
|
|
7
|
+
export async function promptSecret(question, streams = {}) {
|
|
8
|
+
const input = streams.input ?? process.stdin;
|
|
9
|
+
const output = streams.output ?? process.stdout;
|
|
10
|
+
output.write(question);
|
|
11
|
+
const inputAsTTY = input;
|
|
12
|
+
const useRawMode = inputAsTTY.isTTY === true && typeof inputAsTTY.setRawMode === 'function';
|
|
13
|
+
if (useRawMode)
|
|
14
|
+
inputAsTTY.setRawMode(true);
|
|
15
|
+
try {
|
|
16
|
+
return await readLine(input, output, useRawMode);
|
|
17
|
+
}
|
|
18
|
+
finally {
|
|
19
|
+
if (useRawMode)
|
|
20
|
+
inputAsTTY.setRawMode(false);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function readLine(input, output, mask) {
|
|
24
|
+
return new Promise((resolve, reject) => {
|
|
25
|
+
let buffer = '';
|
|
26
|
+
let resolved = false;
|
|
27
|
+
const onData = (chunk) => {
|
|
28
|
+
const str = typeof chunk === 'string' ? chunk : chunk.toString('utf-8');
|
|
29
|
+
for (const ch of str) {
|
|
30
|
+
const code = ch.charCodeAt(0);
|
|
31
|
+
// Enter (CR or LF)
|
|
32
|
+
if (code === 13 || code === 10) {
|
|
33
|
+
finish();
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
// Ctrl-C
|
|
37
|
+
if (code === 3) {
|
|
38
|
+
cleanup();
|
|
39
|
+
output.write('\n');
|
|
40
|
+
if (!resolved) {
|
|
41
|
+
resolved = true;
|
|
42
|
+
reject(new Error('Prompt cancelled.'));
|
|
43
|
+
}
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
// Backspace / DEL
|
|
47
|
+
if (code === 127 || code === 8) {
|
|
48
|
+
if (buffer.length > 0) {
|
|
49
|
+
buffer = buffer.slice(0, -1);
|
|
50
|
+
if (mask)
|
|
51
|
+
output.write('\b \b');
|
|
52
|
+
}
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
// Drop other control chars
|
|
56
|
+
if (code < 32)
|
|
57
|
+
continue;
|
|
58
|
+
buffer += ch;
|
|
59
|
+
if (mask)
|
|
60
|
+
output.write('*');
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const onEnd = () => {
|
|
64
|
+
finish();
|
|
65
|
+
};
|
|
66
|
+
const onError = (err) => {
|
|
67
|
+
cleanup();
|
|
68
|
+
if (!resolved) {
|
|
69
|
+
resolved = true;
|
|
70
|
+
reject(err);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
const cleanup = () => {
|
|
74
|
+
input.off('data', onData);
|
|
75
|
+
input.off('end', onEnd);
|
|
76
|
+
input.off('error', onError);
|
|
77
|
+
const pausable = input;
|
|
78
|
+
if (typeof pausable.pause === 'function')
|
|
79
|
+
pausable.pause();
|
|
80
|
+
};
|
|
81
|
+
const finish = () => {
|
|
82
|
+
cleanup();
|
|
83
|
+
output.write('\n');
|
|
84
|
+
if (!resolved) {
|
|
85
|
+
resolved = true;
|
|
86
|
+
resolve(buffer);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
input.on('data', onData);
|
|
90
|
+
input.on('end', onEnd);
|
|
91
|
+
input.on('error', onError);
|
|
92
|
+
const resumable = input;
|
|
93
|
+
if (typeof resumable.resume === 'function')
|
|
94
|
+
resumable.resume();
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=prompt.js.map
|
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
}
|