@testsprite/testsprite-cli 0.12.0 → 0.13.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 +11 -4
- package/dist/commands/agent.js +16 -13
- package/dist/commands/auth.d.ts +19 -0
- package/dist/commands/auth.js +60 -24
- package/dist/commands/ci.d.ts +86 -1
- package/dist/commands/ci.js +436 -5
- package/dist/commands/doctor.d.ts +2 -0
- package/dist/commands/doctor.js +22 -9
- package/dist/commands/init.js +14 -11
- package/dist/commands/project-env.js +9 -9
- package/dist/commands/project.d.ts +5 -5
- package/dist/commands/project.js +42 -42
- package/dist/commands/schedule.d.ts +2 -0
- package/dist/commands/schedule.js +18 -10
- package/dist/commands/test.d.ts +73 -27
- package/dist/commands/test.js +1756 -413
- package/dist/commands/testlist.js +49 -19
- package/dist/commands/tunnel.d.ts +26 -3
- package/dist/commands/tunnel.js +211 -14
- package/dist/commands/usage.d.ts +3 -0
- package/dist/commands/usage.js +12 -5
- package/dist/index.js +34 -20
- package/dist/lib/agent-targets.d.ts +3 -3
- package/dist/lib/agent-targets.js +2 -2
- package/dist/lib/billing-refusal.d.ts +43 -0
- package/dist/lib/billing-refusal.js +171 -0
- package/dist/lib/bundle.d.ts +5 -0
- package/dist/lib/bundle.js +43 -13
- package/dist/lib/ci-linkage.d.ts +90 -0
- package/dist/lib/ci-linkage.js +181 -0
- package/dist/lib/client-factory.d.ts +4 -1
- package/dist/lib/client-factory.js +23 -2
- package/dist/lib/config.d.ts +17 -0
- package/dist/lib/config.js +20 -1
- package/dist/lib/conflict-reason.d.ts +27 -3
- package/dist/lib/conflict-reason.js +53 -4
- package/dist/lib/credentials.js +56 -14
- package/dist/lib/dry-run/samples.d.ts +13 -1
- package/dist/lib/dry-run/samples.js +51 -7
- package/dist/lib/errors.d.ts +18 -11
- package/dist/lib/errors.js +111 -13
- package/dist/lib/failing-fe-resolver.d.ts +1 -1
- package/dist/lib/failing-fe-resolver.js +3 -3
- package/dist/lib/gh-output.d.ts +1 -0
- package/dist/lib/gh-output.js +13 -4
- package/dist/lib/history-retention.d.ts +8 -0
- package/dist/lib/history-retention.js +24 -0
- package/dist/lib/http.d.ts +37 -19
- package/dist/lib/http.js +46 -24
- package/dist/lib/interrupt.d.ts +21 -13
- package/dist/lib/interrupt.js +32 -21
- package/dist/lib/junit-report.d.ts +11 -1
- package/dist/lib/junit-report.js +15 -3
- package/dist/lib/local-target.d.ts +1 -1
- package/dist/lib/local-target.js +1 -1
- package/dist/lib/plan-poll.d.ts +11 -11
- package/dist/lib/plan-poll.js +12 -12
- package/dist/lib/plans.types.d.ts +9 -9
- package/dist/lib/plans.types.js +3 -3
- package/dist/lib/poll.d.ts +2 -2
- package/dist/lib/poll.js +9 -3
- package/dist/lib/render-error.d.ts +2 -0
- package/dist/lib/render-error.js +13 -0
- package/dist/lib/response-schemas.d.ts +54 -12
- package/dist/lib/response-schemas.js +88 -7
- package/dist/lib/runs.types.d.ts +59 -10
- package/dist/lib/secret-file.js +72 -14
- package/dist/lib/skill-nudge.d.ts +6 -1
- package/dist/lib/skill-nudge.js +32 -5
- package/dist/lib/target-url-preflight.d.ts +6 -4
- package/dist/lib/target-url-preflight.js +64 -51
- package/dist/lib/target-url.js +6 -6
- package/dist/lib/telemetry.d.ts +4 -1
- package/dist/lib/telemetry.js +13 -13
- package/dist/lib/ticker.js +93 -4
- package/dist/lib/tunnel-session.d.ts +13 -0
- package/dist/lib/tunnel-session.js +4 -1
- package/dist/lib/tunnel.types.d.ts +12 -2
- package/dist/lib/tunnel.types.js +2 -2
- package/dist/lib/wait-exit.d.ts +8 -0
- package/dist/lib/wait-exit.js +76 -4
- package/dist/lib/workspace-status.d.ts +23 -0
- package/dist/lib/workspace-status.js +15 -0
- package/dist/version-guard.d.ts +7 -1
- package/dist/version-guard.js +19 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +4 -4
- package/skills/testsprite-onboard.skill.md +4 -4
- package/skills/testsprite-verify.codex.md +59 -57
- package/skills/testsprite-verify.skill.md +53 -38
package/dist/index.js
CHANGED
|
@@ -12,23 +12,22 @@ import { createTunnelCommand } from './commands/tunnel.js';
|
|
|
12
12
|
import { createTestCommand } from './commands/test.js';
|
|
13
13
|
import { createTestListCommand } from './commands/testlist.js';
|
|
14
14
|
import { createUsageCommand } from './commands/usage.js';
|
|
15
|
+
import { resolveProfileName } from './lib/config.js';
|
|
16
|
+
import { classifyBillingRefusal } from './lib/billing-refusal.js';
|
|
15
17
|
import { TARGETS } from './lib/agent-targets.js';
|
|
16
18
|
import { ApiError, CLIError, InterruptError, RequestTimeoutError, extractNodeErrorCode, } from './lib/errors.js';
|
|
17
|
-
import { installBrokenPipeGuard, installSignalHandlers } from './lib/interrupt.js';
|
|
19
|
+
import { armInterruptExitBackstop, installBrokenPipeGuard, installSignalHandlers, } from './lib/interrupt.js';
|
|
18
20
|
import { Output, isOutputMode } from './lib/output.js';
|
|
19
21
|
import { maybeInstallProxyAgent } from './lib/proxy.js';
|
|
20
|
-
import { renderAmbiguousOrgCandidates, renderCommanderError, rephraseUnknownOption, } from './lib/render-error.js';
|
|
22
|
+
import { renderAmbiguousOrgCandidates, renderTunnelBindingLimitIds, renderCommanderError, rephraseUnknownOption, } from './lib/render-error.js';
|
|
21
23
|
import { isPlanTemplateInvocation, maybeEmitSkillNudge } from './lib/skill-nudge.js';
|
|
22
24
|
import { classifyCliError, isTelemetryOptedOut, recordOutcome, resolveTelemetryAuth, } from './lib/telemetry.js';
|
|
23
25
|
import { maybeNotifyUpdate } from './lib/update-check.js';
|
|
24
26
|
import { VERSION } from './version.js';
|
|
25
|
-
import {
|
|
27
|
+
import { rejectUnsupportedNodeVersion } from './version-guard.js';
|
|
26
28
|
// Guard: exit early with a clear message on unsupported Node.js versions,
|
|
27
29
|
// rather than failing later with a cryptic ESM/runtime error.
|
|
28
|
-
|
|
29
|
-
process.stderr.write(`Error: testsprite requires Node.js ${SUPPORTED_NODE_RANGE} (found ${process.versions.node}).\nInstall a supported Node.js release from https://nodejs.org\n`);
|
|
30
|
-
process.exit(1);
|
|
31
|
-
}
|
|
30
|
+
rejectUnsupportedNodeVersion(process.versions.node);
|
|
32
31
|
const program = new Command();
|
|
33
32
|
// exitOverride() causes Commander to throw CommanderError instead of calling
|
|
34
33
|
// process.exit() directly, giving our catch block a chance to remap error
|
|
@@ -231,9 +230,10 @@ program.hook('preAction', (_thisCommand, actionCommand) => {
|
|
|
231
230
|
commandPath,
|
|
232
231
|
output: isOutputMode(globals.output) ? globals.output : 'text',
|
|
233
232
|
dryRun: globals.dryRun ?? false,
|
|
234
|
-
profile: globals.profile
|
|
233
|
+
profile: resolveProfileName(globals.profile),
|
|
235
234
|
cwd: process.cwd(),
|
|
236
235
|
env: process.env,
|
|
236
|
+
debug: globals.debug ?? false,
|
|
237
237
|
});
|
|
238
238
|
}
|
|
239
239
|
// Best-effort update notice (see lib/update-check.ts): self-gates on the
|
|
@@ -251,12 +251,12 @@ program.hook('preAction', (_thisCommand, actionCommand) => {
|
|
|
251
251
|
void maybeNotifyUpdate();
|
|
252
252
|
}
|
|
253
253
|
});
|
|
254
|
-
// Clean process lifecycle (
|
|
254
|
+
// Clean process lifecycle (errors.md §8.1): during a `--wait`
|
|
255
255
|
// poll the scope is armed — the first SIGINT/SIGTERM/SIGHUP aborts gracefully
|
|
256
256
|
// and the wait path prints an honest partial (the run KEEPS executing and
|
|
257
257
|
// billing server-side) + re-attach hint before exiting 128+signum; a second
|
|
258
|
-
// signal hard-exits. Outside an armed scope: a clear one-line message
|
|
259
|
-
//
|
|
258
|
+
// signal hard-exits. Outside an armed scope: a clear one-line message, then
|
|
259
|
+
// drain an in-flight request or exit immediately when idle. Plus an EPIPE guard
|
|
260
260
|
// so piping to a reader that closes early (`| head`) exits cleanly instead of
|
|
261
261
|
// dumping a raw `write EPIPE` stack.
|
|
262
262
|
installSignalHandlers();
|
|
@@ -292,7 +292,7 @@ catch (err) {
|
|
|
292
292
|
// user's error. The classification mirrors the exit-code mapping the
|
|
293
293
|
// branches apply.
|
|
294
294
|
//
|
|
295
|
-
//
|
|
295
|
+
// SET `process.exitCode` and let the event loop drain instead of
|
|
296
296
|
// forcing `process.exit()`. A forced exit tears the process down while the
|
|
297
297
|
// just-completed HTTPS request's TLS socket is still mid-close; on Windows
|
|
298
298
|
// libuv asserts on the half-closed handle (src/win/async.c) and the process
|
|
@@ -321,6 +321,7 @@ catch (err) {
|
|
|
321
321
|
const mode = isOutputMode(rawMode) ? rawMode : 'text';
|
|
322
322
|
const output = new Output(mode);
|
|
323
323
|
if (err instanceof ApiError) {
|
|
324
|
+
const billingRefusal = classifyBillingRefusal(err);
|
|
324
325
|
const message = err.code === 'UNSUPPORTED' &&
|
|
325
326
|
err.getDetail('reason') === 'tunnel-unsupported-for-backend-test'
|
|
326
327
|
? '--local only supports frontend tests today. Re-run without --local, or point the test at a reachable base URL.'
|
|
@@ -333,6 +334,7 @@ catch (err) {
|
|
|
333
334
|
nextAction: err.nextAction,
|
|
334
335
|
requestId: err.requestId,
|
|
335
336
|
details: err.details,
|
|
337
|
+
...(billingRefusal ? { links: billingRefusal.links } : {}),
|
|
336
338
|
},
|
|
337
339
|
};
|
|
338
340
|
process.stderr.write(`${JSON.stringify(envelope, null, 2)}\n`);
|
|
@@ -341,6 +343,10 @@ catch (err) {
|
|
|
341
343
|
process.stderr.write(`Error: ${message}\n`);
|
|
342
344
|
if (err.nextAction)
|
|
343
345
|
process.stderr.write(`${err.nextAction}\n`);
|
|
346
|
+
if (billingRefusal) {
|
|
347
|
+
for (const line of billingRefusal.lines)
|
|
348
|
+
process.stderr.write(`${line}\n`);
|
|
349
|
+
}
|
|
344
350
|
if (err.requestId && err.requestId !== 'local')
|
|
345
351
|
process.stderr.write(`requestId: ${err.requestId}\n`);
|
|
346
352
|
// C1: surface requiredScopes / grantedScopes on AUTH_FORBIDDEN
|
|
@@ -372,14 +378,18 @@ catch (err) {
|
|
|
372
378
|
process.stderr.write(`${line}\n`);
|
|
373
379
|
}
|
|
374
380
|
}
|
|
381
|
+
if (err.code === 'RATE_LIMITED' && err.getDetail('reason') === 'tunnel_binding_limit') {
|
|
382
|
+
for (const line of renderTunnelBindingLimitIds(err.getDetail('clientIds'))) {
|
|
383
|
+
process.stderr.write(`${line}\n`);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
375
386
|
}
|
|
376
387
|
await flushThenSetExitCode(err.exitCode);
|
|
377
388
|
}
|
|
378
389
|
else if (err instanceof InterruptError) {
|
|
379
|
-
//
|
|
380
|
-
//
|
|
381
|
-
// the conventional 128+signum code
|
|
382
|
-
// the error catalog. Note: Ctrl-C does NOT cancel the server-side run.
|
|
390
|
+
// A run wait may already have printed a partial result and re-attach hint.
|
|
391
|
+
// A disarmed request has no run ID, so its JSON hint describes checking
|
|
392
|
+
// current state before retrying. Both use the conventional 128+signum code.
|
|
383
393
|
if (mode === 'json') {
|
|
384
394
|
const tunnelDetach = err
|
|
385
395
|
.tunnelDetach;
|
|
@@ -388,9 +398,12 @@ catch (err) {
|
|
|
388
398
|
code: 'INTERRUPTED',
|
|
389
399
|
message: err.message,
|
|
390
400
|
nextAction: tunnelDetach?.nextAction ??
|
|
391
|
-
|
|
392
|
-
'
|
|
393
|
-
|
|
401
|
+
(err.runWaitContext
|
|
402
|
+
? 'The server-side run (if any) keeps executing and billing. ' +
|
|
403
|
+
'Re-attach with: testsprite test wait <runId>, or stop it with: testsprite test cancel <runId> ' +
|
|
404
|
+
'(runId is in the partial JSON on stdout).'
|
|
405
|
+
: 'The request was interrupted. Check the current state before retrying; ' +
|
|
406
|
+
'a multi-item command may have processed some items.'),
|
|
394
407
|
requestId: 'local',
|
|
395
408
|
details: {
|
|
396
409
|
signal: err.signal,
|
|
@@ -406,6 +419,7 @@ catch (err) {
|
|
|
406
419
|
process.stderr.write(`Error: ${err.message}\n`);
|
|
407
420
|
}
|
|
408
421
|
await flushThenSetExitCode(err.exitCode);
|
|
422
|
+
armInterruptExitBackstop(err.exitCode);
|
|
409
423
|
}
|
|
410
424
|
else if (err instanceof RequestTimeoutError) {
|
|
411
425
|
// Structured rendering for per-request timeouts: JSON mode emits a
|
|
@@ -441,7 +455,7 @@ catch (err) {
|
|
|
441
455
|
// help`, `help test`, etc.)
|
|
442
456
|
// Both are user-initiated "show me help" requests and must exit 0 per the
|
|
443
457
|
// AWS-CLI convention. Failing to map 'commander.help' caused these paths
|
|
444
|
-
// to fall through to the generic `process.exit(5)` branch
|
|
458
|
+
// to fall through to the generic `process.exit(5)` branch.
|
|
445
459
|
if (err.code === 'commander.helpDisplayed' ||
|
|
446
460
|
err.code === 'commander.help' ||
|
|
447
461
|
err.code === 'commander.version') {
|
|
@@ -21,7 +21,7 @@ export interface TargetSpec {
|
|
|
21
21
|
* truncated beyond) and `copilot` (no cap, but `applyTo: '**'` injects it into
|
|
22
22
|
* every request, so context cost is the constraint).
|
|
23
23
|
*
|
|
24
|
-
* Read it via {@link ownFileBodyFor}, never by testing target names
|
|
24
|
+
* Read it via {@link ownFileBodyFor}, never by testing target names.
|
|
25
25
|
*/
|
|
26
26
|
compactBody?: boolean;
|
|
27
27
|
/**
|
|
@@ -153,8 +153,8 @@ export declare function compactBodyFor(skill: string, read?: ReadFn): string;
|
|
|
153
153
|
/**
|
|
154
154
|
* The canonical own-file body for a (target, skill) pair, and therefore the body
|
|
155
155
|
* the install marker's hash covers. Every producer AND consumer of an own-file
|
|
156
|
-
* body must resolve through here —
|
|
157
|
-
*
|
|
156
|
+
* body must resolve through here — keeping separate copies of this rule is
|
|
157
|
+
* what lets install and status disagree on the same file.
|
|
158
158
|
*/
|
|
159
159
|
export declare function ownFileBodyFor(target: AgentTarget, skill: string, read?: ReadFn): string;
|
|
160
160
|
/**
|
|
@@ -287,8 +287,8 @@ export function compactBodyFor(skill, read = defaultRead) {
|
|
|
287
287
|
/**
|
|
288
288
|
* The canonical own-file body for a (target, skill) pair, and therefore the body
|
|
289
289
|
* the install marker's hash covers. Every producer AND consumer of an own-file
|
|
290
|
-
* body must resolve through here —
|
|
291
|
-
*
|
|
290
|
+
* body must resolve through here — keeping separate copies of this rule is
|
|
291
|
+
* what lets install and status disagree on the same file.
|
|
292
292
|
*/
|
|
293
293
|
export function ownFileBodyFor(target, skill, read = defaultRead) {
|
|
294
294
|
return TARGETS[target].compactBody ? compactBodyFor(skill, read) : loadSkillBodyFor(skill, read);
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { ApiError } from './errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* The workspace gate's three refusals, named as the backend's `GateRefusal`
|
|
4
|
+
* names them — the one set the CLI, MCP, portal and agent all share.
|
|
5
|
+
*/
|
|
6
|
+
export type GateRefusal = 'paused' | 'not_entitled' | 'limit_exceeded';
|
|
7
|
+
export interface BillingRefusal {
|
|
8
|
+
/** A gate refusal, or a credit shortfall (reported separately as INSUFFICIENT_CREDITS). */
|
|
9
|
+
reason: GateRefusal | 'insufficient_credits';
|
|
10
|
+
links: {
|
|
11
|
+
pricing: string;
|
|
12
|
+
billing: string;
|
|
13
|
+
};
|
|
14
|
+
nextAction: string;
|
|
15
|
+
lines: string[];
|
|
16
|
+
}
|
|
17
|
+
type BillingInput = Pick<ApiError, 'code' | 'message' | 'nextAction' | 'details'> & {
|
|
18
|
+
apiUrl?: string;
|
|
19
|
+
serverNextAction?: string;
|
|
20
|
+
};
|
|
21
|
+
/** Shared pricing/billing destinations for refusals and history-window notes. */
|
|
22
|
+
export declare function resolveBillingLinks(input: {
|
|
23
|
+
apiUrl?: string;
|
|
24
|
+
billingUrl?: string;
|
|
25
|
+
orgId?: unknown;
|
|
26
|
+
nextAction?: string;
|
|
27
|
+
message?: string;
|
|
28
|
+
}): {
|
|
29
|
+
pricing: string;
|
|
30
|
+
billing: string;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Which gate refusal a FEATURE_GATED `details.reason` is. An absent or empty
|
|
34
|
+
* reason is an older backend that never sent one (historically a plan
|
|
35
|
+
* exclusion). Any other value — `rollout`, the MCP view-only mirror's
|
|
36
|
+
* `mcp_origin`, or one this CLI doesn't know yet — is not a billing refusal:
|
|
37
|
+
* upgrading does nothing for it, so it gets no links and no fallback advice.
|
|
38
|
+
*/
|
|
39
|
+
export declare function gateRefusalOf(reason: unknown): GateRefusal | undefined;
|
|
40
|
+
/** True for a paused-workspace reason, including the deprecated `billing_hold`. */
|
|
41
|
+
export declare function isPausedReason(reason: unknown): boolean;
|
|
42
|
+
export declare function classifyBillingRefusal(input: BillingInput): BillingRefusal | undefined;
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { resolvePortalBase } from './facade.js';
|
|
2
|
+
function hasPlaceholder(url) {
|
|
3
|
+
return (/^(undefined|null)$/i.test(url.hostname) || /\/(?:undefined|null)(?:\/|$)/i.test(url.pathname));
|
|
4
|
+
}
|
|
5
|
+
function portalUrlIn(text, billingOnly = false) {
|
|
6
|
+
for (const match of text.matchAll(/https?:\/\/[^\s<>"'`]+/g)) {
|
|
7
|
+
const candidate = match[0].replace(/[),.;!?]+$/, '');
|
|
8
|
+
try {
|
|
9
|
+
const url = new URL(candidate);
|
|
10
|
+
if (hasPlaceholder(url))
|
|
11
|
+
continue;
|
|
12
|
+
if (url.pathname.endsWith('/settings/billing') ||
|
|
13
|
+
(!billingOnly && url.pathname === '/pricing')) {
|
|
14
|
+
return candidate;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
// Ignore malformed server text and use the next available source.
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The `TESTSPRITE_PORTAL_URL` origin, when the override is set and valid.
|
|
25
|
+
* `resolvePortalBase` checks this same env var first and ignores its `apiUrl`
|
|
26
|
+
* argument once it finds it set, so any argument resolves it — `''` keeps the
|
|
27
|
+
* intent explicit at each call site (there is no API URL to fall back to).
|
|
28
|
+
*/
|
|
29
|
+
function overridePortalBase() {
|
|
30
|
+
if (!process.env.TESTSPRITE_PORTAL_URL?.trim())
|
|
31
|
+
return undefined;
|
|
32
|
+
const resolved = resolvePortalBase('');
|
|
33
|
+
return resolved && !hasPlaceholder(new URL(resolved)) ? resolved : undefined;
|
|
34
|
+
}
|
|
35
|
+
function portalBase(input) {
|
|
36
|
+
const override = overridePortalBase();
|
|
37
|
+
if (override)
|
|
38
|
+
return override;
|
|
39
|
+
const billingUrl = typeof input.details.billingUrl === 'string' ? input.details.billingUrl : '';
|
|
40
|
+
const serverUrl = portalUrlIn([billingUrl, input.serverNextAction ?? input.nextAction, input.message].join(' '));
|
|
41
|
+
if (serverUrl)
|
|
42
|
+
return new URL(serverUrl).origin;
|
|
43
|
+
return input.apiUrl ? resolvePortalBase(input.apiUrl) : undefined;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Rebase an absolute server-supplied billing URL onto the operator's
|
|
47
|
+
* `TESTSPRITE_PORTAL_URL` override, keeping the path (and query, if any) —
|
|
48
|
+
* the server knows its own routes, but the override says where the CLI's
|
|
49
|
+
* links should actually point. Without this, an override set for `pricing`
|
|
50
|
+
* (always synthesized from `portalBase`) silently didn't apply to a
|
|
51
|
+
* server-found `billing` URL, sending the two links to different hosts.
|
|
52
|
+
*/
|
|
53
|
+
function rebaseOntoOverride(url) {
|
|
54
|
+
const override = overridePortalBase();
|
|
55
|
+
if (!override)
|
|
56
|
+
return url;
|
|
57
|
+
const parsed = new URL(url);
|
|
58
|
+
return `${override}${parsed.pathname}${parsed.search}`;
|
|
59
|
+
}
|
|
60
|
+
/** Shared pricing/billing destinations for refusals and history-window notes. */
|
|
61
|
+
export function resolveBillingLinks(input) {
|
|
62
|
+
const base = portalBase({
|
|
63
|
+
apiUrl: input.apiUrl,
|
|
64
|
+
details: { billingUrl: input.billingUrl },
|
|
65
|
+
nextAction: input.nextAction ?? '',
|
|
66
|
+
message: input.message ?? '',
|
|
67
|
+
code: 'FEATURE_GATED',
|
|
68
|
+
});
|
|
69
|
+
const pricing = base ? `${base}/pricing` : '/pricing';
|
|
70
|
+
const foundBilling = portalUrlIn(input.billingUrl ?? '', true) ??
|
|
71
|
+
portalUrlIn([input.nextAction, input.message].join(' '), true);
|
|
72
|
+
const orgId = safeOrgId(input.orgId);
|
|
73
|
+
const billing = (foundBilling !== undefined ? rebaseOntoOverride(foundBilling) : undefined) ??
|
|
74
|
+
(base
|
|
75
|
+
? `${base}${orgId ? `/dashboard-v3/o/${orgId}` : '/dashboard'}/settings/billing`
|
|
76
|
+
: orgId
|
|
77
|
+
? `/dashboard-v3/o/${orgId}/settings/billing`
|
|
78
|
+
: '/dashboard/settings/billing');
|
|
79
|
+
return { pricing, billing };
|
|
80
|
+
}
|
|
81
|
+
/** One ` label: value` line, aligned like the CLI's other key/value output. */
|
|
82
|
+
function fact(label, value) {
|
|
83
|
+
return ` ${`${label}:`.padEnd(11)}${value}`;
|
|
84
|
+
}
|
|
85
|
+
function safeOrgId(value) {
|
|
86
|
+
return typeof value === 'string' &&
|
|
87
|
+
value.trim() !== '' &&
|
|
88
|
+
!/^(undefined|null)$/i.test(value.trim()) &&
|
|
89
|
+
!/[/?#]/.test(value)
|
|
90
|
+
? encodeURIComponent(value)
|
|
91
|
+
: undefined;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* `details.reason` spellings of the three gate refusals: the gate's own names,
|
|
95
|
+
* plus the deprecated `billing_hold` / `plan` / `plan_limit` that older
|
|
96
|
+
* backends' CLI envelope and gate body still send. The CLI reads both and
|
|
97
|
+
* only ever writes the gate's names.
|
|
98
|
+
*/
|
|
99
|
+
const GATE_REFUSAL_BY_REASON = new Map([
|
|
100
|
+
['paused', 'paused'],
|
|
101
|
+
['billing_hold', 'paused'],
|
|
102
|
+
['not_entitled', 'not_entitled'],
|
|
103
|
+
['plan', 'not_entitled'],
|
|
104
|
+
['limit_exceeded', 'limit_exceeded'],
|
|
105
|
+
['plan_limit', 'limit_exceeded'],
|
|
106
|
+
]);
|
|
107
|
+
/**
|
|
108
|
+
* Which gate refusal a FEATURE_GATED `details.reason` is. An absent or empty
|
|
109
|
+
* reason is an older backend that never sent one (historically a plan
|
|
110
|
+
* exclusion). Any other value — `rollout`, the MCP view-only mirror's
|
|
111
|
+
* `mcp_origin`, or one this CLI doesn't know yet — is not a billing refusal:
|
|
112
|
+
* upgrading does nothing for it, so it gets no links and no fallback advice.
|
|
113
|
+
*/
|
|
114
|
+
export function gateRefusalOf(reason) {
|
|
115
|
+
if (reason === undefined || reason === '')
|
|
116
|
+
return 'not_entitled';
|
|
117
|
+
return typeof reason === 'string' ? GATE_REFUSAL_BY_REASON.get(reason) : undefined;
|
|
118
|
+
}
|
|
119
|
+
/** True for a paused-workspace reason, including the deprecated `billing_hold`. */
|
|
120
|
+
export function isPausedReason(reason) {
|
|
121
|
+
return reason === 'paused' || reason === 'billing_hold';
|
|
122
|
+
}
|
|
123
|
+
export function classifyBillingRefusal(input) {
|
|
124
|
+
let reason;
|
|
125
|
+
if (input.code === 'INSUFFICIENT_CREDITS') {
|
|
126
|
+
reason = 'insufficient_credits';
|
|
127
|
+
}
|
|
128
|
+
else if (input.code === 'FEATURE_GATED') {
|
|
129
|
+
const refusal = gateRefusalOf(input.details.reason);
|
|
130
|
+
if (!refusal)
|
|
131
|
+
return undefined;
|
|
132
|
+
reason = refusal;
|
|
133
|
+
}
|
|
134
|
+
else {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
const { pricing, billing } = resolveBillingLinks({
|
|
138
|
+
apiUrl: input.apiUrl,
|
|
139
|
+
billingUrl: typeof input.details.billingUrl === 'string' ? input.details.billingUrl : undefined,
|
|
140
|
+
orgId: input.details.orgId,
|
|
141
|
+
nextAction: input.serverNextAction ?? input.nextAction,
|
|
142
|
+
message: input.message,
|
|
143
|
+
});
|
|
144
|
+
// The server's message says why (which feature, which limit, why the
|
|
145
|
+
// workspace is paused) and its nextAction says what to do. These fallbacks
|
|
146
|
+
// only cover a response that arrived without a nextAction, and follow the
|
|
147
|
+
// backend's own CLI wording rather than guessing a cause.
|
|
148
|
+
let nextAction = input.nextAction;
|
|
149
|
+
if (!nextAction) {
|
|
150
|
+
switch (reason) {
|
|
151
|
+
case 'not_entitled':
|
|
152
|
+
nextAction = `Upgrade at ${billing} (plans: ${pricing}), then retry.`;
|
|
153
|
+
break;
|
|
154
|
+
case 'limit_exceeded':
|
|
155
|
+
nextAction = `Delete one and retry, or upgrade at ${billing} for a higher limit.`;
|
|
156
|
+
break;
|
|
157
|
+
case 'paused':
|
|
158
|
+
nextAction = `See ${billing} to resume this workspace, then retry.`;
|
|
159
|
+
break;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// Add only the links the printed message and nextAction don't already carry.
|
|
163
|
+
const printed = `${input.message}\n${nextAction}`;
|
|
164
|
+
const lines = [];
|
|
165
|
+
if (!printed.includes(pricing))
|
|
166
|
+
lines.push(fact('upgrade', pricing));
|
|
167
|
+
if (!printed.includes(billing))
|
|
168
|
+
lines.push(fact('billing', billing));
|
|
169
|
+
return { reason, links: { pricing, billing }, nextAction, lines };
|
|
170
|
+
}
|
|
171
|
+
//# sourceMappingURL=billing-refusal.js.map
|
package/dist/lib/bundle.d.ts
CHANGED
|
@@ -33,6 +33,7 @@
|
|
|
33
33
|
* when the agent re-runs. M3 may add resume.
|
|
34
34
|
*/
|
|
35
35
|
import type { CliFailureContext } from '../commands/test.js';
|
|
36
|
+
import { type ShutdownHandle } from './interrupt.js';
|
|
36
37
|
import type { FetchImpl } from './http.js';
|
|
37
38
|
/** Schema version stamped into `meta.json`. Bumps with the contract. */
|
|
38
39
|
export declare const BUNDLE_SCHEMA_VERSION: "cli-v1";
|
|
@@ -90,6 +91,8 @@ export interface WriteBundleOptions {
|
|
|
90
91
|
failedOnly: boolean;
|
|
91
92
|
/** Custom fetch impl for tests. Defaults to global `fetch`. */
|
|
92
93
|
fetchImpl?: FetchImpl;
|
|
94
|
+
shutdownSignal?: AbortSignal;
|
|
95
|
+
shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
|
|
93
96
|
/** Server requestId to embed in `.partial` on failure. */
|
|
94
97
|
requestId?: string;
|
|
95
98
|
}
|
|
@@ -226,4 +229,6 @@ export declare function commitBundle(tmpDir: string, dir: string, files: Readonl
|
|
|
226
229
|
*/
|
|
227
230
|
export declare function streamUrlToFile(url: string, filePath: string, fetchImpl: FetchImpl, deps?: {
|
|
228
231
|
sleep?: (ms: number) => Promise<void>;
|
|
232
|
+
shutdownSignal?: AbortSignal;
|
|
233
|
+
shutdown?: Pick<ShutdownHandle, 'runCriticalOperation'>;
|
|
229
234
|
}): Promise<void>;
|
package/dist/lib/bundle.js
CHANGED
|
@@ -37,7 +37,9 @@ import { mkdir, mkdtemp, readdir, rename, rm, stat, unlink, writeFile } from 'no
|
|
|
37
37
|
import { pipeline } from 'node:stream/promises';
|
|
38
38
|
import { createWriteStream } from 'node:fs';
|
|
39
39
|
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
40
|
-
import { ApiError, TransportError, localValidationError } from './errors.js';
|
|
40
|
+
import { ApiError, InterruptError, TransportError, localValidationError } from './errors.js';
|
|
41
|
+
import { globalShutdown } from './interrupt.js';
|
|
42
|
+
import { defaultSleep, sleepUnlessInterrupted } from './poll-support.js';
|
|
41
43
|
import { requireEnum } from './validate.js';
|
|
42
44
|
/** Schema version stamped into `meta.json`. Bumps with the contract. */
|
|
43
45
|
export const BUNDLE_SCHEMA_VERSION = 'cli-v1';
|
|
@@ -321,6 +323,10 @@ export async function writeBundle(ctx, options) {
|
|
|
321
323
|
assertContextIntegrity(filtered, requestId);
|
|
322
324
|
const dir = resolveBundleDir(options.dir);
|
|
323
325
|
const fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
326
|
+
const downloadDeps = {
|
|
327
|
+
shutdownSignal: options.shutdownSignal,
|
|
328
|
+
shutdown: options.shutdown,
|
|
329
|
+
};
|
|
324
330
|
const meta = buildMeta(filtered);
|
|
325
331
|
const codeExt = pickCodeExtension(filtered.code.language, filtered.code.framework);
|
|
326
332
|
await mkdir(dir, { recursive: true });
|
|
@@ -343,7 +349,7 @@ export async function writeBundle(ctx, options) {
|
|
|
343
349
|
// bodies), stream the URL into the file rather than embedding
|
|
344
350
|
// the URL in code.<ext>. M2's backend hasn't shipped the
|
|
345
351
|
// >=100KB branch yet, but the contract supports it.
|
|
346
|
-
await streamUrlToFile(filtered.code.code, join(tmpDir, codeFile), fetchImpl);
|
|
352
|
+
await streamUrlToFile(filtered.code.code, join(tmpDir, codeFile), fetchImpl, downloadDeps);
|
|
347
353
|
}
|
|
348
354
|
else {
|
|
349
355
|
await writeFile(join(tmpDir, codeFile), filtered.code.code, 'utf8');
|
|
@@ -356,11 +362,11 @@ export async function writeBundle(ctx, options) {
|
|
|
356
362
|
// (some runs ship `.webm`, not `.mp4`).
|
|
357
363
|
if (filtered.result.videoUrl) {
|
|
358
364
|
const videoFile = `video.${pickVideoExtension(filtered.result.videoUrl)}`;
|
|
359
|
-
await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, videoFile), fetchImpl);
|
|
365
|
+
await streamUrlToFile(filtered.result.videoUrl, join(tmpDir, videoFile), fetchImpl, downloadDeps);
|
|
360
366
|
filesWritten.push(videoFile);
|
|
361
367
|
}
|
|
362
368
|
for (const step of filtered.steps) {
|
|
363
|
-
await writeStepArtifacts(step, filtered.failure.evidence, stepsTmpDir, fetchImpl, filesWritten);
|
|
369
|
+
await writeStepArtifacts(step, filtered.failure.evidence, stepsTmpDir, fetchImpl, filesWritten, downloadDeps);
|
|
364
370
|
}
|
|
365
371
|
// meta.json LAST. Its presence is the sentinel that the bundle
|
|
366
372
|
// is complete. An agent that opens <dir> and finds meta.json can
|
|
@@ -521,7 +527,7 @@ async function dirExists(path) {
|
|
|
521
527
|
* console — for that step). The evidence-json file is omitted when
|
|
522
528
|
* there's nothing to put in it; it's NOT a placeholder.
|
|
523
529
|
*/
|
|
524
|
-
async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, filesWritten) {
|
|
530
|
+
async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, filesWritten, downloadDeps) {
|
|
525
531
|
// stepIndex comes straight from the response and is used to build the
|
|
526
532
|
// filename — reject anything that isn't a real index before composing a path.
|
|
527
533
|
if (!Number.isInteger(step.stepIndex) || step.stepIndex < 0) {
|
|
@@ -530,12 +536,12 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
|
|
|
530
536
|
const prefix = stepFilenamePrefix(step.stepIndex);
|
|
531
537
|
if (step.screenshotUrl) {
|
|
532
538
|
const file = `${prefix}-screenshot.png`;
|
|
533
|
-
await streamUrlToFile(step.screenshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl);
|
|
539
|
+
await streamUrlToFile(step.screenshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl, downloadDeps);
|
|
534
540
|
filesWritten.push(`steps/${file}`);
|
|
535
541
|
}
|
|
536
542
|
if (step.htmlSnapshotUrl) {
|
|
537
543
|
const file = `${prefix}-snapshot.html`;
|
|
538
|
-
await streamUrlToFile(step.htmlSnapshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl);
|
|
544
|
+
await streamUrlToFile(step.htmlSnapshotUrl, assertNoEscape(stepsTmpDir, file), fetchImpl, downloadDeps);
|
|
539
545
|
filesWritten.push(`steps/${file}`);
|
|
540
546
|
}
|
|
541
547
|
// Evidence sidecar artifacts. Per codex round-1 P2: the bundle must
|
|
@@ -583,7 +589,7 @@ async function writeStepArtifacts(step, allEvidence, stepsTmpDir, fetchImpl, fil
|
|
|
583
589
|
}
|
|
584
590
|
const ext = sidecarExtension(entry.kind);
|
|
585
591
|
const filename = `${prefix}-${entry.kind}-${i}.${ext}`;
|
|
586
|
-
await streamUrlToFile(entry.url, assertNoEscape(stepsTmpDir, filename), fetchImpl);
|
|
592
|
+
await streamUrlToFile(entry.url, assertNoEscape(stepsTmpDir, filename), fetchImpl, downloadDeps);
|
|
587
593
|
filesWritten.push(`steps/${filename}`);
|
|
588
594
|
return {
|
|
589
595
|
kind: entry.kind,
|
|
@@ -628,21 +634,31 @@ function sidecarExtension(kind) {
|
|
|
628
634
|
* Presigned URLs are valid for 15 minutes, so retries are safe.
|
|
629
635
|
*/
|
|
630
636
|
export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
|
|
631
|
-
const
|
|
637
|
+
const shutdownSignal = deps?.shutdownSignal ?? globalShutdown.signal;
|
|
638
|
+
const shutdown = deps?.shutdown ?? globalShutdown;
|
|
639
|
+
return shutdown.runCriticalOperation(() => streamUrlToFileTracked(url, filePath, fetchImpl, deps?.sleep ?? defaultSleep, shutdownSignal));
|
|
640
|
+
}
|
|
641
|
+
async function streamUrlToFileTracked(url, filePath, fetchImpl, sleepFn, shutdownSignal) {
|
|
632
642
|
const artifactUrl = redactArtifactUrlForDetails(url);
|
|
633
643
|
for (let attempt = 1; attempt <= STREAM_URL_MAX_RETRIES; attempt++) {
|
|
644
|
+
if (shutdownSignal.aborted)
|
|
645
|
+
throw shutdownSignal.reason;
|
|
634
646
|
let response;
|
|
635
647
|
try {
|
|
636
|
-
response = await fetchImpl(url, { redirect: 'error' });
|
|
648
|
+
response = await fetchImpl(url, { redirect: 'error', signal: shutdownSignal });
|
|
637
649
|
}
|
|
638
650
|
catch (err) {
|
|
651
|
+
if (err instanceof InterruptError || shutdownSignal.aborted)
|
|
652
|
+
throw shutdownSignal.reason ?? err;
|
|
639
653
|
const message = err instanceof Error ? err.message : String(err);
|
|
640
654
|
if (attempt < STREAM_URL_MAX_RETRIES) {
|
|
641
|
-
await sleepFn
|
|
655
|
+
await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
|
|
642
656
|
continue;
|
|
643
657
|
}
|
|
644
658
|
throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
|
|
645
659
|
}
|
|
660
|
+
if (shutdownSignal.aborted)
|
|
661
|
+
throw shutdownSignal.reason;
|
|
646
662
|
if (!response.ok) {
|
|
647
663
|
// Non-2xx: the URL itself is bad (expired, unauthorized, not found).
|
|
648
664
|
// Retrying the same URL won't help — surface immediately.
|
|
@@ -665,12 +681,20 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
|
|
|
665
681
|
try {
|
|
666
682
|
const buffer = Buffer.from(await response.arrayBuffer());
|
|
667
683
|
await writeFile(filePath, buffer);
|
|
684
|
+
if (shutdownSignal.aborted) {
|
|
685
|
+
await rm(filePath, { force: true }).catch(() => undefined);
|
|
686
|
+
throw shutdownSignal.reason;
|
|
687
|
+
}
|
|
668
688
|
return;
|
|
669
689
|
}
|
|
670
690
|
catch (err) {
|
|
691
|
+
if (err instanceof InterruptError || shutdownSignal.aborted) {
|
|
692
|
+
await rm(filePath, { force: true }).catch(() => undefined);
|
|
693
|
+
throw shutdownSignal.reason ?? err;
|
|
694
|
+
}
|
|
671
695
|
const message = err instanceof Error ? err.message : String(err);
|
|
672
696
|
if (attempt < STREAM_URL_MAX_RETRIES) {
|
|
673
|
-
await sleepFn
|
|
697
|
+
await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
|
|
674
698
|
continue;
|
|
675
699
|
}
|
|
676
700
|
throw new TransportError(`Failed to download presigned URL ${artifactUrl}: ${message}`);
|
|
@@ -688,12 +712,18 @@ export async function streamUrlToFile(url, filePath, fetchImpl, deps) {
|
|
|
688
712
|
const { Readable } = await import('node:stream');
|
|
689
713
|
const nodeStream = Readable.fromWeb(webBody);
|
|
690
714
|
await pipeline(nodeStream, fileSink);
|
|
715
|
+
if (shutdownSignal.aborted)
|
|
716
|
+
throw shutdownSignal.reason;
|
|
691
717
|
return;
|
|
692
718
|
}
|
|
693
719
|
catch (err) {
|
|
720
|
+
if (err instanceof InterruptError || shutdownSignal.aborted) {
|
|
721
|
+
await rm(filePath, { force: true }).catch(() => undefined);
|
|
722
|
+
throw shutdownSignal.reason ?? err;
|
|
723
|
+
}
|
|
694
724
|
const message = err instanceof Error ? err.message : String(err);
|
|
695
725
|
if (attempt < STREAM_URL_MAX_RETRIES) {
|
|
696
|
-
await sleepFn
|
|
726
|
+
await sleepUnlessInterrupted(sleepFn, STREAM_URL_RETRY_DELAY_MS, shutdownSignal);
|
|
697
727
|
continue;
|
|
698
728
|
}
|
|
699
729
|
throw new TransportError(`Failed mid-download of ${artifactUrl}: ${message}`);
|