@testsprite/testsprite-cli 0.3.0 → 0.5.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/README.md +55 -29
- package/dist/commands/agent.js +17 -6
- package/dist/commands/auth.d.ts +51 -0
- package/dist/commands/auth.js +46 -2
- package/dist/commands/completion.d.ts +36 -0
- package/dist/commands/completion.js +111 -0
- package/dist/commands/doctor.js +56 -16
- package/dist/commands/init.d.ts +32 -1
- package/dist/commands/init.js +40 -10
- package/dist/commands/project.d.ts +102 -4
- package/dist/commands/project.js +250 -47
- package/dist/commands/test.d.ts +253 -11
- package/dist/commands/test.js +1822 -390
- package/dist/commands/usage.d.ts +56 -17
- package/dist/commands/usage.js +144 -29
- package/dist/index.js +172 -29
- package/dist/lib/browser.d.ts +6 -0
- package/dist/lib/browser.js +54 -0
- package/dist/lib/bundle.d.ts +32 -31
- package/dist/lib/bundle.js +144 -84
- package/dist/lib/client-factory.d.ts +29 -0
- package/dist/lib/client-factory.js +49 -1
- package/dist/lib/config.js +7 -3
- package/dist/lib/credentials.d.ts +17 -1
- package/dist/lib/credentials.js +175 -16
- package/dist/lib/dry-run/samples.js +51 -1
- package/dist/lib/errors.d.ts +33 -1
- package/dist/lib/errors.js +110 -19
- package/dist/lib/failing-fe-resolver.d.ts +15 -0
- package/dist/lib/failing-fe-resolver.js +49 -1
- package/dist/lib/flaky.d.ts +12 -1
- package/dist/lib/flaky.js +7 -12
- package/dist/lib/gh-output.d.ts +62 -0
- package/dist/lib/gh-output.js +99 -0
- package/dist/lib/http.d.ts +86 -16
- package/dist/lib/http.js +181 -11
- package/dist/lib/interrupt.d.ts +65 -10
- package/dist/lib/interrupt.js +94 -9
- package/dist/lib/org-render.d.ts +52 -0
- package/dist/lib/org-render.js +59 -0
- package/dist/lib/poll.d.ts +11 -0
- package/dist/lib/poll.js +71 -6
- package/dist/lib/render-error.d.ts +14 -0
- package/dist/lib/render-error.js +30 -0
- package/dist/lib/response-schemas.d.ts +83 -0
- package/dist/lib/response-schemas.js +272 -0
- package/dist/lib/runs.types.d.ts +62 -8
- package/dist/lib/skill-nudge.d.ts +17 -0
- package/dist/lib/skill-nudge.js +19 -0
- package/dist/lib/telemetry.d.ts +90 -0
- package/dist/lib/telemetry.js +171 -0
- package/dist/lib/text-table.d.ts +14 -0
- package/dist/lib/text-table.js +45 -0
- package/dist/lib/v3-advisory.d.ts +22 -0
- package/dist/lib/v3-advisory.js +32 -0
- package/dist/lib/version-notice.d.ts +37 -0
- package/dist/lib/version-notice.js +87 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +16 -5
- package/schemas/plan.schema.json +61 -0
- package/skills/testsprite-verify.codex.md +8 -2
- package/skills/testsprite-verify.skill.md +18 -7
package/dist/lib/http.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import
|
|
2
|
+
import * as v from 'valibot';
|
|
3
|
+
import { ApiError, InterruptError, RequestTimeoutError, TransportError } from './errors.js';
|
|
3
4
|
import { VERSION } from '../version.js';
|
|
5
|
+
import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, } from './response-schemas.js';
|
|
4
6
|
/**
|
|
5
7
|
* Default per-request timeout (120s). Comfortably covers every metadata/read
|
|
6
8
|
* request and every <=25s long-poll request (`?waitSeconds` is capped at 25
|
|
@@ -39,6 +41,10 @@ const MAX_ATTEMPTS_INTERNAL = 2;
|
|
|
39
41
|
const MAX_RATE_LIMITED_DELAY_MS = 60_000;
|
|
40
42
|
const CONFLICT_DELAY_MS = 1000;
|
|
41
43
|
const INTERNAL_DELAY_MS = 500;
|
|
44
|
+
// Cap on how many valibot issues a shape-mismatch INTERNAL envelope carries in
|
|
45
|
+
// `details.issues` (path + message each). Keeps the envelope readable and
|
|
46
|
+
// guarantees the response body itself is never echoed back to the operator.
|
|
47
|
+
const MAX_SCHEMA_ISSUES_IN_DETAILS = 3;
|
|
42
48
|
export class HttpClient {
|
|
43
49
|
baseUrl;
|
|
44
50
|
apiKey;
|
|
@@ -47,17 +53,41 @@ export class HttpClient {
|
|
|
47
53
|
random;
|
|
48
54
|
onDebug;
|
|
49
55
|
onTransition;
|
|
56
|
+
onServerVersion;
|
|
50
57
|
requestTimeoutMs;
|
|
58
|
+
shutdownSignal;
|
|
51
59
|
constructor(options) {
|
|
52
60
|
this.baseUrl = trimTrailingSlash(options.baseUrl);
|
|
53
61
|
this.apiKey = options.apiKey;
|
|
62
|
+
this.shutdownSignal = options.shutdownSignal;
|
|
54
63
|
this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
55
64
|
this.sleep = options.sleep ?? defaultSleep;
|
|
56
65
|
this.random = options.random ?? Math.random;
|
|
57
66
|
this.onDebug = options.onDebug;
|
|
58
67
|
this.onTransition = options.onTransition;
|
|
68
|
+
this.onServerVersion = options.onServerVersion;
|
|
59
69
|
this.requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_DEFAULT_MS;
|
|
60
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Read the backend's supported-floor header off a response and forward it to
|
|
73
|
+
* `onServerVersion` when present. Never throws — a bad header must not break
|
|
74
|
+
* the request. Called on every response (success or error) so the advisory
|
|
75
|
+
* covers all paths. (The backend advertises only the floor; "latest" is
|
|
76
|
+
* resolved client-side via the npm update-notice.)
|
|
77
|
+
*/
|
|
78
|
+
captureServerVersion(response) {
|
|
79
|
+
if (!this.onServerVersion)
|
|
80
|
+
return;
|
|
81
|
+
try {
|
|
82
|
+
const minVersion = response.headers.get('x-testsprite-cli-min-version') ?? undefined;
|
|
83
|
+
if (minVersion !== undefined) {
|
|
84
|
+
this.onServerVersion({ minVersion });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
// Header parsing is best-effort; never let it affect the request.
|
|
89
|
+
}
|
|
90
|
+
}
|
|
61
91
|
async get(path, options = {}) {
|
|
62
92
|
return this.requestWithMeta('GET', path, options).then(r => r.body);
|
|
63
93
|
}
|
|
@@ -104,6 +134,7 @@ export class HttpClient {
|
|
|
104
134
|
body,
|
|
105
135
|
headers: { 'idempotency-key': options.idempotencyKey },
|
|
106
136
|
signal: options.signal,
|
|
137
|
+
schema: TRIGGER_RUN_RESPONSE_SCHEMA,
|
|
107
138
|
// 409 on POST /runs means "another run is already in flight" — a
|
|
108
139
|
// persistent condition, not a transient snapshot conflict. Retrying
|
|
109
140
|
// would enqueue a second run once the first finishes.
|
|
@@ -127,6 +158,7 @@ export class HttpClient {
|
|
|
127
158
|
body,
|
|
128
159
|
headers: { 'idempotency-key': options.idempotencyKey },
|
|
129
160
|
signal: options.signal,
|
|
161
|
+
schema: TRIGGER_RUN_RESPONSE_SCHEMA,
|
|
130
162
|
retryOnConflict: false,
|
|
131
163
|
// Default true: single `test run` / `test create --run` retain 429 retry.
|
|
132
164
|
// Batch call site passes false to keep outer-loop as sole rate-limit owner.
|
|
@@ -135,8 +167,9 @@ export class HttpClient {
|
|
|
135
167
|
}
|
|
136
168
|
/**
|
|
137
169
|
* POST /api/cli/v1/tests/{testId}/runs/rerun
|
|
138
|
-
* Trigger a rerun (replay) for a single test. FE: verbatim script replay
|
|
139
|
-
*
|
|
170
|
+
* Trigger a rerun (replay) for a single test. FE: verbatim script replay, billed at
|
|
171
|
+
* 0.5 credits (same as a fresh run; legacy V2 accounts: free). BE: dependency-closure
|
|
172
|
+
* re-run, billed at 0.2 credits. Returns `runId` + optional `closure` (BE).
|
|
140
173
|
*
|
|
141
174
|
* `retryOnConflict: false` — 409 on rerun means the test is already in-flight,
|
|
142
175
|
* a persistent condition. Retrying would race against the running test.
|
|
@@ -146,6 +179,7 @@ export class HttpClient {
|
|
|
146
179
|
body,
|
|
147
180
|
headers: { 'idempotency-key': options.idempotencyKey },
|
|
148
181
|
signal: options.signal,
|
|
182
|
+
schema: RERUN_RESPONSE_SCHEMA,
|
|
149
183
|
retryOnConflict: false,
|
|
150
184
|
}).then(r => r.body);
|
|
151
185
|
}
|
|
@@ -161,6 +195,7 @@ export class HttpClient {
|
|
|
161
195
|
body,
|
|
162
196
|
headers: { 'idempotency-key': options.idempotencyKey },
|
|
163
197
|
signal: options.signal,
|
|
198
|
+
schema: BATCH_RERUN_RESPONSE_SCHEMA,
|
|
164
199
|
retryOnConflict: false,
|
|
165
200
|
}).then(r => r.body);
|
|
166
201
|
}
|
|
@@ -177,6 +212,7 @@ export class HttpClient {
|
|
|
177
212
|
body,
|
|
178
213
|
headers: { 'idempotency-key': options.idempotencyKey },
|
|
179
214
|
signal: options.signal,
|
|
215
|
+
schema: BATCH_RUN_FRESH_RESPONSE_SCHEMA,
|
|
180
216
|
retryOnConflict: false,
|
|
181
217
|
}).then(r => r.body);
|
|
182
218
|
}
|
|
@@ -198,7 +234,10 @@ export class HttpClient {
|
|
|
198
234
|
q.source = query.source;
|
|
199
235
|
if (query.since !== undefined)
|
|
200
236
|
q.since = query.since;
|
|
201
|
-
return this.get(`/tests/${encodeURIComponent(testId)}/runs`, {
|
|
237
|
+
return this.get(`/tests/${encodeURIComponent(testId)}/runs`, {
|
|
238
|
+
query: q,
|
|
239
|
+
schema: LIST_RUNS_RESPONSE_SCHEMA,
|
|
240
|
+
});
|
|
202
241
|
}
|
|
203
242
|
/**
|
|
204
243
|
* GET /api/cli/v1/runs/{runId}
|
|
@@ -224,6 +263,24 @@ export class HttpClient {
|
|
|
224
263
|
return this.get(`/runs/${encodeURIComponent(runId)}`, {
|
|
225
264
|
query: Object.keys(query).length > 0 ? query : undefined,
|
|
226
265
|
signal: options?.signal,
|
|
266
|
+
schema: RUN_RESPONSE_SCHEMA,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* POST /api/cli/v1/runs/{runId}/cancel
|
|
271
|
+
* User-initiated cancel of a queued/running run (DEV-331 piece 3). No
|
|
272
|
+
* body, no `Idempotency-Key` — the endpoint is naturally idempotent (D10):
|
|
273
|
+
* re-cancel → 200 `alreadyCancelled: true`; already-terminal (passed/
|
|
274
|
+
* failed/blocked) → 409 CONFLICT; unknown/cross-tenant runId → 404.
|
|
275
|
+
*
|
|
276
|
+
* `retryOnConflict: false` — same rationale as `triggerRun`: a 409 here is
|
|
277
|
+
* a truthful terminal answer ("already finished"), not a transient
|
|
278
|
+
* snapshot conflict to paper over with a retry.
|
|
279
|
+
*/
|
|
280
|
+
async cancelRun(runId, options) {
|
|
281
|
+
return this.post(`/runs/${encodeURIComponent(runId)}/cancel`, {
|
|
282
|
+
signal: options?.signal,
|
|
283
|
+
retryOnConflict: false,
|
|
227
284
|
});
|
|
228
285
|
}
|
|
229
286
|
/**
|
|
@@ -235,6 +292,14 @@ export class HttpClient {
|
|
|
235
292
|
* continue its own error handling (transport retry / envelope parse).
|
|
236
293
|
*/
|
|
237
294
|
rethrowIfAbort(err, timeoutSignal, callerSignal, requestId, effectiveSignal = timeoutSignal) {
|
|
295
|
+
// A user interrupt (DEV-331) outranks every other classification: once the
|
|
296
|
+
// shutdown signal fired, whatever error surfaced from the aborted fetch or
|
|
297
|
+
// body read is the interrupt. Throw its InterruptError reason so the wait
|
|
298
|
+
// paths can render the honest detach UX — never a RequestTimeoutError, and
|
|
299
|
+
// never fall through to the transport retry loop.
|
|
300
|
+
if (this.shutdownSignal?.aborted) {
|
|
301
|
+
throw this.shutdownSignal.reason;
|
|
302
|
+
}
|
|
238
303
|
if (isAbortError(err) || isTimeoutError(err)) {
|
|
239
304
|
const timeoutWon = timeoutSignal.aborted &&
|
|
240
305
|
(callerSignal == null ||
|
|
@@ -251,8 +316,14 @@ export class HttpClient {
|
|
|
251
316
|
throw ApiError.authRequired();
|
|
252
317
|
const url = buildUrl(this.baseUrl, path, options.query);
|
|
253
318
|
const requestId = options.requestId ?? newRequestId();
|
|
319
|
+
const allowTransportRetry = canRetryTransport(method, options);
|
|
254
320
|
let attempt = 0;
|
|
255
321
|
while (true) {
|
|
322
|
+
// Bail before issuing (or re-issuing after a retry sleep) a request the
|
|
323
|
+
// user has already interrupted; the composed signal below would abort it
|
|
324
|
+
// immediately anyway, this just skips the wasted dispatch.
|
|
325
|
+
if (this.shutdownSignal?.aborted)
|
|
326
|
+
throw this.shutdownSignal.reason;
|
|
256
327
|
attempt += 1;
|
|
257
328
|
this.debug({ kind: 'request', method, url, attempt, requestId });
|
|
258
329
|
const startedAt = Date.now();
|
|
@@ -266,7 +337,15 @@ export class HttpClient {
|
|
|
266
337
|
// long-poll window (<=25s via ?waitSeconds), so it never bites polling.
|
|
267
338
|
const requestTimeout = createRequestTimeout(this.requestTimeoutMs);
|
|
268
339
|
const timeoutSignal = requestTimeout.signal;
|
|
269
|
-
const
|
|
340
|
+
const composedSignals = [timeoutSignal];
|
|
341
|
+
if (options.signal != null)
|
|
342
|
+
composedSignals.push(options.signal);
|
|
343
|
+
// Shutdown composition (DEV-331): an armed SIGINT/SIGTERM aborts the
|
|
344
|
+
// in-flight fetch immediately (reason: InterruptError) instead of
|
|
345
|
+
// letting a long-poll drain its window before the interrupt surfaces.
|
|
346
|
+
if (this.shutdownSignal != null)
|
|
347
|
+
composedSignals.push(this.shutdownSignal);
|
|
348
|
+
const effectiveSignal = composedSignals.length > 1 ? AbortSignal.any(composedSignals) : timeoutSignal;
|
|
270
349
|
try {
|
|
271
350
|
try {
|
|
272
351
|
response = await this.fetchImpl(url, {
|
|
@@ -284,6 +363,14 @@ export class HttpClient {
|
|
|
284
363
|
// A caller-supplied abort sets `name === 'AbortError'`.
|
|
285
364
|
// We treat both abort variants together: if the timeout signal fired and
|
|
286
365
|
// the caller hadn't already aborted, surface a clear RequestTimeoutError.
|
|
366
|
+
// A user interrupt is never retried and never re-wrapped as a
|
|
367
|
+
// TransportError (same passthrough discipline as RequestTimeoutError).
|
|
368
|
+
// The instanceof check matters even without `this.shutdownSignal`:
|
|
369
|
+
// the polling path composes the shutdown signal into its per-
|
|
370
|
+
// iteration caller signal, so the fetch can reject with the
|
|
371
|
+
// InterruptError reason directly (DEV-331).
|
|
372
|
+
if (err instanceof InterruptError)
|
|
373
|
+
throw err;
|
|
287
374
|
// A timeout/abort during the fetch itself: classify it (RequestTimeoutError
|
|
288
375
|
// when our deadline fired; otherwise rethrow the caller's abort unmodified).
|
|
289
376
|
this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
|
|
@@ -302,7 +389,9 @@ export class HttpClient {
|
|
|
302
389
|
errorCode: 'TRANSPORT',
|
|
303
390
|
durationMs: Date.now() - startedAt,
|
|
304
391
|
});
|
|
305
|
-
const decision =
|
|
392
|
+
const decision = allowTransportRetry
|
|
393
|
+
? transportRetryDecision(attempt, this.random)
|
|
394
|
+
: { retry: false, delayMs: 0 };
|
|
306
395
|
if (!decision.retry)
|
|
307
396
|
throw new TransportError(message, requestId);
|
|
308
397
|
this.transition(`Network error on ${shortPath(path)} — retrying in ${Math.round(decision.delayMs / 1000)}s (attempt ${attempt})`);
|
|
@@ -316,10 +405,14 @@ export class HttpClient {
|
|
|
316
405
|
delayMs: decision.delayMs,
|
|
317
406
|
});
|
|
318
407
|
requestTimeout.clear();
|
|
319
|
-
await this.
|
|
408
|
+
await this.sleepBeforeRetry(decision.delayMs);
|
|
320
409
|
continue;
|
|
321
410
|
}
|
|
322
411
|
const durationMs = Date.now() - startedAt;
|
|
412
|
+
// Surface the backend version-compatibility headers on every response
|
|
413
|
+
// (success or error) before branching, so the caller's advisory covers
|
|
414
|
+
// all paths.
|
|
415
|
+
this.captureServerVersion(response);
|
|
323
416
|
if (response.ok) {
|
|
324
417
|
this.debug({
|
|
325
418
|
kind: 'response',
|
|
@@ -330,10 +423,14 @@ export class HttpClient {
|
|
|
330
423
|
requestId,
|
|
331
424
|
durationMs,
|
|
332
425
|
});
|
|
426
|
+
let raw;
|
|
333
427
|
try {
|
|
334
|
-
|
|
428
|
+
raw = await response.json();
|
|
335
429
|
}
|
|
336
430
|
catch (err) {
|
|
431
|
+
// Interrupt passthrough (see the fetch catch above).
|
|
432
|
+
if (err instanceof InterruptError)
|
|
433
|
+
throw err;
|
|
337
434
|
// A timeout/abort can fire mid-body-read (headers received, stream stalls).
|
|
338
435
|
this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
|
|
339
436
|
// Otherwise the successful response body was not valid JSON — a
|
|
@@ -344,12 +441,39 @@ export class HttpClient {
|
|
|
344
441
|
// and break the --output json envelope contract.
|
|
345
442
|
throw malformedResponseError(response, requestId, err);
|
|
346
443
|
}
|
|
444
|
+
if (options.schema !== undefined) {
|
|
445
|
+
const parsed = v.safeParse(options.schema, raw);
|
|
446
|
+
if (!parsed.success) {
|
|
447
|
+
const issues = parsed.issues.slice(0, MAX_SCHEMA_ISSUES_IN_DETAILS).map(issue => ({
|
|
448
|
+
path: v.getDotPath(issue) ?? '(root)',
|
|
449
|
+
message: issue.message,
|
|
450
|
+
}));
|
|
451
|
+
// Shape drift is a server-side contract break: surface a typed
|
|
452
|
+
// INTERNAL envelope (requestId + the first mismatched paths,
|
|
453
|
+
// never the body) instead of letting a blind cast poison
|
|
454
|
+
// downstream output with undefined fields or a raw TypeError.
|
|
455
|
+
throw ApiError.fromEnvelope({
|
|
456
|
+
error: {
|
|
457
|
+
code: 'INTERNAL',
|
|
458
|
+
message: `Response shape mismatch from ${shortPath(path)}.`,
|
|
459
|
+
nextAction: 'Retry; if it persists, report this requestId (the server returned an unexpected shape).',
|
|
460
|
+
requestId,
|
|
461
|
+
details: { issues },
|
|
462
|
+
},
|
|
463
|
+
}, response.status);
|
|
464
|
+
}
|
|
465
|
+
return { body: parsed.output, requestId, status: response.status };
|
|
466
|
+
}
|
|
467
|
+
return { body: raw, requestId, status: response.status };
|
|
347
468
|
}
|
|
348
469
|
let rawBody;
|
|
349
470
|
try {
|
|
350
471
|
rawBody = await safeReadJson(response);
|
|
351
472
|
}
|
|
352
473
|
catch (err) {
|
|
474
|
+
// Interrupt passthrough (see the fetch catch above).
|
|
475
|
+
if (err instanceof InterruptError)
|
|
476
|
+
throw err;
|
|
353
477
|
// safeReadJson rethrows aborts/timeouts (it swallows only non-abort parse
|
|
354
478
|
// errors), so a timeout fired mid-body-read on a non-OK response lands here.
|
|
355
479
|
this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
|
|
@@ -370,7 +494,9 @@ export class HttpClient {
|
|
|
370
494
|
errorCode: 'TRANSPORT',
|
|
371
495
|
durationMs,
|
|
372
496
|
});
|
|
373
|
-
const decision =
|
|
497
|
+
const decision = allowTransportRetry
|
|
498
|
+
? transportRetryDecision(attempt, this.random)
|
|
499
|
+
: { retry: false, delayMs: 0 };
|
|
374
500
|
if (!decision.retry) {
|
|
375
501
|
throw new TransportError(`HTTP ${response.status} from ${url}`, requestId);
|
|
376
502
|
}
|
|
@@ -385,7 +511,7 @@ export class HttpClient {
|
|
|
385
511
|
delayMs: decision.delayMs,
|
|
386
512
|
});
|
|
387
513
|
requestTimeout.clear();
|
|
388
|
-
await this.
|
|
514
|
+
await this.sleepBeforeRetry(decision.delayMs);
|
|
389
515
|
continue;
|
|
390
516
|
}
|
|
391
517
|
const retryAfterSec = parseRetryAfter(response.headers.get('retry-after'));
|
|
@@ -434,7 +560,7 @@ export class HttpClient {
|
|
|
434
560
|
delayMs: decision.delayMs,
|
|
435
561
|
});
|
|
436
562
|
requestTimeout.clear();
|
|
437
|
-
await this.
|
|
563
|
+
await this.sleepBeforeRetry(decision.delayMs);
|
|
438
564
|
}
|
|
439
565
|
finally {
|
|
440
566
|
requestTimeout.clear();
|
|
@@ -463,6 +589,31 @@ export class HttpClient {
|
|
|
463
589
|
}
|
|
464
590
|
return headers;
|
|
465
591
|
}
|
|
592
|
+
/**
|
|
593
|
+
* Retry-delay sleep that bails the moment the shutdown signal fires
|
|
594
|
+
* (DEV-331, codex finding 1): a RATE_LIMITED `Retry-After: 60` or a
|
|
595
|
+
* transport backoff must not delay the honest-detach exit by up to a
|
|
596
|
+
* minute — reject with the InterruptError reason immediately. Mirrors
|
|
597
|
+
* poll.ts::sleepUnlessInterrupted.
|
|
598
|
+
*/
|
|
599
|
+
sleepBeforeRetry(ms) {
|
|
600
|
+
const signal = this.shutdownSignal;
|
|
601
|
+
if (signal == null)
|
|
602
|
+
return this.sleep(ms);
|
|
603
|
+
if (signal.aborted)
|
|
604
|
+
return Promise.reject(signal.reason);
|
|
605
|
+
return new Promise((resolve, reject) => {
|
|
606
|
+
const onAbort = () => reject(signal.reason);
|
|
607
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
608
|
+
this.sleep(ms).then(() => {
|
|
609
|
+
signal.removeEventListener('abort', onAbort);
|
|
610
|
+
resolve();
|
|
611
|
+
}, err => {
|
|
612
|
+
signal.removeEventListener('abort', onAbort);
|
|
613
|
+
reject(err instanceof Error ? err : new Error(String(err)));
|
|
614
|
+
});
|
|
615
|
+
});
|
|
616
|
+
}
|
|
466
617
|
debug(event) {
|
|
467
618
|
if (this.onDebug)
|
|
468
619
|
this.onDebug(event);
|
|
@@ -608,6 +759,18 @@ function transportRetryDecision(attempt, random) {
|
|
|
608
759
|
return { retry: false, delayMs: 0 };
|
|
609
760
|
return { retry: true, delayMs: backoffDelay(attempt, random) };
|
|
610
761
|
}
|
|
762
|
+
function canRetryTransport(method, options) {
|
|
763
|
+
return isIdempotentMethod(method) || hasIdempotencyKey(options.headers);
|
|
764
|
+
}
|
|
765
|
+
function isIdempotentMethod(method) {
|
|
766
|
+
const normalized = method.toUpperCase();
|
|
767
|
+
return normalized === 'GET' || normalized === 'HEAD';
|
|
768
|
+
}
|
|
769
|
+
function hasIdempotencyKey(headers) {
|
|
770
|
+
if (!headers)
|
|
771
|
+
return false;
|
|
772
|
+
return Object.keys(headers).some(name => name.toLowerCase() === 'idempotency-key');
|
|
773
|
+
}
|
|
611
774
|
function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict = true, retryOnRateLimit = true) {
|
|
612
775
|
switch (code) {
|
|
613
776
|
// M3.2 piece-1 / piece-2: `PRECONDITION_FAILED` (etag mismatch),
|
|
@@ -621,6 +784,9 @@ function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict
|
|
|
621
784
|
// case below and retries normally.
|
|
622
785
|
// FEATURE_GATED is non-retriable: a paid-feature gate can't self-heal with
|
|
623
786
|
// retries — the caller must upgrade their plan first.
|
|
787
|
+
// AMBIGUOUS_ORG is non-retriable: unlike a generic CONFLICT (mid-mutation
|
|
788
|
+
// snapshot race), this is a permanent id collision across the caller's
|
|
789
|
+
// organizations — retrying resolves the exact same ambiguity again.
|
|
624
790
|
case 'AUTH_REQUIRED':
|
|
625
791
|
case 'AUTH_INVALID':
|
|
626
792
|
case 'AUTH_FORBIDDEN':
|
|
@@ -632,6 +798,10 @@ function apiRetryDecision(code, attempt, retryAfterSec, random, retryOnConflict
|
|
|
632
798
|
case 'UNSUPPORTED':
|
|
633
799
|
case 'INSUFFICIENT_CREDITS':
|
|
634
800
|
case 'FEATURE_GATED':
|
|
801
|
+
case 'CLIENT_TOO_OLD':
|
|
802
|
+
case 'AMBIGUOUS_ORG':
|
|
803
|
+
// CLIENT_TOO_OLD: retrying re-sends the same too-old client — it can only
|
|
804
|
+
// self-heal by upgrading, so fail fast with the upgrade guidance.
|
|
635
805
|
return { retry: false, delayMs: 0 };
|
|
636
806
|
case 'CONFLICT':
|
|
637
807
|
// Read paths (e.g. GET /failure) retry once: 409 = mid-mutation snapshot.
|
package/dist/lib/interrupt.d.ts
CHANGED
|
@@ -18,18 +18,65 @@
|
|
|
18
18
|
* `process` and the streams are injectable so the wiring is unit-testable
|
|
19
19
|
* without spawning a subprocess or sending a real signal.
|
|
20
20
|
*/
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
* exit code. sourceRef: POSIX signal numbers (SIGHUP=1, SIGINT=2, SIGTERM=15).
|
|
24
|
-
*/
|
|
25
|
-
export declare const TERMINATION_EXIT_CODES: {
|
|
26
|
-
readonly SIGINT: 130;
|
|
27
|
-
readonly SIGTERM: 143;
|
|
28
|
-
readonly SIGHUP: 129;
|
|
29
|
-
};
|
|
30
|
-
export type TerminationSignal = keyof typeof TERMINATION_EXIT_CODES;
|
|
21
|
+
import { type TerminationSignal } from './errors.js';
|
|
22
|
+
export { TERMINATION_EXIT_CODES, type TerminationSignal } from './errors.js';
|
|
31
23
|
/** Back-compat alias: SIGINT's conventional exit code. */
|
|
32
24
|
export declare const SIGINT_EXIT_CODE: 130;
|
|
25
|
+
/**
|
|
26
|
+
* Structural view of {@link ShutdownController} threaded through the DI
|
|
27
|
+
* surfaces (`TestDeps`, `PollOptions`) — commands and the polling loop need
|
|
28
|
+
* only these members, and tests can supply a lightweight fake.
|
|
29
|
+
*/
|
|
30
|
+
export interface ShutdownHandle {
|
|
31
|
+
/** Aborts (reason: `InterruptError`) when a termination signal arrives while armed. */
|
|
32
|
+
readonly signal: AbortSignal;
|
|
33
|
+
/** Enter a graceful-detach scope. Returns the disposer that leaves it. */
|
|
34
|
+
arm(): () => void;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Process-lifetime coordinator between the signal handler and the `--wait`
|
|
38
|
+
* polling paths (DEV-331 piece 1).
|
|
39
|
+
*
|
|
40
|
+
* Two modes, chosen by whether a graceful-detach scope is armed when the
|
|
41
|
+
* signal arrives:
|
|
42
|
+
*
|
|
43
|
+
* - **Armed** (inside `pollRunUntilTerminal`): the handler only aborts
|
|
44
|
+
* `signal` with an `InterruptError` — no I/O, no exit. The in-flight fetch
|
|
45
|
+
* and every backoff sleep bail immediately; the `--wait` catch blocks own
|
|
46
|
+
* the cleanup (finalize the ticker, print the honest partial envelope +
|
|
47
|
+
* re-attach hint, rethrow to `index.ts` → exit 130/143/129).
|
|
48
|
+
* - **Disarmed** (no wait in progress — prompts, one-shot commands, local
|
|
49
|
+
* FS work): the handler prints the generic explanation and exits
|
|
50
|
+
* immediately, preserving the pre-DEV-331 behavior. An abort nobody
|
|
51
|
+
* observes must never leave the process hanging at e.g. a readline prompt.
|
|
52
|
+
*
|
|
53
|
+
* A second signal while the armed cleanup is in flight is the documented
|
|
54
|
+
* escape hatch: immediate hard exit.
|
|
55
|
+
*/
|
|
56
|
+
export declare class ShutdownController {
|
|
57
|
+
private readonly controller;
|
|
58
|
+
private armedCount;
|
|
59
|
+
private receivedSignal;
|
|
60
|
+
constructor();
|
|
61
|
+
get signal(): AbortSignal;
|
|
62
|
+
/** The first termination signal received, or null if none yet. */
|
|
63
|
+
get received(): TerminationSignal | null;
|
|
64
|
+
get isArmed(): boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Enter a graceful-detach scope (re-entrant: fan-out members overlap).
|
|
67
|
+
* Returns an idempotent disposer.
|
|
68
|
+
*/
|
|
69
|
+
arm(): () => void;
|
|
70
|
+
/** Record the signal and abort with an `InterruptError` carrying it. */
|
|
71
|
+
interrupt(signal: TerminationSignal): void;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The process-wide instance: `index.ts` hands it to `installSignalHandlers`,
|
|
75
|
+
* and it is the default `shutdown` for `TestDeps` / `PollOptions` /
|
|
76
|
+
* `ClientFactoryDeps`, so production wiring is automatic. Tests inject their
|
|
77
|
+
* own `ShutdownController` (or a `ShutdownHandle` fake) instead.
|
|
78
|
+
*/
|
|
79
|
+
export declare const globalShutdown: ShutdownController;
|
|
33
80
|
export declare function formatInterruptMessage(signal?: TerminationSignal): string;
|
|
34
81
|
export interface InterruptDeps {
|
|
35
82
|
/** Signal registrar. Defaults to `process.on`. */
|
|
@@ -38,10 +85,18 @@ export interface InterruptDeps {
|
|
|
38
85
|
stderr?: (line: string) => void;
|
|
39
86
|
/** Process exit. Defaults to `process.exit`. */
|
|
40
87
|
exit?: (code: number) => void;
|
|
88
|
+
/** Shutdown coordinator. Defaults to {@link globalShutdown}. */
|
|
89
|
+
shutdown?: ShutdownController;
|
|
41
90
|
}
|
|
42
91
|
/**
|
|
43
92
|
* Register handlers for SIGINT, SIGTERM and SIGHUP. Idempotent enough for a
|
|
44
93
|
* single top-level call in `index.ts`; not designed to be installed twice.
|
|
94
|
+
*
|
|
95
|
+
* First signal, armed scope: abort-only — the `--wait` catch paths own the
|
|
96
|
+
* honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
|
|
97
|
+
* First signal, disarmed: print the generic explanation + exit `128+signum`.
|
|
98
|
+
* Second signal (any mode): immediate hard exit — the escape hatch when the
|
|
99
|
+
* graceful cleanup itself wedges.
|
|
45
100
|
*/
|
|
46
101
|
export declare function installSignalHandlers(deps?: InterruptDeps): void;
|
|
47
102
|
export interface BrokenPipeDeps {
|
package/dist/lib/interrupt.js
CHANGED
|
@@ -18,18 +18,79 @@
|
|
|
18
18
|
* `process` and the streams are injectable so the wiring is unit-testable
|
|
19
19
|
* without spawning a subprocess or sending a real signal.
|
|
20
20
|
*/
|
|
21
|
+
import { setMaxListeners } from 'node:events';
|
|
21
22
|
import { writeSync } from 'node:fs';
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
* exit code. sourceRef: POSIX signal numbers (SIGHUP=1, SIGINT=2, SIGTERM=15).
|
|
25
|
-
*/
|
|
26
|
-
export const TERMINATION_EXIT_CODES = {
|
|
27
|
-
SIGINT: 130, // 128 + 2
|
|
28
|
-
SIGTERM: 143, // 128 + 15
|
|
29
|
-
SIGHUP: 129, // 128 + 1
|
|
30
|
-
};
|
|
23
|
+
import { InterruptError, TERMINATION_EXIT_CODES } from './errors.js';
|
|
24
|
+
export { TERMINATION_EXIT_CODES } from './errors.js';
|
|
31
25
|
/** Back-compat alias: SIGINT's conventional exit code. */
|
|
32
26
|
export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
|
|
27
|
+
/**
|
|
28
|
+
* Process-lifetime coordinator between the signal handler and the `--wait`
|
|
29
|
+
* polling paths (DEV-331 piece 1).
|
|
30
|
+
*
|
|
31
|
+
* Two modes, chosen by whether a graceful-detach scope is armed when the
|
|
32
|
+
* signal arrives:
|
|
33
|
+
*
|
|
34
|
+
* - **Armed** (inside `pollRunUntilTerminal`): the handler only aborts
|
|
35
|
+
* `signal` with an `InterruptError` — no I/O, no exit. The in-flight fetch
|
|
36
|
+
* and every backoff sleep bail immediately; the `--wait` catch blocks own
|
|
37
|
+
* the cleanup (finalize the ticker, print the honest partial envelope +
|
|
38
|
+
* re-attach hint, rethrow to `index.ts` → exit 130/143/129).
|
|
39
|
+
* - **Disarmed** (no wait in progress — prompts, one-shot commands, local
|
|
40
|
+
* FS work): the handler prints the generic explanation and exits
|
|
41
|
+
* immediately, preserving the pre-DEV-331 behavior. An abort nobody
|
|
42
|
+
* observes must never leave the process hanging at e.g. a readline prompt.
|
|
43
|
+
*
|
|
44
|
+
* A second signal while the armed cleanup is in flight is the documented
|
|
45
|
+
* escape hatch: immediate hard exit.
|
|
46
|
+
*/
|
|
47
|
+
export class ShutdownController {
|
|
48
|
+
controller = new AbortController();
|
|
49
|
+
armedCount = 0;
|
|
50
|
+
receivedSignal = null;
|
|
51
|
+
constructor() {
|
|
52
|
+
// Every fetch and every poll iteration composes this signal via
|
|
53
|
+
// AbortSignal.any — a 50-run batch fan-out legitimately holds >10
|
|
54
|
+
// concurrent listeners, so silence Node's MaxListeners warning.
|
|
55
|
+
setMaxListeners(0, this.controller.signal);
|
|
56
|
+
}
|
|
57
|
+
get signal() {
|
|
58
|
+
return this.controller.signal;
|
|
59
|
+
}
|
|
60
|
+
/** The first termination signal received, or null if none yet. */
|
|
61
|
+
get received() {
|
|
62
|
+
return this.receivedSignal;
|
|
63
|
+
}
|
|
64
|
+
get isArmed() {
|
|
65
|
+
return this.armedCount > 0;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Enter a graceful-detach scope (re-entrant: fan-out members overlap).
|
|
69
|
+
* Returns an idempotent disposer.
|
|
70
|
+
*/
|
|
71
|
+
arm() {
|
|
72
|
+
this.armedCount += 1;
|
|
73
|
+
let disposed = false;
|
|
74
|
+
return () => {
|
|
75
|
+
if (disposed)
|
|
76
|
+
return;
|
|
77
|
+
disposed = true;
|
|
78
|
+
this.armedCount -= 1;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** Record the signal and abort with an `InterruptError` carrying it. */
|
|
82
|
+
interrupt(signal) {
|
|
83
|
+
this.receivedSignal = signal;
|
|
84
|
+
this.controller.abort(new InterruptError(signal));
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The process-wide instance: `index.ts` hands it to `installSignalHandlers`,
|
|
89
|
+
* and it is the default `shutdown` for `TestDeps` / `PollOptions` /
|
|
90
|
+
* `ClientFactoryDeps`, so production wiring is automatic. Tests inject their
|
|
91
|
+
* own `ShutdownController` (or a `ShutdownHandle` fake) instead.
|
|
92
|
+
*/
|
|
93
|
+
export const globalShutdown = new ShutdownController();
|
|
33
94
|
export function formatInterruptMessage(signal = 'SIGINT') {
|
|
34
95
|
return (`Interrupted (${signal}). Any run already started keeps executing on the server; ` +
|
|
35
96
|
'check it with `testsprite test list` or `testsprite test wait <runId>`.');
|
|
@@ -37,6 +98,12 @@ export function formatInterruptMessage(signal = 'SIGINT') {
|
|
|
37
98
|
/**
|
|
38
99
|
* Register handlers for SIGINT, SIGTERM and SIGHUP. Idempotent enough for a
|
|
39
100
|
* single top-level call in `index.ts`; not designed to be installed twice.
|
|
101
|
+
*
|
|
102
|
+
* First signal, armed scope: abort-only — the `--wait` catch paths own the
|
|
103
|
+
* honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
|
|
104
|
+
* First signal, disarmed: print the generic explanation + exit `128+signum`.
|
|
105
|
+
* Second signal (any mode): immediate hard exit — the escape hatch when the
|
|
106
|
+
* graceful cleanup itself wedges.
|
|
40
107
|
*/
|
|
41
108
|
export function installSignalHandlers(deps = {}) {
|
|
42
109
|
const on = deps.on ??
|
|
@@ -56,8 +123,26 @@ export function installSignalHandlers(deps = {}) {
|
|
|
56
123
|
}
|
|
57
124
|
});
|
|
58
125
|
const exit = deps.exit ?? ((code) => process.exit(code));
|
|
126
|
+
const shutdown = deps.shutdown ?? globalShutdown;
|
|
59
127
|
for (const signal of Object.keys(TERMINATION_EXIT_CODES)) {
|
|
60
128
|
on(signal, () => {
|
|
129
|
+
if (shutdown.received !== null) {
|
|
130
|
+
// Second signal while graceful cleanup is in flight: hard exit now.
|
|
131
|
+
exit(TERMINATION_EXIT_CODES[signal]);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (shutdown.isArmed) {
|
|
135
|
+
// Graceful detach: abort only (sync, signal-safe — no I/O here so a
|
|
136
|
+
// pending stdout `drain` wait can settle); the armed catch paths
|
|
137
|
+
// finalize the ticker, print the partial + re-attach hint, and exit
|
|
138
|
+
// via index.ts with this signal's code.
|
|
139
|
+
shutdown.interrupt(signal);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
// Disarmed (no --wait in progress): legacy immediate exit. Record the
|
|
143
|
+
// signal first so a second one takes the hard-exit branch even when
|
|
144
|
+
// `exit` is injected and does not terminate (unit tests).
|
|
145
|
+
shutdown.interrupt(signal);
|
|
61
146
|
// Blank line first so the message starts on its own row rather than
|
|
62
147
|
// trailing the progress ticker's in-place line.
|
|
63
148
|
stderr('');
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared org-attribution text rendering for `auth status`, `usage`, and
|
|
3
|
+
* `doctor` — every surface that reads `GET /me`.
|
|
4
|
+
*
|
|
5
|
+
* `organizations[]` (the caller's full account-wide membership list) and
|
|
6
|
+
* `org` (a membership key's own org binding, present only for a
|
|
7
|
+
* Postgres-backed `sk-member-…` key) are both optional/absent-safe on the `/me`
|
|
8
|
+
* response: older backends omit them entirely, and a lookup hiccup
|
|
9
|
+
* server-side omits `organizations` without failing the request. Callers
|
|
10
|
+
* render a line only when the corresponding formatter returns a non-undefined
|
|
11
|
+
* string — never an `undefined`/`null` literal.
|
|
12
|
+
*/
|
|
13
|
+
/** One organization from `MeResponse.organizations[]`. */
|
|
14
|
+
export interface CliOrgSummary {
|
|
15
|
+
id: string;
|
|
16
|
+
name: string;
|
|
17
|
+
role: string;
|
|
18
|
+
isPersonal: boolean;
|
|
19
|
+
}
|
|
20
|
+
/** A membership key's own org binding, from `MeResponse.org`. */
|
|
21
|
+
export interface CliOrgBinding {
|
|
22
|
+
id: string;
|
|
23
|
+
/** `null` when best-effort name resolution failed or found no match server-side. */
|
|
24
|
+
name: string | null;
|
|
25
|
+
role: string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* One-line summary of the caller's full membership list, for an `orgs:`
|
|
29
|
+
* line. Returns `undefined` when the list is absent or empty so the caller
|
|
30
|
+
* can omit the line entirely.
|
|
31
|
+
*/
|
|
32
|
+
export declare function formatOrgsSummary(organizations: readonly CliOrgSummary[] | undefined): string | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* One-line summary of a membership key's own org binding, for an
|
|
35
|
+
* `org binding:` line. Returns `undefined` when no binding is present
|
|
36
|
+
* (legacy envelope key, or a backend that doesn't return it).
|
|
37
|
+
*/
|
|
38
|
+
export declare function formatOrgBinding(org: CliOrgBinding | undefined): string | undefined;
|
|
39
|
+
/**
|
|
40
|
+
* Hint for a caller whose key can only reach their personal workspace while
|
|
41
|
+
* they are a member of at least one team workspace.
|
|
42
|
+
*
|
|
43
|
+
* A key is bound to exactly ONE membership — the workspace is chosen when the
|
|
44
|
+
* key is minted, not per command, which is why there is no `--org` flag to
|
|
45
|
+
* reach for. Without this line the failure mode is silent and baffling: the
|
|
46
|
+
* team's projects simply don't appear in `project list`, and addressing one by
|
|
47
|
+
* id 404s exactly like a typo would.
|
|
48
|
+
*
|
|
49
|
+
* Returns `undefined` when the key is already workspace-bound, or when the
|
|
50
|
+
* caller has no team workspace to be confused about.
|
|
51
|
+
*/
|
|
52
|
+
export declare function formatPersonalScopeHint(organizations: readonly CliOrgSummary[] | undefined, org: CliOrgBinding | undefined): string | undefined;
|