@computesdk/cli 2.3.1 → 2.3.2

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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/providers.ts","../src/actions.ts","../src/actions-client.ts","../src/market.ts","../src/sandboxes.ts"],"sourcesContent":["/**\n * @computesdk/cli\n *\n * ComputeSDK CLI — platform commands and the benchmarks CLI.\n *\n * Usage:\n * compute login # OAuth device login (benchsdk-cli)\n * compute logout # clear stored credentials\n * compute providers # list configured providers\n * compute actions … # Actions API\n * compute market … # market sell-side commands\n * compute sandboxes … # platform sandbox control plane\n * compute bench … # benchmarks platform CLI\n */\n\nimport 'dotenv/config';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { getProviderStatus } from './providers.js';\nimport { registerActionsCommands } from './actions.js';\nimport { registerMarketCommands } from './market.js';\nimport { registerSandboxesCommands } from './sandboxes.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst packageJson = JSON.parse(\n readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')\n);\n\n// Detect if running from dev workspace\nconst isDevBuild = import.meta.url.includes('worktrees') ||\n import.meta.url.includes('/packages/cli/');\nconst VERSION = isDevBuild ? `${packageJson.version}-dev` : packageJson.version;\n\n// stdout closed early (`compute … | jq -r`, `| head`): exit quietly — the\n// consumer already has what it wanted. stderr closed: swallow the write\n// error but let the command finish, so a failed command keeps its nonzero\n// exit instead of masking as success. Other stream errors still throw.\nprocess.stdout.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE') process.exit(0);\n throw err;\n});\nprocess.stderr.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE') return;\n throw err;\n});\n\nconst program = new Command();\n\nprogram\n .name('compute')\n .description('ComputeSDK CLI')\n .version(VERSION)\n .enablePositionalOptions()\n .passThroughOptions();\n\nfunction envBaseUrl(): string | undefined {\n return process.env.COMPUTE_PLATFORM_URL ?? process.env.BENCHMARKS_PLATFORM_URL;\n}\n\nasync function benchAuth(opts: { baseUrl?: string } = {}) {\n const { resolveAuth } = await import('@benchsdk/cli');\n return resolveAuth({ baseUrl: opts.baseUrl ?? envBaseUrl() });\n}\n\nasync function printSessionLine(options?: { baseUrl?: string }): Promise<void> {\n try {\n const { getMe } = await import('@benchsdk/cli');\n const me = await getMe(await benchAuth({ baseUrl: options?.baseUrl }));\n const active = me.organizations.find((o) => o.id === me.activeOrganizationId);\n const who = me.user.email ?? me.user.name ?? me.user.id;\n if (active) {\n p.log.success(\n `Logged in as ${who} — active org: ${active.slug}. Change with \\`compute org use <slug>\\`.`,\n );\n } else {\n p.log.success(`Logged in as ${who} — no active org`);\n }\n } catch {\n p.log.warn('Logged in, but could not fetch session info.');\n }\n}\n\n// `compute login` and `bench auth login` are the same login: the\n// `benchsdk-cli` OAuth client with the full first-party scope set, stored\n// once in ~/.benchsdk/credentials.json.\nasync function runLogin(options?: { baseUrl?: string }): Promise<void> {\n const { oauthLogin } = await import('@benchsdk/cli');\n await oauthLogin({\n baseUrl: options?.baseUrl ?? envBaseUrl(),\n });\n}\n\nasync function runLogout(): Promise<void> {\n const { clearCredentials } = await import('@benchsdk/cli');\n await clearCredentials();\n}\n\n// ─── Default action: Show help ─────────────────────────────────────────────\n\nprogram\n .option('--login', 'force re-authentication')\n .option('--logout', 'clear stored credentials')\n .option('--org <slug>', 'organization slug override for this invocation (or $COMPUTE_ORG)')\n .action(async (opts) => {\n if (opts.logout) {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await runLogout();\n p.log.success('Logged out. Stored credentials removed.');\n p.outro(pc.green('Done!'));\n process.exit(0);\n }\n\n if (opts.login) {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await runLogin();\n await printSessionLine();\n p.outro(pc.green('Authenticated!'));\n process.exit(0);\n }\n\n // Show help by default\n program.help();\n });\n\n// `compute --org <slug> <group> …` (leading position): forward to the env the\n// client layer reads. A trailing --org on the subcommand still wins —\n// resolveActionsAuth reads opts.org before COMPUTE_ORG.\nprogram.hook('preAction', (thisCommand) => {\n const org = thisCommand.opts().org;\n if (org) process.env.COMPUTE_ORG = org;\n});\n\n// ─── providers ───────────────────────────────────────────────────────────────\n\nprogram\n .command('providers')\n .description('List all providers and their configuration status')\n .action(async () => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n const statuses = getProviderStatus();\n\n console.log();\n for (const status of statuses) {\n const icon = status.ready ? pc.green('●') : pc.gray('○');\n const name = status.ready ? pc.white(status.name) : pc.gray(status.name);\n const detail = status.ready\n ? pc.green('ready')\n : pc.gray(`missing: ${status.missing.join(', ')}`);\n console.log(` ${icon} ${name} ${detail}`);\n }\n console.log();\n });\n\n// ─── login / logout ──────────────────────────────────────────────────────────\n\nprogram\n .command('login')\n .description('Authenticate with ComputeSDK (OAuth device flow)')\n .option('--base-url <url>', 'platform URL to authenticate against')\n .action(async (opts) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await runLogin({ baseUrl: opts.baseUrl });\n await printSessionLine({ baseUrl: opts.baseUrl });\n p.outro(pc.green('Authenticated!'));\n });\n\nprogram\n .command('logout')\n .description('Clear stored credentials')\n .option('--json', 'print machine-readable JSON')\n .action(async (opts) => {\n await runLogout();\n if (opts.json) {\n console.log(JSON.stringify({ loggedOut: true }, null, 2));\n return;\n }\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n p.log.success('Logged out. Stored credentials removed.');\n p.outro(pc.green('Done!'));\n });\n\n// ─── org ────────────────────────────────────────────────────────────────────\n// Mirrors `bench org` — same credential store and /api/v1/organizations calls\n// through @benchsdk/cli. The active org is per user+client, shared by every\n// CLI on every machine.\n\nasync function printWhoami(options: { json?: boolean; baseUrl?: string } = {}): Promise<void> {\n const { getMe } = await import('@benchsdk/cli');\n const me = await getMe(await benchAuth({ baseUrl: options.baseUrl }));\n if (options.json) {\n console.log(JSON.stringify(me, null, 2));\n return;\n }\n const active = me.organizations.find((o) => o.id === me.activeOrganizationId);\n console.log(me.user.email ?? me.user.name ?? me.user.id);\n console.log(\n `active org: ${active ? `${active.slug} (${active.id})` : '—'}${me.organizations.length > 1 ? ' — change with `compute org use <slug>`' : ''}`,\n );\n}\n\nconst org = program.command('org').description('Manage the active organization');\n\norg\n .command('list')\n .description('List your organizations')\n .option('--json', 'print machine-readable JSON')\n .action(async (opts) => {\n const { listOrganizations, getMe } = await import('@benchsdk/cli');\n const auth = await benchAuth();\n const [organizations, me] = await Promise.all([listOrganizations(auth), getMe(auth)]);\n if (opts.json) {\n console.log(JSON.stringify(organizations, null, 2));\n return;\n }\n for (const o of organizations) {\n const marker = o.id === me.activeOrganizationId ? pc.green('*') : ' ';\n console.log(`${marker} ${pc.cyan(o.slug)} ${o.name ?? ''} ${pc.dim(o.id)}`);\n }\n });\n\norg\n .command('use <slug>')\n .description('Set the active organization (persisted to the stored login)')\n .action(async (slug: string) => {\n const { loadCredentials, saveCredentials, createApiClient, setActiveOrganization } =\n await import('@benchsdk/cli');\n const credentials = (await loadCredentials()) ?? {};\n const { auth } = await createApiClient({ baseUrl: envBaseUrl() });\n const result = await setActiveOrganization(auth, slug);\n if (!result.organization) {\n throw new Error(`Could not set active organization to ${slug}`);\n }\n await saveCredentials({\n ...credentials,\n baseUrl: auth.baseUrl,\n // An API-key login must not be rewritten as an OAuth one — keep its\n // key and kind, and only stamp token fields when this auth actually\n // is a token session.\n ...(auth.token\n ? {\n token: auth.token,\n refreshToken: auth.refreshToken,\n tokenExpiresAt: auth.tokenExpiresAt,\n refreshExpiresAt: auth.refreshExpiresAt,\n kind: 'oauth' as const,\n }\n : {}),\n orgSlug: result.organization.slug,\n orgId: result.organization.id,\n });\n console.log(`Active organization set to ${result.organization.slug} (${result.organization.id})`);\n });\n\norg\n .command('current')\n .description('Show the current user and active organization')\n .option('--base-url <url>', 'platform URL to query')\n .option('--json', 'print machine-readable JSON')\n .action((opts) => printWhoami(opts));\n\nprogram\n .command('whoami')\n .description('Show the current user and active organization')\n .option('--base-url <url>', 'platform URL to query')\n .option('--json', 'print machine-readable JSON')\n .action((opts) => printWhoami(opts));\n\n// ─── actions ─────────────────────────────────────────────────────────────────\n\nregisterActionsCommands(program);\n\n// ─── market ──────────────────────────────────────────────────────────────────\n// `compute market` is the sell side of the compute market — same platform\n// API and auth as `compute actions`, for orgs flagged `market_provider`.\n\nregisterMarketCommands(program);\n\n// ─── sandboxes ───────────────────────────────────────────────────────────────\n// `compute sandboxes` drives /api/v1/sandboxes — the customer-facing sandbox\n// control plane (create/exec/processes/files/urls). Same auth as actions.\n\nregisterSandboxesCommands(program);\n\n// ─── bench ───────────────────────────────────────────────────────────────────\n// `compute bench` is the benchmarks-platform CLI (@benchsdk/runner's `bench`\n// binary) folded under compute: run/check/auth/org/benchmarks/runs/results/\n// iterations/artifacts/logs/export all dispatch through it.\n\nprogram\n .command('bench')\n .description('Benchmarks platform CLI (run, auth, org, benchmarks, runs, results, artifacts, export, ...)')\n .allowUnknownOption()\n .helpOption(false)\n .action(() => {\n // Never reached: bench args are dispatched pre-parse below.\n });\n\n// ─── Run ─────────────────────────────────────────────────────────────────────\n\n// Bench args are opaque to commander (its own --flags, `--` separators, file\n// paths), so they dispatch before parsing. `@benchsdk/runner`'s run() owns the\n// process — it exits itself after dispatch.\nasync function main() {\n if (process.argv[2] === 'bench' || process.argv[2] === 'benchmark') {\n const { run: benchRun } = await import('@benchsdk/runner');\n await benchRun(process.argv.slice(3));\n return;\n }\n await program.parseAsync(process.argv);\n}\n\nmain().catch((error) => {\n console.error(pc.red(`\\nError: ${error.message}`));\n process.exit(1);\n});\n","/**\n * Provider detection and validation\n *\n * Detection is local: each provider declares the env vars its credentials come\n * from, and \"ready\" means all of them are set. This used to import helpers from\n * `computesdk` that the package no longer exports, which made every `compute`\n * invocation fail at module load.\n */\n\ninterface ProviderEnvSpec {\n /**\n * Alternative complete credential sets — the provider is usable when every\n * var in any one set is present (e.g. Vercel: the traditional tuple OR\n * VERCEL_OIDC_TOKEN; Namespace: NSC_TOKEN or NSC_TOKEN_FILE).\n */\n authOptions: string[][];\n /**\n * Maps each env var to the provider's nested config key (the field names in\n * the provider package's config interface, e.g. `apiKey`, `tokenId`).\n */\n configKeys: Record<string, string>;\n}\n\nconst PROVIDER_ENV: Record<string, ProviderEnvSpec> = {\n e2b: { authOptions: [['E2B_API_KEY']], configKeys: { E2B_API_KEY: 'apiKey' } },\n railway: { authOptions: [['RAILWAY_API_TOKEN']], configKeys: { RAILWAY_API_TOKEN: 'token' } },\n modal: {\n authOptions: [['MODAL_TOKEN_ID', 'MODAL_TOKEN_SECRET']],\n configKeys: { MODAL_TOKEN_ID: 'tokenId', MODAL_TOKEN_SECRET: 'tokenSecret' },\n },\n vercel: {\n authOptions: [['VERCEL_TOKEN', 'VERCEL_TEAM_ID', 'VERCEL_PROJECT_ID'], ['VERCEL_OIDC_TOKEN']],\n configKeys: {\n VERCEL_TOKEN: 'token',\n VERCEL_TEAM_ID: 'teamId',\n VERCEL_PROJECT_ID: 'projectId',\n },\n },\n daytona: { authOptions: [['DAYTONA_API_KEY']], configKeys: { DAYTONA_API_KEY: 'apiKey' } },\n namespace: {\n authOptions: [['NSC_TOKEN'], ['NSC_TOKEN_FILE']],\n configKeys: { NSC_TOKEN: 'token', NSC_TOKEN_FILE: 'tokenFile' },\n },\n blaxel: {\n authOptions: [['BL_API_KEY', 'BL_WORKSPACE']],\n configKeys: { BL_API_KEY: 'apiKey', BL_WORKSPACE: 'workspace' },\n },\n codesandbox: { authOptions: [['CSB_API_KEY']], configKeys: { CSB_API_KEY: 'apiKey' } },\n render: { authOptions: [['RENDER_API_KEY']], configKeys: { RENDER_API_KEY: 'apiKey' } },\n};\n\nconst PROVIDER_NAMES = Object.keys(PROVIDER_ENV);\n\n/** Missing vars from whichever auth option is closest to complete. */\nfunction missingEnvVars(provider: string): string[] {\n const spec = PROVIDER_ENV[provider];\n if (!spec) return [];\n let best: string[] | null = null;\n for (const option of spec.authOptions) {\n const missing = option.filter((name) => !process.env[name]);\n if (missing.length === 0) return [];\n if (!best || missing.length < best.length) best = missing;\n }\n return best ?? [];\n}\n\nfunction isProviderAuthComplete(provider: string): boolean {\n return missingEnvVars(provider).length === 0;\n}\n\n/**\n * Provider status info\n */\nexport interface ProviderStatus {\n name: string;\n ready: boolean;\n missing: string[];\n}\n\n/**\n * Detect all available providers from environment variables\n */\nexport function detectAvailableProviders(): string[] {\n const available: string[] = [];\n\n for (const provider of PROVIDER_NAMES) {\n if (isProviderAuthComplete(provider)) {\n available.push(provider);\n }\n }\n\n return available;\n}\n\n/**\n * Get status of all providers\n */\nexport function getProviderStatus(): ProviderStatus[] {\n const statuses: ProviderStatus[] = [];\n\n for (const provider of PROVIDER_NAMES) {\n statuses.push({\n name: provider,\n ready: isProviderAuthComplete(provider),\n missing: missingEnvVars(provider),\n });\n }\n\n return statuses;\n}\n","/** A file/dir name reduced to a safe basename — strips `..` and separators. */\nfunction sanitizePathPart(name: string): string {\n const base = basename(name);\n if (base === '' || base === '.' || base === '..') return 'artifact';\n return base;\n}\n\n/**\n * `compute actions` — drive the benchmarks-platform Actions API end-to-end:\n * dispatch workflows, watch runs, inspect run context, stream logs,\n * manage artifacts.\n *\n * Auth: --api-key, else COMPUTE_API_KEY, else the platform OAuth credentials\n * `compute login` (or `compute bench auth login`) stored (refreshed silently,\n * never prompts). --base-url overrides the\n * https://platform.computesdk.com default; a non-computesdk host needs\n * --allow-untrusted-host and an explicit key — stored OAuth is never sent there.\n * Every subcommand takes --json for machine-readable output — on success the\n * data, on failure the `{ ok: false, error: {...} }` envelope on stderr.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { basename, join } from 'path';\nimport {\n ActionsApiError,\n ActionsCliError,\n ActionsClient,\n encodeWatchCursor,\n isTrustedActionsHost,\n resolveActionsAuth,\n toErrorEnvelope,\n type ActionsAuth,\n type CiArtifactListItem,\n type CiJob,\n type CiLogSlice,\n type CiProviderInfo,\n type CiProviderKeyResponse,\n type CiProvidersResponse,\n type CiRepo,\n type CiRepoConnectResponse,\n type CiRepoPatchResponse,\n type CiReposResponse,\n type CiRun,\n type CiRunHistory,\n type CiRunInspection,\n type CiRunSummary,\n type CiVaultDeleteResponse,\n type CiVaultItem,\n type CiVaultKind,\n type CiVaultListResponse,\n type CiVaultRevealResponse,\n type CiVaultSaveResponse,\n type CiWorkflow,\n} from './actions-client.js';\n\n/** The jobs inside a `/state` response — a subset of CiJob, no name/steps. */\ninterface CiLiveStateJob {\n id: string;\n state: CiJob['state'];\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n placementAttempts: CiJob['placementAttempts'];\n}\n\nexport type JsonOpts = { json?: boolean };\n\nexport interface CommonOpts extends JsonOpts {\n apiKey?: string;\n baseUrl?: string;\n allowUntrustedHost?: boolean;\n /** One-off org override sent as X-Org-Slug (or set $COMPUTE_ORG). */\n org?: string;\n}\n\n/** The platform API client behind both `compute actions` and `compute market`. */\nexport async function client(opts: CommonOpts): Promise<ActionsClient> {\n return new ActionsClient(await resolveActionsAuth(opts));\n}\n\n/**\n * Commands that send or read a local secret value (vault set/get, market\n * credential connect) only ever talk to a trusted host: --allow-untrusted-host\n * opts an explicit API key into a host, not the secrets themselves.\n */\nexport function assertSecretValueHost(auth: ActionsAuth, what: string): void {\n if (!isTrustedActionsHost(auth.baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host',\n `Refusing to send or read ${what} at ${auth.baseUrl} — only computesdk.com and localhost hosts are allowed, even with --allow-untrusted-host.`,\n );\n }\n}\n\nexport function assertVaultValueHost(auth: ActionsAuth): void {\n assertSecretValueHost(auth, 'vault values');\n}\n\n/** A client for commands carrying a local secret value — trusted hosts only. */\nexport async function secretValueClient(opts: CommonOpts, what: string): Promise<ActionsClient> {\n const auth = await resolveActionsAuth(opts);\n assertSecretValueHost(auth, what);\n return new ActionsClient(auth);\n}\n\nasync function vaultValueClient(opts: CommonOpts): Promise<ActionsClient> {\n return secretValueClient(opts, 'vault values');\n}\n\n/** Print `data` as JSON when --json was passed; otherwise call `render`. */\nexport function output<T>(opts: JsonOpts, data: T, render: (data: T) => void): void {\n if (opts.json) {\n process.stdout.write(JSON.stringify(data, null, 2) + '\\n');\n } else {\n render(data);\n }\n}\n\n/** The run's job list: full detail when the runs detail route exists, else the\n * live-state route (which predates it and lists jobs without names). */\nasync function listRunJobs(c: ActionsClient, runId: string): Promise<CiJob[]> {\n try {\n const run = await c.get<CiRun>(`/api/v1/actions/runs/${runId}`);\n return run.jobs;\n } catch (e) {\n if (!(e instanceof ActionsApiError) || e.status !== 404) throw e;\n }\n const state = await c.get<{ jobs: CiLiveStateJob[] }>(`/api/v1/actions/runs/${runId}/state`);\n return state.jobs.map((j) => ({\n id: j.id,\n name: j.id.slice(0, 8), // the live-state route does not carry job names\n needs: [],\n workflowJobId: null,\n matrix: null,\n state: j.state,\n provider: j.provider,\n region: j.region,\n sandboxId: j.sandboxId,\n placementAttempts: j.placementAttempts,\n durationMs: null,\n steps: [],\n }));\n}\n\n/** The run's failure digest; null when the summary cannot be fetched. */\nasync function fetchRunSummary(c: ActionsClient, runId: string): Promise<CiRunSummary | null> {\n try {\n return await c.get<CiRunSummary>(`/api/v1/actions/runs/${runId}/summary`);\n } catch (e) {\n // The digest rides along with `actions run`; a deployment without the\n // route or a summary error must not hide the run detail itself. The\n // `summary` command fetches directly so its own errors still surface.\n if (!(e instanceof ActionsApiError && e.status === 404)) {\n console.error(\n pc.dim(`summary unavailable: ${e instanceof Error ? e.message : String(e)}`),\n );\n }\n return null;\n }\n}\n\n/**\n * Report an error and exit 1. With --json the stderr line is the stable\n * envelope from `toErrorEnvelope` (stdout stays empty, so a consumer can parse\n * either stream without guessing); otherwise a one-line human message.\n */\nexport function fail(error: unknown, opts: JsonOpts = {}): never {\n if (opts.json) {\n process.stderr.write(JSON.stringify(toErrorEnvelope(error)) + '\\n');\n } else if (error instanceof ActionsApiError) {\n console.error(pc.red(`Error (${error.status}): ${error.message}`));\n } else {\n console.error(pc.red(`Error: ${error instanceof Error ? error.message : String(error)}`));\n }\n process.exit(1);\n}\n\n/**\n * Commander's own usage errors (unknown option, missing required option or\n * argument) are raised before any action runs, so `fail` never sees them.\n * Route them through the same envelope when --json is among the raw args.\n */\nexport function usageErrorOutput(str: string, write: (str: string) => void, argv: string[] = process.argv): void {\n if (argv.includes('--json')) {\n const message = str.replace(/^error:\\s*/i, '').trim();\n write(JSON.stringify(toErrorEnvelope(new ActionsCliError('invalid_argument', message))) + '\\n');\n } else {\n write(str);\n }\n}\n\n// ─── Formatting (pure, exported for tests) ──────────────────────────────────\n\nexport function formatDuration(ms: number | null | undefined): string {\n if (ms === null || ms === undefined) return '-';\n if (ms < 1000) return `${ms}ms`;\n const s = Math.round(ms / 1000);\n if (s < 60) return `${s}s`;\n const m = Math.floor(s / 60);\n if (m < 60) return `${m}m${s % 60}s`;\n const h = Math.floor(m / 60);\n return `${h}h${m % 60}m`;\n}\n\nexport function shortSha(sha: string): string {\n return sha.slice(0, 8);\n}\n\nexport function conclusionLabel(conclusion: string): string {\n switch (conclusion) {\n case 'passed': return pc.green('passed');\n case 'failed': return pc.red('failed');\n case 'running': return pc.yellow('running');\n case 'cancelled': return pc.gray('cancelled');\n case 'none': return pc.yellow('queued');\n default: return conclusion;\n }\n}\n\nexport function formatRunRow(run: CiRun): string {\n const num = run.runNumber === null ? '-' : `#${run.runNumber}`;\n return [\n run.id,\n pc.dim(num),\n run.workflowName || run.workflowPath,\n conclusionLabel(run.conclusion),\n pc.dim(`${run.repoFullName}@${run.ref}`),\n shortSha(run.headSha),\n formatDuration(run.durationMs),\n run.startedAt,\n ].join(' ');\n}\n\nexport function formatRunDetail(run: CiRun, runUrl?: string): string {\n const lines: string[] = [];\n lines.push(`${pc.bold(run.workflowName || run.workflowPath)} ${conclusionLabel(run.conclusion)}`);\n lines.push(pc.dim(`run ${run.id}${run.runNumber === null ? '' : ` #${run.runNumber}`}`));\n lines.push(`${run.repoFullName} @ ${run.ref} ${shortSha(run.headSha)} ${run.event}${run.prNumber ? ` PR #${run.prNumber}` : ''}`);\n lines.push(`title: ${run.title}`);\n lines.push(`started: ${run.startedAt} duration: ${formatDuration(run.durationMs)}`);\n if (run.cancellationReason) lines.push(`cancelled: ${run.cancellationReason}`);\n if (run.providerOverride) lines.push(`dispatched to: ${run.providerOverride}`);\n if (run.supersededByRunId) lines.push(`superseded by: ${run.supersededByRunId}`);\n if (runUrl) lines.push(`url: ${runUrl}`);\n if (run.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of run.jobs) {\n const placement = job.provider\n ? `${job.provider}${job.region ? `:${job.region}` : ''}`\n : '-';\n lines.push(` ${job.id} ${job.name} ${conclusionLabel(job.state)} ${placement} ${formatDuration(job.durationMs)}`);\n for (const attempt of job.placementAttempts) {\n lines.push(pc.dim(` placement failed on ${attempt.provider}${attempt.region ? `:${attempt.region}` : ''}: ${attempt.error}`));\n }\n for (const step of job.steps) {\n const exit = step.exitCode === null ? '' : ` (exit ${step.exitCode})`;\n lines.push(pc.dim(` ${step.name} ${step.state}${exit} ${formatDuration(step.durationMs)}`));\n }\n }\n }\n return lines.join('\\n');\n}\n\n/** `compute actions inspect` — the run plus everything that shaped it. */\nexport function formatRunInspection(run: CiRunInspection): string {\n const lines: string[] = [];\n lines.push(`${pc.bold('run')} ${conclusionLabel(run.conclusion)}${run.runNumber === null ? '' : ` #${run.runNumber}`}`);\n lines.push(pc.dim(run.id));\n lines.push(`${safeTerm(run.ref)} ${shortSha(run.headSha)} ${safeTerm(run.event)}`);\n lines.push(`queued: ${run.queuedAt} started: ${run.startedAt} finished: ${run.finishedAt}`);\n if (run.cancellationReason) lines.push(`cancelled: ${run.cancellationReason}`);\n if (run.supersededByRunId) lines.push(`superseded by: ${run.supersededByRunId}`);\n if (run.blockedReason) lines.push(pc.red(`blocked: ${safeTerm(run.blockedReason)}`));\n if (run.concurrencyGroup) lines.push(`concurrency: ${safeTerm(run.concurrencyGroup)}`);\n if (run.providerOverride) lines.push(`dispatched to: ${safeTerm(run.providerOverride)}`);\n if (run.definitionStale) {\n const parsed = run.workflowParsedFromSha ? shortSha(run.workflowParsedFromSha) : 'unknown';\n lines.push(pc.yellow(`definition: stored parse is from ${parsed}, not this head — context may be newer than the run`));\n }\n if (run.dispatchInputs && Object.keys(run.dispatchInputs).length > 0) {\n lines.push(`inputs: ${Object.entries(run.dispatchInputs).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(' ')}`);\n }\n if (run.secrets) {\n const names = run.secrets.names.length > 0 ? run.secrets.names.map(safeTerm).join(', ') : 'none';\n lines.push(`secrets (${run.secrets.access}${run.secrets.env ? ', exported to env' : ''}): ${names}`);\n }\n if (run.caches.length > 0) {\n lines.push('');\n lines.push(pc.bold('caches'));\n for (const cache of run.caches) {\n const action = [cache.restoredAt ? 'restored' : null, cache.savedAt ? 'saved' : null]\n .filter(Boolean)\n .join('+');\n lines.push(` ${safeTerm(cache.key)} ${pc.dim(`${action} ${safeTerm(cache.scopeRef)} ${cache.sizeBytes}B`)}`);\n }\n }\n if (run.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of run.jobs) {\n const placement = job.provider\n ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ''}`\n : '-';\n lines.push(` ${safeTerm(job.name)} ${conclusionLabel(job.state)} ${placement}`);\n lines.push(pc.dim(` ${job.id}`));\n if (job.runsOn.length > 0 || job.resolvedRunsOn !== null) {\n const resolved =\n job.resolvedRunsOn !== null && job.resolvedRunsOn.join(',') !== job.runsOn.join(',')\n ? ` → ${job.resolvedRunsOn.map(safeTerm).join(', ')}`\n : '';\n lines.push(` runs-on: ${job.runsOn.map(safeTerm).join(', ') || '(none)'}${resolved}`);\n }\n if (job.runsOnHasExpression) lines.push(pc.dim(' runs-on resolves at runtime (expression)'));\n if (job.container) lines.push(` container: ${safeTerm(job.container)}`);\n if (job.runnerImage) lines.push(` image: ${safeTerm(job.runnerImage)}`);\n if (job.placementHint) {\n lines.push(` pinned: ${safeTerm(job.placementHint.label)}`);\n }\n if (job.concurrencyGroup) {\n lines.push(` concurrency: ${safeTerm(job.concurrencyGroup)}${job.concurrencyCancelInProgress ? ' (cancel-in-progress)' : ''}`);\n }\n const overrides = [\n job.timeoutMinutes !== null ? `timeout ${job.timeoutMinutes}m` : null,\n job.fetchDepth !== null ? `fetch-depth ${job.fetchDepth}` : null,\n ].filter(Boolean);\n if (overrides.length > 0) lines.push(` ${overrides.join(' ')}`);\n if (job.matrix) {\n lines.push(` matrix: ${Object.entries(job.matrix).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(' ')}`);\n }\n if (job.failureReason) lines.push(pc.red(` failed: ${safeTerm(job.failureReason)}`));\n for (const attempt of job.placementAttempts) {\n lines.push(pc.dim(` placement failed on ${safeTerm(attempt.provider)}${attempt.region ? `:${safeTerm(attempt.region)}` : ''}: ${safeTerm(attempt.error)}`));\n }\n }\n }\n return lines.join('\\n');\n}\n\n/** The failure digest rendered for humans — shared by `run` and `summary`. */\nexport function formatRunSummary(summary: CiRunSummary): string {\n const lines: string[] = [];\n lines.push(pc.bold(`failures — run ${summary.runId} ${conclusionLabel(summary.conclusion)}`));\n if (summary.failures.length === 0) {\n lines.push(' no failed jobs');\n return lines.join('\\n');\n }\n for (const job of summary.failures) {\n const placement = job.provider\n ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ''}`\n : '-';\n lines.push(` ${job.id} ${safeTerm(job.name)} ${conclusionLabel(job.conclusion)} ${placement}`);\n if (job.failureReason) lines.push(pc.dim(` ${safeTerm(job.failureReason)}`));\n for (const step of job.failedSteps) {\n const exit = step.exitCode === null ? '' : ` (exit ${step.exitCode})`;\n lines.push(` step ${step.ordinal} ${safeTerm(step.name)}${exit}`);\n }\n if (job.excerpt) {\n const scope = job.excerpt.stepOrdinal === null ? 'job log' : `step ${job.excerpt.stepOrdinal}`;\n const cut = job.excerpt.truncated ? ', truncated' : '';\n lines.push(pc.dim(` ── ${scope} tail${cut} ──`));\n for (const line of job.excerpt.text.split('\\n')) lines.push(` ${safeTerm(line)}`);\n }\n }\n return lines.join('\\n');\n}\n\n// ─── Parsing helpers (pure, exported for tests) ─────────────────────────────\n\n/** `--inputs k=v` pairs → a dispatch inputs object. `k=v` with no `=` is an error. */\nexport function parseInputs(pairs: string[] | undefined): Record<string, string> {\n const inputs: Record<string, string> = {};\n for (const pair of pairs ?? []) {\n const eq = pair.indexOf('=');\n if (eq === -1) {\n throw new ActionsCliError('invalid_argument', `Invalid --inputs entry \"${pair}\". Expected key=value.`);\n }\n inputs[pair.slice(0, eq)] = pair.slice(eq + 1);\n }\n return inputs;\n}\n\n/** Match `--workflow` to a workflow by path first, then by name. */\nexport function matchWorkflow(\n workflows: CiWorkflow[],\n selector: string,\n): CiWorkflow | undefined {\n return (\n workflows.find((w) => w.path === selector) ??\n workflows.find((w) => w.name === selector) ??\n workflows.find((w) => w.id === selector)\n );\n}\n\n/** Match `--job` to a run's job by id, then by name. */\nexport function matchJob(jobs: CiJob[], selector: string): CiJob | undefined {\n return jobs.find((j) => j.id === selector) ?? jobs.find((j) => j.name === selector);\n}\n\n// ─── Logs ───────────────────────────────────────────────────────────────────\n\nasync function readWholeJobLog(client: ActionsClient, jobId: string, step?: string): Promise<CiLogSlice> {\n const segments: CiLogSlice['segments'] = [];\n let offset = 0;\n let slice: CiLogSlice;\n do {\n slice = await client.get<CiLogSlice>(`/api/v1/actions/jobs/${jobId}/logs`, {\n offset: String(offset),\n step,\n });\n segments.push(...slice.segments);\n offset = slice.nextOffset;\n } while (slice.truncated);\n return { ...slice, segments };\n}\n\n/** Follow one job's log over the SSE `follow=1` slice stream, resuming on reconnect. */\nasync function* followJobLog(client: ActionsClient, jobId: string, step?: string): AsyncGenerator<CiLogSlice> {\n let offset = 0;\n for (;;) {\n let terminal = false;\n for await (const raw of client.sse(`/api/v1/actions/jobs/${jobId}/logs`, {\n offset: String(offset),\n follow: '1',\n step,\n })) {\n const slice = raw as CiLogSlice;\n offset = slice.nextOffset;\n if (slice.segments.length > 0 || slice.state !== 'running') yield slice;\n if (slice.state !== 'running' && slice.state !== 'pending' && !slice.truncated) {\n terminal = true;\n }\n }\n if (terminal) return;\n // The connection ended (server-side ceiling or a drop): resume from the\n // offset we hold — resumable cursors make this a continuation, not a replay.\n }\n}\n\n/** `--step` CLI value → the watch-cursor step field. */\nexport function parseStep(step: string | undefined): number | 'runner' | null {\n if (step === undefined) return null;\n if (step === 'runner') return 'runner';\n const n = Number(step);\n if (!Number.isInteger(n) || n < 0) {\n throw new ActionsCliError('invalid_argument', `Invalid --step \"${step}\". Expected a step ordinal or \"runner\".`);\n }\n return n;\n}\n\n/** Follow a run's logs across jobs via the multiplexed run stream. */\nasync function* followRunLogs(\n client: ActionsClient,\n runId: string,\n jobs: CiJob[],\n step?: string,\n): AsyncGenerator<{ job: CiJob; slice: CiLogSlice }> {\n const cursorStep = parseStep(step);\n const offsets = new Map<string, number>(jobs.map((j) => [j.id, 0]));\n const byCursor = new Map<string, CiJob>(jobs.map((j, i) => [`j${i}`, j]));\n for (;;) {\n let done = false;\n const watch = jobs.map((j, i) =>\n encodeWatchCursor(`j${i}`, j.id, cursorStep, offsets.get(j.id) ?? 0),\n );\n for await (const raw of client.sse(`/api/v1/actions/runs/${runId}/stream`, { watch })) {\n const msg = raw as\n | { type: 'state'; state: unknown }\n | { type: 'log'; cursor: string; slice: CiLogSlice }\n | { type: 'done' }\n | { type: 'reconnect' };\n if (msg.type === 'log') {\n const job = byCursor.get(msg.cursor);\n if (job) {\n offsets.set(msg.slice.jobId, msg.slice.nextOffset);\n yield { job, slice: msg.slice };\n }\n } else if (msg.type === 'done') {\n done = true;\n break;\n } else if (msg.type === 'reconnect') {\n break;\n }\n }\n if (done) return;\n // Both an explicit `reconnect` event and an unexpected EOF resume from the\n // offsets we hold; back off briefly so a repeatedly-closing server doesn't\n // spin the loop.\n await new Promise((r) => setTimeout(r, 1000));\n }\n}\n\n// Job and step names come from workflow files — potentially attacker-controlled\n// in a PR context — so strip control characters before writing to the terminal.\nexport function safeTerm(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/[\\u0000-\\u001F\\u007F-\\u009F]/g, '�');\n}\n\nexport function formatRunHistory(history: CiRunHistory): string {\n const lines: string[] = [];\n const parts = (Object.entries(history.conclusions) as [string, number][])\n .map(([c, n]) => `${n} ${c}`)\n .join(', ');\n lines.push(`last ${history.runCount} runs: ${parts || 'none'}`);\n if (history.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of history.jobs) {\n const rate = job.runs > 0 ? Math.round((job.failedRuns / job.runs) * 100) : 0;\n const platform = job.failedBeforeSteps > 0 ? pc.dim(` (${job.failedBeforeSteps} failed before steps)`) : '';\n const count = `${job.failedRuns}/${job.runs} runs failed`;\n const label = job.failedRuns > 0 ? pc.red(count) : pc.green(count);\n lines.push(` ${safeTerm(job.job)} ${label} ${rate}%${platform}`);\n for (const step of job.steps) {\n lines.push(pc.dim(` step \"${safeTerm(step.step)}\" failed in ${step.failedRuns} run${step.failedRuns === 1 ? '' : 's'}`));\n }\n }\n }\n const failed = history.runs.filter(\n (r) => r.conclusion === 'failed' || r.failedJobs.length > 0,\n );\n if (failed.length > 0) {\n lines.push('');\n lines.push(pc.bold('failed runs'));\n for (const run of failed) {\n const blame = run.failedJobs.length > 0\n ? run.failedJobs.map((j) => safeTerm(j.step === null ? j.job : `${j.job}:${j.step}`)).join(', ')\n : pc.dim('(no failed job recorded)');\n lines.push(` ${shortSha(run.headSha)} ${pc.dim(run.startedAt)} ${blame}`);\n }\n }\n return lines.join('\\n');\n}\n\nexport function formatProviderRow(p: CiProviderInfo): string {\n const icon = p.usable ? pc.green('●') : pc.gray('○');\n const name = p.usable ? pc.white(p.provider) : pc.gray(p.provider);\n const flags = [\n p.credential,\n p.actCapable ? pc.green('act') : pc.gray('no-act'),\n p.regions.length > 0 ? `regions: ${p.regions.join(',')}` : 'no region choice',\n p.position === null ? pc.gray('not in provider order') : `order #${p.position}`,\n ].join(' ');\n return ` ${icon} ${name} ${flags}`;\n}\n\nexport function formatVerifyResult(r: CiProviderKeyResponse): string {\n const ok = r.verified === true;\n const head = ok ? pc.green('verified') : pc.red('not verified');\n const detail = r.key.statusDetail ? pc.dim(` ${r.key.statusDetail}`) : '';\n const act = r.key.actCapable ? pc.green(' act-capable') : '';\n return `${head} ${r.key.provider}${act}${detail}`;\n}\n\nfunction formatRepoRow(r: CiRepo): string {\n const head = r.enabled ? pc.green('enabled') : pc.dim('disabled');\n const via = r.authType === 'github_app' ? 'github-app' : r.authType;\n const workflows =\n r.workflowPaths.length > 0\n ? `${r.workflowPaths.length} workflow${r.workflowPaths.length === 1 ? '' : 's'}`\n : 'no workflows yet';\n const error = r.lastPollError ? pc.red(` poll error: ${safeTerm(r.lastPollError)}`) : '';\n return `${head} ${safeTerm(r.fullName)} ${pc.dim(`${safeTerm(via)} · ${safeTerm(r.defaultBranch)} · ${workflows}`)}${error}`;\n}\n\n/** Print what an enable/connect discovered — one dim line, nothing on a clean run. */\nfunction printDiscovery(d: { workflowsFound: boolean; seeded: boolean; error: string | null }): void {\n if (d.error) {\n console.log(pc.yellow(`discovery: ${safeTerm(d.error)} (the poll cron retries)`));\n return;\n }\n console.log(pc.dim(`discovery: ${d.workflowsFound ? 'workflows found' : 'no workflows yet'}${d.seeded ? ', cursors seeded' : ''}`));\n}\n\n// ─── Commands ───────────────────────────────────────────────────────────────\n\n/**\n * The `POST /api/v1/actions/dispatch` body for `dispatch`. Without --manual a\n * workflow must declare `workflow_dispatch`. With it, a workflow that doesn't\n * is run anyway; such a run has no inputs, so any given are refused rather\n * than silently dropped. A dispatchable workflow keeps its inputs either way.\n */\nexport function dispatchBody(\n workflow: CiWorkflow,\n opts: {\n ref?: string;\n inputs?: string[];\n manual?: boolean;\n provider?: string;\n providerRegion?: string;\n maxBid?: string;\n maxBidPer?: string;\n },\n): Record<string, unknown> {\n if (!workflow.dispatchable && !opts.manual) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${workflow.path}\" does not declare workflow_dispatch. Pass --manual to run it anyway (no inputs).`,\n );\n }\n if (!workflow.dispatchable && opts.inputs !== undefined && opts.inputs.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${workflow.path}\" has no workflow_dispatch inputs; --manual runs of it take no --inputs.`,\n );\n }\n const ref = opts.ref ?? workflow.refs[0];\n if (!ref) throw new ActionsCliError('invalid_argument', 'No --ref given and the workflow has no watched refs.');\n if (opts.providerRegion !== undefined && opts.provider === undefined) {\n throw new ActionsCliError('invalid_argument', '--provider-region requires --provider.');\n }\n const maxPrice = maxPriceFields(opts.maxBid, opts.maxBidPer);\n return {\n workflowId: workflow.id,\n ref,\n inputs: parseInputs(opts.inputs),\n ...(opts.manual && { manual: true }),\n ...(opts.provider !== undefined && {\n provider: opts.provider,\n ...(opts.providerRegion !== undefined && { providerRegion: opts.providerRegion }),\n }),\n ...(maxPrice !== undefined && maxPrice),\n };\n}\n\n/**\n * `--max-bid`/`--max-bid-per` → the dispatch body's market price ceiling\n * fields. Undefined when no ceiling is set; the ceiling only applies to a\n * market fill — jobs that can't be filled at the price fall through to the\n * next provider-order entry.\n */\nexport function maxPriceFields(\n maxBid: string | undefined,\n maxBidPer: string | undefined,\n): { maxPriceUsd: number; maxPricePer: 'second' | 'minute' | 'hour' } | undefined {\n if (maxBidPer !== undefined && maxBid === undefined) {\n throw new ActionsCliError('invalid_argument', '--max-bid-per requires --max-bid.');\n }\n if (maxBid === undefined) return undefined;\n const usd = Number(maxBid);\n if (!/^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/.test(maxBid) || !Number.isFinite(usd) || usd <= 0) {\n throw new ActionsCliError('invalid_argument', `Invalid --max-bid \"${maxBid}\". Expected a positive dollar amount (e.g. 0.12).`);\n }\n const per = maxBidPer ?? 'second';\n if (per !== 'second' && per !== 'minute' && per !== 'hour') {\n throw new ActionsCliError('invalid_argument', `--max-bid-per must be second, minute, or hour, got \"${maxBidPer}\".`);\n }\n return { maxPriceUsd: usd, maxPricePer: per };\n}\n\n/** `--kind` for the vault commands: `secret` unless told otherwise. */\nexport function parseVaultKind(kind: string | undefined): CiVaultKind {\n if (kind === undefined || kind === 'secret' || kind === 'variable') return kind ?? 'secret';\n throw new ActionsCliError('invalid_argument', `--kind must be secret or variable, got \"${kind}\".`);\n}\n\n/** A vault route path with its scope in the query string. */\nexport function vaultPath(\n path: string,\n params: { repo?: string; kind?: CiVaultKind; name?: string },\n): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) search.set(key, value);\n }\n const query = search.toString();\n return query ? `${path}?${query}` : path;\n}\n\n/**\n * The `PUT /api/v1/vault` body for `vault set`. The value is sent exactly as\n * read — never trimmed — because whitespace can be part of a key.\n */\nexport function vaultSetBody(\n name: string,\n value: string,\n opts: { kind: CiVaultKind; revealable?: boolean; description?: string; labels?: string[] },\n): Record<string, unknown> {\n if (value === '') throw new ActionsCliError('invalid_argument', 'The value is empty.');\n if (opts.revealable && opts.kind === 'variable') {\n throw new ActionsCliError('invalid_argument', '--revealable applies to secrets; variables are always readable.');\n }\n return {\n name,\n kind: opts.kind,\n value,\n ...(opts.revealable && { revealable: true }),\n ...(opts.description !== undefined && { description: opts.description }),\n ...(opts.labels !== undefined && opts.labels.length > 0 && { labels: opts.labels }),\n };\n}\n\nexport function formatVaultRow(item: CiVaultItem): string {\n const flags = [\n item.kind,\n ...(item.revealable && item.kind === 'secret' ? ['revealable'] : []),\n `v${item.version}`,\n ...(item.source === 'organization' ? ['inherited'] : []),\n ...(item.overridesOrganization ? ['overrides org'] : []),\n ];\n return `${pc.cyan(safeTerm(item.name))} ${pc.dim(flags.join(', '))} ${pc.dim(`updated ${safeTerm(item.updatedAt)}`)}`;\n}\n\nexport function registerActionsCommands(program: Command): void {\n const actions = program\n .command('actions')\n .alias('ci')\n .description('Drive the benchmarks-platform Actions API')\n .configureOutput({ outputError: usageErrorOutput });\n\n const common = (cmd: Command) =>\n cmd\n .option('--api-key <key>', 'API key (default: $COMPUTE_API_KEY)')\n .option('--base-url <url>', 'API base URL (default: https://platform.computesdk.com)')\n .option('--org <slug>', 'organization slug for this command (or $COMPUTE_ORG)')\n .option('--allow-untrusted-host', 'send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)')\n .option('--json', 'print machine-readable JSON');\n\n common(\n actions\n .command('dispatch')\n .description('Dispatch a workflow_dispatch run (or any workflow with --manual)')\n .argument('<repo>', 'repository in owner/repo format')\n .requiredOption('--workflow <path|name>', 'workflow path or name')\n .option('--ref <ref>', 'git ref to run (default: the workflow\\'s first watched ref)')\n .option('--inputs <pairs...>', 'workflow inputs as key=value (workflow_dispatch inputs only)')\n .option('--manual', 'run a workflow even if it does not declare workflow_dispatch (such runs take no --inputs)')\n .option('--provider <id>', 'place the run on one provider (e.g. namespace, vercel:sfo1) instead of the org provider order')\n .option('--provider-region <region>', 'region for --provider (same as --provider <id>:<region>)')\n .option('--max-bid <usd>', 'max price per vCPU for a market fill (e.g. 0.12); unfilled jobs fall through to the next provider')\n .option('--max-bid-per <unit>', 'time unit --max-bid is priced in: second, minute, or hour (default: second)'),\n ).action(async (repo: string, opts: CommonOpts & { workflow: string; ref?: string; inputs?: string[]; manual?: boolean; provider?: string; providerRegion?: string; maxBid?: string; maxBidPer?: string }) => {\n try {\n const c = await client(opts);\n const { workflows } = await c.get<{ workflows: CiWorkflow[] }>(\n '/api/v1/actions/workflows',\n { repo },\n );\n const workflow = matchWorkflow(workflows, opts.workflow);\n if (!workflow) {\n const choices = workflows.map((w) => `${w.path} (${w.name})`).join(', ') || 'none';\n throw new ActionsCliError(\n 'workflow_not_found',\n `No workflow \"${opts.workflow}\" in ${repo}. Available: ${choices}`,\n );\n }\n const body = dispatchBody(workflow, opts);\n const result = await c.post<{ runId: string; created: boolean; headSha: string }>(\n '/api/v1/actions/dispatch',\n body,\n );\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${result.runId}`;\n output(opts, { ...result, url }, (r) => {\n console.log(`${r.created ? 'dispatched' : 'already running'} ${pc.cyan(r.runId)}`);\n console.log(`sha: ${r.headSha}`);\n console.log(`url: ${r.url}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('runs')\n .description('List recent runs for a repo')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--status <status...>', 'filter by conclusion: passed, failed, running, cancelled, none')\n .option('--branch <branch...>', 'filter by branch/ref'),\n ).action(async (repo: string, opts: CommonOpts & { status?: string[]; branch?: string[] }) => {\n try {\n const { runs } = await (await client(opts)).get<{ runs: CiRun[] }>(\n '/api/v1/actions/runs',\n { repo, status: opts.status, branch: opts.branch },\n );\n output(opts, runs, (rs) => {\n if (rs.length === 0) {\n console.log('No runs found.');\n return;\n }\n for (const run of rs) console.log(formatRunRow(run));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('history')\n .description('Recent run history for a workflow — per-job/step failure rates (is this failure flaky?)')\n .argument('<repo>', 'repository in owner/repo format')\n .requiredOption('--workflow <path|name>', 'workflow path or name')\n .option('--branch <branch...>', 'narrow the window to branches/refs')\n .option('--job <job>', 'narrow the rollup to one job name or workflow job id')\n .option('--limit <n>', 'runs in the window (default 10, max 50)'),\n ).action(async (repo: string, opts: CommonOpts & { workflow: string; branch?: string[]; job?: string; limit?: string }) => {\n try {\n const c = await client(opts);\n const { workflows } = await c.get<{ workflows: CiWorkflow[] }>(\n '/api/v1/actions/workflows',\n { repo },\n );\n const workflow = matchWorkflow(workflows, opts.workflow) ?? workflows.find((w) => w.path === opts.workflow);\n const workflowPath = workflow?.path ?? opts.workflow;\n const history = await c.get<CiRunHistory>('/api/v1/actions/history', {\n repo,\n workflow: workflowPath,\n branch: opts.branch,\n job: opts.job,\n limit: opts.limit,\n });\n output(opts, history, (h) => console.log(formatRunHistory(h)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('run')\n .description('Show a run: jobs, provider:region placement, placement attempts')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const run = await c.get<CiRun>(`/api/v1/actions/runs/${runId}`);\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${run.id}`;\n // A failed run's interesting part is its failure digest; on deployments\n // that have the summary route it prints inline, saving a second command.\n const summary = run.conclusion === 'failed' ? await fetchRunSummary(c, runId) : null;\n output(opts, { ...run, url, summary }, (r) => {\n console.log(formatRunDetail(r, r.url));\n if (summary && summary.failures.length > 0) {\n console.log('');\n console.log(formatRunSummary(summary));\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('summary')\n .description('Show a run\\'s failure digest: failed jobs, failed steps, bounded log tails')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const summary = await (await client(opts)).get<CiRunSummary>(`/api/v1/actions/runs/${runId}/summary`);\n output(opts, summary, (s) => console.log(formatRunSummary(s)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('inspect')\n .description('Inspect a run: resolved runner image, caches, secret names, concurrency, placement context')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const inspection = await c.get<CiRunInspection>(\n `/api/v1/actions/runs/${runId}/state`,\n );\n output(opts, inspection, (r) => console.log(formatRunInspection(r)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('logs')\n .description('Print or follow a run\\'s job logs')\n .argument('<run-id>', 'run ID')\n .option('--job <job>', 'job ID or name (default: all jobs)')\n .option('--step <step>', 'step ordinal or \"runner\" (default: whole job)')\n .option('--follow', 'stream logs while the run is live'),\n ).action(async (runId: string, opts: CommonOpts & { job?: string; step?: string; follow?: boolean }) => {\n try {\n const c = await client(opts);\n let jobs = await listRunJobs(c, runId);\n if (opts.job) {\n const job = matchJob(jobs, opts.job);\n if (!job) {\n throw new Error(\n `No job \"${opts.job}\" in run ${runId}. Jobs: ${jobs.map((j) => j.name).join(', ') || 'none'}`,\n );\n }\n jobs = [job];\n }\n if (jobs.length === 0) {\n if (opts.json) output(opts, { segments: [] }, () => {});\n else console.error('Run has no jobs yet.');\n return;\n }\n\n if (!opts.follow) {\n for (const job of jobs) {\n const slice = await readWholeJobLog(c, job.id, opts.step);\n if (opts.json) {\n process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + '\\n');\n } else {\n if (jobs.length > 1) console.log(pc.bold(`── ${job.name} ──`));\n for (const seg of slice.segments) process.stdout.write(seg.text);\n }\n }\n return;\n }\n\n if (jobs.length === 1) {\n // Single job: the slice endpoint's own SSE, resumed on reconnect.\n for await (const slice of followJobLog(c, jobs[0].id, opts.step)) {\n if (opts.json) {\n process.stdout.write(JSON.stringify(slice) + '\\n');\n } else {\n for (const seg of slice.segments) process.stdout.write(seg.text);\n }\n }\n return;\n }\n\n // Multiple jobs: one multiplexed stream, each slice tagged by job.\n for await (const { job, slice } of followRunLogs(c, runId, jobs, opts.step)) {\n if (opts.json) {\n process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + '\\n');\n } else {\n for (const seg of slice.segments) {\n const text = seg.text.replace(/\\n/g, `\\n[${job.name}] `);\n process.stdout.write(`[${job.name}] ${text}`);\n }\n }\n }\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const providers = actions\n .command('providers')\n .description('List the org\\'s registered compute providers (regions, act/usable status)');\n common(providers).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiProvidersResponse>('/api/v1/actions/providers');\n output(opts, data, (d) => {\n for (const p of d.providers) console.log(formatProviderRow(p));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('configure')\n .description('Save the org\\'s credential for a provider (owner/admin API key)')\n .argument('<provider>', 'provider id (e.g. tensorlake, blaxel)')\n .option('--key <key>', 'provider API key (single-field credentials)')\n .option('--field <pair...>', 'credential fields as name=value (multi-field providers)')\n .option('--verify', 'run the placement probe after saving'),\n ).action(async (provider: string, opts: CommonOpts & { key?: string; field?: string[]; verify?: boolean }) => {\n try {\n const c = await client(opts);\n let body: Record<string, unknown>;\n if (opts.field !== undefined) {\n if (opts.key !== undefined) throw new Error('Pass either --key or --field, not both.');\n body = { fields: parseInputs(opts.field) };\n } else if (opts.key !== undefined) {\n body = { key: opts.key };\n } else {\n throw new Error('Pass --key <key> or --field name=value.');\n }\n const saved = await c.put<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/key`,\n body,\n );\n const verification = opts.verify\n ? await c.post<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/verify`,\n )\n : undefined;\n output(opts, verification ? { key: saved.key, verification } : saved, () => {\n console.log(`saved ${saved.key.provider} ${pc.dim(saved.key.keyHint)} ${saved.key.status}`);\n if (verification) console.log(formatVerifyResult(verification));\n });\n if (verification?.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('verify')\n .description('Probe the stored provider key with a real sandbox (\"Test\" in Settings)')\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/verify`,\n );\n output(opts, result, (r) => console.log(formatVerifyResult(r)));\n if (result.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('remove')\n .description('Delete the org\\'s stored credential for a provider')\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ provider: string; deleted: boolean }>(\n `/api/v1/actions/providers/${provider}/key`,\n );\n output(opts, result, (r) => {\n console.log(r.deleted ? `deleted ${r.provider}` : `no key stored for ${r.provider}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const repos = actions\n .command('repos')\n .description('List the org\\'s connected repositories');\n common(repos).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiReposResponse>('/api/v1/actions/repos');\n output(opts, data, (d) => {\n for (const r of d.repos) console.log(formatRepoRow(r));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('connect')\n .description('Connect a git remote (validated by a real ls-remote; lands enabled)')\n .argument('<cloneUrl>', 'http(s) or ssh git remote URL')\n .option('--name <owner/repo>', 'repo name override (default: derived from cloneUrl)')\n .option('--branch <branch>', 'default branch (default: main, else the remote\\'s first)')\n .option('--token <token>', 'credential for private http(s) remotes')\n .option('--username <user>', 'username — with --token, makes auth \"basic\" instead of \"token\"')\n .option('--ssh-key-file <path>', 'OpenSSH/PEM private key file for ssh remotes')\n .option('--known-hosts-file <path>', 'known_hosts pin for ssh remotes'),\n ).action(async (cloneUrl: string, opts: CommonOpts & { name?: string; branch?: string; token?: string; username?: string; sshKeyFile?: string; knownHostsFile?: string }) => {\n try {\n let body: Record<string, unknown>;\n if (opts.sshKeyFile !== undefined) {\n if (opts.token !== undefined || opts.username !== undefined) {\n throw new Error('Pass either --ssh-key-file or --token/--username, not both.');\n }\n body = {\n authType: 'ssh',\n credential: readFileSync(opts.sshKeyFile, 'utf8'),\n ...(opts.knownHostsFile !== undefined && {\n knownHosts: readFileSync(opts.knownHostsFile, 'utf8'),\n }),\n };\n } else if (opts.username !== undefined) {\n if (opts.token === undefined) throw new Error('--username requires --token.');\n body = { authType: 'basic', username: opts.username, credential: opts.token };\n } else if (opts.token !== undefined) {\n body = { authType: 'token', credential: opts.token };\n } else {\n body = { authType: 'none' };\n }\n if (opts.knownHostsFile !== undefined && opts.sshKeyFile === undefined) {\n throw new Error('--known-hosts-file requires --ssh-key-file.');\n }\n const result = await (await client(opts)).post<CiRepoConnectResponse>('/api/v1/actions/repos', {\n cloneUrl,\n ...body,\n ...(opts.name !== undefined && { name: opts.name }),\n ...(opts.branch !== undefined && { defaultBranch: opts.branch }),\n });\n output(opts, result, (r) => {\n console.log(`connected ${pc.cyan(safeTerm(r.fullName))} ${pc.dim(`(${safeTerm(r.authType)}, ${safeTerm(r.defaultBranch)})`)}`);\n printDiscovery(r.discovery);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('enable')\n .description('Enable a repo the org can already see (granted by a GitHub App install, or a connected remote)')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--repo-id <id>', 'scope to one row when two installations grant the same name'),\n ).action(async (repo: string, opts: CommonOpts & { repoId?: string }) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: true,\n ...(opts.repoId !== undefined && { repoId: opts.repoId }),\n });\n output(opts, result, (r) => {\n console.log(`enabled ${pc.cyan(safeTerm(r.fullName))}`);\n if (r.discovery) printDiscovery(r.discovery);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('disable')\n .description('Disable a repo — it stays connected but no runs are scheduled')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--repo-id <id>', 'scope to one row when two installations grant the same name'),\n ).action(async (repo: string, opts: CommonOpts & { repoId?: string }) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: false,\n ...(opts.repoId !== undefined && { repoId: opts.repoId }),\n });\n output(opts, result, (r) => console.log(`disabled ${pc.cyan(safeTerm(r.fullName))}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const vault = actions\n .command('vault')\n .description('The org vault: secrets and variables (owner/admin key)');\n const vaultScope = (cmd: Command) =>\n common(cmd)\n .option('--repo <owner/repo>', 'scope to a repo\\'s own items instead of the org\\'s')\n .option('--kind <kind>', 'secret or variable', 'secret');\n type VaultOpts = CommonOpts & { repo?: string; kind?: string };\n\n vaultScope(\n vault.command('ls').description('List names and metadata (never values)'),\n ).action(async (opts: VaultOpts) => {\n try {\n const path = vaultPath('/api/v1/vault', { repo: opts.repo, kind: parseVaultKind(opts.kind) });\n const data = await (await client(opts)).get<CiVaultListResponse>(path);\n output(opts, data, (d) => {\n for (const item of d.items) console.log(formatVaultRow(item));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('set')\n .description('Store a value, read from stdin (or --from-file) and sent exactly as read')\n .argument('<name>', 'item name, e.g. NPM_TOKEN')\n .option('--from-file <path>', 'read the value from a file instead of stdin')\n .option('--revealable', 'let the value be read back with `vault get` (secrets; fixed at creation)')\n .option('--description <text>', 'what the item is for')\n .option('--labels <labels...>', 'labels (fixed at creation)'),\n ).action(async (name: string, opts: VaultOpts & { fromFile?: string; revealable?: boolean; description?: string; labels?: string[] }) => {\n try {\n if (opts.fromFile === undefined && process.stdin.isTTY) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Pipe the value on stdin (e.g. printf %s \"$VALUE\" | compute actions vault set NAME) or pass --from-file.',\n );\n }\n const value = readFileSync(opts.fromFile ?? 0, 'utf8');\n const kind = parseVaultKind(opts.kind);\n const body = vaultSetBody(name, value, { ...opts, kind });\n const result = await (await vaultValueClient(opts)).put<CiVaultSaveResponse>(\n vaultPath('/api/v1/vault', { repo: opts.repo }),\n body,\n );\n output(opts, result, (r) => {\n const where = opts.repo ? safeTerm(opts.repo) : 'org';\n console.log(`saved ${pc.cyan(safeTerm(r.item.name))} ${pc.dim(`(${r.item.kind}, v${r.item.version}, ${where})`)}`);\n if (/\\r?\\n$/.test(value)) {\n console.error(pc.yellow('note: the stored value ends with a newline; use printf %s rather than echo to avoid one.'));\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('get')\n .description('Print a value: any variable, or a secret created --revealable')\n .argument('<name>', 'item name'),\n ).action(async (name: string, opts: VaultOpts) => {\n try {\n const kind = parseVaultKind(opts.kind);\n const result = await (await vaultValueClient(opts)).post<CiVaultRevealResponse>(\n vaultPath('/api/v1/vault/reveal', { repo: opts.repo }),\n { name, kind },\n );\n output(opts, result, (r) => process.stdout.write(r.value));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('rm')\n .description('Delete an item (with --repo, only the repo\\'s override)')\n .argument('<name>', 'item name'),\n ).action(async (name: string, opts: VaultOpts) => {\n try {\n const path = vaultPath('/api/v1/vault', { repo: opts.repo, kind: parseVaultKind(opts.kind), name });\n const result = await (await client(opts)).del<CiVaultDeleteResponse>(path);\n output(opts, result, (r) => console.log(`deleted ${pc.cyan(safeTerm(r.name))} ${pc.dim(`(${r.kind})`)}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('cancel')\n .description('Cancel a run')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<{ cancelled: boolean }>(\n `/api/v1/actions/runs/${runId}/cancel`,\n );\n output(opts, result, (r) => {\n console.log(r.cancelled ? `Cancelled ${runId}` : `Run ${runId} was already finished`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('rerun')\n .description('Re-run a finished run at the same commit')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const result = await c.post<{ runId: string; created: boolean }>(\n `/api/v1/actions/runs/${runId}/rerun`,\n );\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${result.runId}`;\n output(opts, { ...result, url }, (r) => {\n console.log(`${r.created ? 'rerun dispatched' : 'rerun already running'} ${pc.cyan(r.runId)}`);\n console.log(`url: ${r.url}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('artifacts')\n .description('List or download a run\\'s artifacts')\n .argument('<run-id>', 'run ID')\n .option('--job <job>', 'job ID or name (default: all jobs)')\n .option('--out <dir>', 'download artifacts into this directory instead of listing'),\n ).action(async (runId: string, opts: CommonOpts & { job?: string; out?: string }) => {\n try {\n const c = await client(opts);\n let jobs = await listRunJobs(c, runId);\n if (opts.job) {\n const job = matchJob(jobs, opts.job);\n if (!job) throw new Error(`No job \"${opts.job}\" in run ${runId}.`);\n jobs = [job];\n }\n const entries: { job: CiJob; artifacts: CiArtifactListItem[] }[] = [];\n for (const job of jobs) {\n const artifacts = await c.get<CiArtifactListItem[]>(\n `/api/v1/actions/jobs/${job.id}/artifacts`,\n );\n entries.push({ job, artifacts });\n }\n\n if (opts.out) {\n const written: { jobId: string; id: string; file: string }[] = [];\n for (const { job, artifacts } of entries) {\n // Per-job directory: artifact names are not unique across jobs.\n const jobDir = join(opts.out, sanitizePathPart(job.name || job.id));\n mkdirSync(jobDir, { recursive: true });\n for (const artifact of artifacts) {\n if (artifact.expired || artifact.skippedReason) continue;\n const bytes = await c.download(\n `/api/v1/actions/jobs/${job.id}/artifacts/${artifact.id}`,\n );\n const file = join(jobDir, sanitizePathPart(artifact.fileName || artifact.name));\n writeFileSync(file, bytes);\n written.push({ jobId: job.id, id: artifact.id, file });\n }\n }\n output(opts, written, (ws) => {\n for (const w of ws) console.log(`wrote ${w.file}`);\n if (ws.length === 0) console.log('No downloadable artifacts.');\n });\n return;\n }\n\n output(opts, entries.map((e) => ({ jobId: e.job.id, job: e.job.name, artifacts: e.artifacts })), (es) => {\n let any = false;\n for (const { job, artifacts } of es) {\n for (const a of artifacts) {\n any = true;\n const flags = a.expired ? ' expired' : a.skippedReason ? ` skipped: ${a.skippedReason}` : '';\n console.log(\n `${job} ${a.id} ${a.name} ${a.contentType} ${a.byteLength}B${flags}`,\n );\n }\n }\n if (!any) console.log('No artifacts.');\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * Thin client for the benchmarks-platform Actions v1 API.\n * Types mirror the wire shapes in benchmarks-platform `lib/ci/types.ts` —\n * keep them in sync by hand; the API is the contract.\n */\n\n\nexport const DEFAULT_BASE_URL = 'https://platform.computesdk.com';\n\nexport interface ActionsAuth {\n apiKey: string;\n baseUrl: string;\n /** Sent as `X-Org-Slug` when set (--org / COMPUTE_ORG / stored login org). */\n orgSlug?: string;\n}\n\nexport interface CiWorkflowInput {\n name: string;\n description: string;\n type: 'string' | 'number' | 'boolean' | 'choice' | 'environment';\n required: boolean;\n default: string;\n options?: string[];\n}\n\nexport interface CiWorkflow {\n id: string;\n repoFullName: string;\n name: string;\n path: string;\n dispatchable: boolean;\n refs: string[];\n inputs: CiWorkflowInput[];\n schedules: unknown[];\n}\n\nexport type CiConclusion = 'passed' | 'failed' | 'running' | 'cancelled' | 'none';\nexport type CiJobState =\n | 'queued'\n | 'running'\n | 'passed'\n | 'failed'\n | 'skipped'\n | 'cancelled';\n\nexport interface CiPlacementAttempt {\n provider: string;\n region?: string | null;\n error: string;\n}\n\nexport interface CiStep {\n name: string;\n state: CiJobState;\n durationMs: number | null;\n exitCode: number | null;\n}\n\nexport interface CiJob {\n id: string;\n name: string;\n needs: string[];\n workflowJobId: string | null;\n matrix: Record<string, string> | null;\n state: CiJobState;\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n placementAttempts: CiPlacementAttempt[];\n durationMs: number | null;\n steps: CiStep[];\n}\n\nexport interface CiRun {\n id: string;\n repoFullName: string;\n ref: string;\n branchReason: string | null;\n headSha: string;\n event: string;\n prNumber: number | null;\n runNumber: number | null;\n title: string;\n workflowPath: string;\n workflowName: string;\n conclusion: CiConclusion;\n startedAt: string;\n durationMs: number | null;\n supersededByRunId: string | null;\n concurrencyGroup: string | null;\n cancellationReason: string | null;\n /** `provider[:region]` the dispatch pinned this run to, else null. */\n providerOverride?: string | null;\n jobs: CiJob[];\n logTail: string[];\n}\n\n/**\n * One job of `GET /api/v1/actions/runs/{id}/state`: the live fields plus the\n * context that decided how the job ran — resolved runner image, container\n * pin, concurrency group, timeout/fetch-depth overrides.\n */\nexport interface CiJobInspection {\n id: string;\n name: string;\n state: CiJobState;\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n startedAt: string | null;\n finishedAt: string | null;\n placementAttempts: CiPlacementAttempt[];\n /** Why the platform failed the job before steps ran, when it did. */\n failureReason: string | null;\n /** The `runs-on:` labels as declared. */\n runsOn: string[];\n /** The `computesdk:` placement pin the labels carried, when one did. */\n placementHint: { provider: string; region: string | null; label: string } | null;\n /** Labels act actually read (placement labels stripped, default substituted). */\n resolvedRunsOn: string[] | null;\n runsOnHasExpression: boolean;\n /** The image the job's steps ran in: container pin, else the mapped label. */\n runnerImage: string | null;\n /** The literal `container:` image the job declared, if any. */\n container: string | null;\n timeoutMinutes: number | null;\n /** Deepest `fetch-depth` a checkout step pinned (0 = full history). */\n fetchDepth: number | null;\n concurrencyGroup: string | null;\n concurrencyCancelInProgress: boolean;\n matrix: Record<string, string> | null;\n steps: {\n ordinal: number;\n name: string;\n state: CiJobState;\n exitCode: number | null;\n startedAt: string | null;\n finishedAt: string | null;\n }[];\n}\n\n/** A cache entry the run's window touched (saved or restored). */\nexport interface CiRunCacheTouch {\n key: string;\n version: string;\n scopeRef: string;\n sizeBytes: number;\n savedAt: string | null;\n restoredAt: string | null;\n}\n\n/** `GET /api/v1/actions/runs/{id}/state` — a run plus its effective context. */\nexport interface CiRunInspection {\n id: string;\n conclusion: CiConclusion;\n runNumber: number | null;\n ref: string;\n headSha: string;\n event: string;\n queuedAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n supersededByRunId: string | null;\n cancellationReason: string | null;\n /** Why the run was refused before placement, when it was. */\n blockedReason: string | null;\n concurrencyGroup: string | null;\n dispatchInputs: Record<string, string> | null;\n providerOverride: string | null;\n /** The commit the stored workflow definition was parsed from. */\n workflowParsedFromSha: string | null;\n /**\n * True when the stored parse came from a different commit than the run's\n * head — the definition-derived fields may then describe a newer workflow\n * than the run used (a fork pull request always shows this by design).\n */\n definitionStale: boolean;\n /** Secret *names* the jobs could reference — never values. */\n secrets: {\n access: 'declared' | 'all';\n /** Whether named secrets are also exported as job env vars. */\n env: boolean;\n names: string[];\n } | null;\n caches: CiRunCacheTouch[];\n jobs: CiJobInspection[];\n}\n\n/**\n * `GET /api/v1/actions/runs/{runId}/summary` — a run's failure digest.\n * Wire shape mirrors `CiRunSummary` in benchmarks-platform `lib/ci/run-summary.ts`.\n */\nexport interface CiRunSummaryJob {\n id: string;\n name: string;\n conclusion: CiJobState;\n provider: string | null;\n region: string | null;\n}\n\nexport interface CiRunSummaryFailedStep {\n ordinal: number;\n name: string;\n exitCode: number | null;\n}\n\nexport interface CiRunSummaryFailure extends CiRunSummaryJob {\n failureReason: string | null;\n failedSteps: CiRunSummaryFailedStep[];\n excerpt: {\n stepOrdinal: number | null;\n text: string;\n truncated: boolean;\n } | null;\n}\n\nexport interface CiRunSummary {\n runId: string;\n conclusion: CiConclusion;\n jobs: CiRunSummaryJob[];\n failures: CiRunSummaryFailure[];\n}\n\nexport interface CiArtifactListItem {\n id: string;\n name: string;\n fileName: string;\n contentType: string;\n byteLength: number;\n fileCount: number;\n skippedReason: string | null;\n expiresAt: string;\n expired: boolean;\n}\n\nexport interface CiLogSegment {\n byteOffset: number;\n stream: 'stdout' | 'stderr';\n stepOrdinal: number | null;\n text: string;\n}\n\n/** One resumable read of a job log. Resume from `nextOffset`. */\nexport interface CiLogSlice {\n jobId: string;\n fromOffset: number;\n nextOffset: number;\n totalBytes: number;\n segments: CiLogSegment[];\n state: 'running' | 'complete' | 'failed' | 'cancelled' | 'expired' | 'pending';\n truncated: boolean;\n}\n\nexport interface CiProviderInfo {\n provider: string;\n /** Selectable regions for `provider:region` order entries; empty when unknown. */\n regions: string[];\n credential: 'ambient' | 'configured' | 'not-configured';\n /** In the effective act set: built-ins, CI_ACT_PROVIDERS override, act-probe-verified keys. */\n actCapable: boolean;\n /** A placement reaching the provider finds credentials. */\n usable: boolean;\n /** 1-based position in the effective provider order, null when absent. */\n position: number | null;\n}\n\nexport interface CiProvidersResponse {\n providerOrder: string[];\n providers: CiProviderInfo[];\n}\n\n/** A saved provider credential — never carries key material, only the hint. */\nexport interface CiProviderKeyRecord {\n provider: string;\n keyHint: string;\n lastCheckedAt: string | null;\n status: 'connected' | 'error' | 'unconfigured';\n statusDetail: string | null;\n actCapable: boolean;\n credential: 'key';\n fields: unknown[];\n}\n\nexport interface CiProviderKeyResponse {\n key: CiProviderKeyRecord;\n /** Present on the verify response. */\n verified?: boolean;\n}\n\n/** One failed job inside a run-history entry — step is the first failed step. */\nexport interface CiRunJobFailure {\n job: string;\n workflowJobId: string | null;\n step: string | null;\n stepOrdinal: number | null;\n}\n\nexport interface CiRunHistoryEntry {\n id: string;\n ref: string;\n headSha: string;\n runNumber: number | null;\n conclusion: CiConclusion;\n startedAt: string;\n failedJobs: CiRunJobFailure[];\n}\n\nexport interface CiJobHistory {\n job: string;\n /** The workflow job key, when recorded; disambiguates same-named jobs. */\n workflowJobId: string | null;\n /** Runs in the window that contained this job. */\n runs: number;\n failedRuns: number;\n /** Runs where the job failed with no step blamed (platform failures). */\n failedBeforeSteps: number;\n steps: { step: string; ordinal: number; failedRuns: number }[];\n}\n\n/** `GET /api/v1/actions/history` — the window plus the rollup over it. */\nexport interface CiRunHistory {\n runCount: number;\n conclusions: Partial<Record<CiConclusion, number>>;\n jobs: CiJobHistory[];\n runs: CiRunHistoryEntry[];\n}\n\nexport interface ActionsOrg {\n organizationId: string;\n name: string;\n slug: string;\n}\n\n/**\n * One row of `GET /api/v1/actions/repos`: a repo the org can run CI on,\n * GitHub-App-granted or a generic git remote.\n */\nexport interface CiRepo {\n repoId: string;\n fullName: string;\n defaultBranch: string;\n enabled: boolean;\n private: boolean;\n forkPullRequests: boolean;\n /** `github_app` for App-granted repos; `none`/`token`/`basic`/`ssh` for remotes. */\n authType: string;\n cloneUrl: string | null;\n githubInstallationId: number | null;\n workflowPaths: string[];\n disabledWorkflowCount: number;\n lastPolledAt: string | null;\n lastPollError: string | null;\n}\n\nexport interface CiReposResponse {\n repos: CiRepo[];\n}\n\n/** What an enable/remote-connect discovered before answering. */\nexport interface CiRepoDiscovery {\n workflowsFound: boolean;\n seeded: boolean;\n error: string | null;\n}\n\nexport interface CiRepoConnectResponse {\n repoId: string | null;\n fullName: string;\n defaultBranch: string;\n authType: string;\n discovery: CiRepoDiscovery;\n}\n\nexport interface CiRepoPatchResponse {\n fullName: string;\n enabled?: boolean;\n forkPullRequests?: boolean;\n discovery: CiRepoDiscovery | null;\n}\n\nexport type CiVaultKind = 'secret' | 'variable';\n\n/** One row of `GET /api/v1/vault` — metadata only; values never list. */\nexport interface CiVaultItem {\n name: string;\n kind: CiVaultKind;\n description: string | null;\n revealable: boolean;\n labels: string[];\n version: number;\n createdAt: string;\n updatedAt: string;\n /** Present when listing or writing with `?repo=`. */\n source?: 'organization' | 'repository';\n overridesOrganization?: boolean;\n}\n\nexport interface CiVaultListResponse {\n items: CiVaultItem[];\n}\n\nexport interface CiVaultSaveResponse {\n item: CiVaultItem;\n}\n\nexport interface CiVaultRevealResponse {\n name: string;\n kind: CiVaultKind;\n value: string;\n}\n\nexport interface CiVaultDeleteResponse {\n name: string;\n kind: CiVaultKind;\n deleted: true;\n}\n\nexport class ActionsApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public body?: unknown,\n ) {\n super(message);\n this.name = 'ActionsApiError';\n }\n}\n\n/** Stable machine-readable codes for errors raised by the CLI itself. */\nexport type ActionsCliErrorCode =\n | 'no_credentials'\n | 'untrusted_host'\n | 'untrusted_host_stored_auth'\n | 'insecure_transport'\n | 'invalid_argument'\n | 'workflow_not_found';\n\n/** An error the CLI raised before or instead of an API call. */\nexport class ActionsCliError extends Error {\n constructor(\n public code: ActionsCliErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'ActionsCliError';\n }\n}\n\n/** The `--json` error envelope; `code` is stable, `message` is for humans. */\nexport interface ActionsErrorEnvelope {\n ok: false;\n error: {\n code: string;\n message: string;\n /** Present when the platform answered; absent for local/transport failures. */\n httpStatus?: number;\n retryable: boolean;\n /** The platform's `details` object, when its error response carried one. */\n details?: Record<string, unknown>;\n };\n}\n\nfunction codeForStatus(status: number): string {\n switch (status) {\n case 400: return 'bad_request';\n case 401: return 'unauthenticated';\n case 403: return 'forbidden';\n case 404: return 'not_found';\n case 409: return 'conflict';\n case 413: return 'payload_too_large';\n case 429: return 'rate_limited';\n default: return status >= 500 ? 'server_error' : 'http_error';\n }\n}\n\nfunction errorDetails(body: unknown): Record<string, unknown> | undefined {\n if (body && typeof body === 'object' && 'details' in body) {\n const details = (body as { details: unknown }).details;\n if (details && typeof details === 'object' && !Array.isArray(details)) {\n return details as Record<string, unknown>;\n }\n }\n return undefined;\n}\n\n/**\n * Classify any error thrown by an Actions command. API errors carry the HTTP\n * status; CLI errors carry their own code; a fetch rejection (DNS, refused\n * connection, TLS) is `network`; anything else is `unknown`.\n */\nexport function toErrorEnvelope(error: unknown): ActionsErrorEnvelope {\n if (error instanceof ActionsApiError) {\n const details = errorDetails(error.body);\n // The platform's OAuth layer answers 403 insufficient_scope when the\n // stored login's grant doesn't cover the call — point at re-login rather\n // than leaving the raw error.\n const insufficientScope =\n error.message.includes('insufficient_scope') ||\n (typeof error.body === 'string' && error.body.includes('insufficient_scope')) ||\n (typeof error.body === 'object' && error.body !== null &&\n JSON.stringify(error.body).includes('insufficient_scope'));\n return {\n ok: false,\n error: {\n code: codeForStatus(error.status),\n message: insufficientScope\n ? `${error.message} — run \\`compute login\\` to sign in again.`\n : error.message,\n httpStatus: error.status,\n retryable: error.status === 429 || error.status === 502 || error.status === 503 || error.status === 504,\n ...(details !== undefined && { details }),\n },\n };\n }\n if (error instanceof ActionsCliError) {\n return { ok: false, error: { code: error.code, message: error.message, retryable: false } };\n }\n // undici/Node fetch rejects with a TypeError whose cause is the socket error.\n if (error instanceof TypeError && /fetch failed/i.test(error.message)) {\n const cause = (error as { cause?: unknown }).cause;\n const detail = cause instanceof Error ? `: ${cause.message}` : '';\n return {\n ok: false,\n error: { code: 'network', message: `${error.message}${detail}`, retryable: true },\n };\n }\n return {\n ok: false,\n error: {\n code: 'unknown',\n message: error instanceof Error ? error.message : String(error),\n retryable: false,\n },\n };\n}\n\nexport class ActionsClient {\n private orgPromise: Promise<ActionsOrg> | null = null;\n\n constructor(\n private readonly auth: ActionsAuth,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {}\n\n get baseUrl(): string {\n return this.auth.baseUrl;\n }\n\n /** The credential's org — fetched once, needed for dashboard URLs. */\n org(): Promise<ActionsOrg> {\n this.orgPromise ??= this.get<ActionsOrg>('/api/v1/actions/org');\n return this.orgPromise;\n }\n\n async get<T>(path: string, params?: Record<string, string | string[] | undefined>): Promise<T> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, { headers: this.headers() });\n return this.parse<T>(res);\n }\n\n async post<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'POST',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async put<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'PUT',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async patch<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'PATCH',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async del<T>(path: string): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'DELETE',\n headers: this.headers(),\n });\n return this.parse<T>(res);\n }\n\n /**\n * One `data:` JSON payload per SSE event. `next()` resolves to the payload,\n * or null when the stream ends. Call `close()` to abort.\n */\n async *sse(path: string, params?: Record<string, string | string[] | undefined>): AsyncGenerator<unknown> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, {\n headers: { ...this.headers(), accept: 'text/event-stream' },\n });\n if (!res.ok) {\n await this.parse(res); // throws\n }\n if (!res.body) throw new Error('SSE response has no body');\n yield* readSseEvents(res.body);\n }\n\n /**\n * `sse()` with the frame's `event:` name preserved — for streams whose\n * events are distinguished by name rather than payload shape (process\n * follow: stdout/stderr share a `{chunk}` payload).\n */\n async *sseNamed(\n path: string,\n params?: Record<string, string | string[] | undefined>,\n ): AsyncGenerator<{ event: string; data: unknown }> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, {\n headers: { ...this.headers(), accept: 'text/event-stream' },\n });\n if (!res.ok) {\n await this.parse(res); // throws\n }\n if (!res.body) throw new Error('SSE response has no body');\n yield* readSseNamedEvents(res.body);\n }\n\n /** Download bytes following redirects (artifact URLs 302 to storage). */\n async download(path: string): Promise<Uint8Array> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n headers: this.headers(),\n redirect: 'follow',\n });\n if (!res.ok) {\n const body = await res.json().catch(() => undefined);\n throw new ActionsApiError(res.status, errorMessage(body, res.status), body);\n }\n return new Uint8Array(await res.arrayBuffer());\n }\n\n private headers(): Record<string, string> {\n const headers: Record<string, string> = {\n authorization: `Bearer ${this.auth.apiKey}`,\n accept: 'application/json',\n };\n if (this.auth.orgSlug) headers['X-Org-Slug'] = this.auth.orgSlug;\n return headers;\n }\n\n private async parse<T>(res: Response): Promise<T> {\n const body = await res.json().catch(() => undefined);\n if (!res.ok) throw new ActionsApiError(res.status, errorMessage(body, res.status), body);\n return body as T;\n }\n}\n\nfunction errorMessage(body: unknown, status: number): string {\n if (body && typeof body === 'object' && 'error' in body && typeof (body as { error: unknown }).error === 'string') {\n return (body as { error: string }).error;\n }\n return `Request failed with status ${status}`;\n}\n\n/** Minimal SSE reader: yields the JSON payload of each `data:` event. */\nexport async function* readSseEvents(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<unknown> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let idx;\n while ((idx = buffer.indexOf('\\n\\n')) !== -1) {\n const event = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n for (const line of event.split('\\n')) {\n if (line.startsWith('data: ')) {\n yield JSON.parse(line.slice(6));\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/** `readSseEvents` with the `event:` name preserved alongside the JSON payload. */\nexport async function* readSseNamedEvents(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<{ event: string; data: unknown }> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let idx;\n while ((idx = buffer.indexOf('\\n\\n')) !== -1) {\n const frame = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n let event = 'message';\n const dataLines: string[] = [];\n for (const line of frame.split('\\n')) {\n if (line.startsWith('event: ')) event = line.slice(7);\n else if (line.startsWith('data: ')) dataLines.push(line.slice(6));\n }\n if (dataLines.length > 0) {\n yield { event, data: JSON.parse(dataLines.join('\\n')) };\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/** `id:jobId:step:offset` — the run-stream watch cursor wire format. */\nexport function encodeWatchCursor(\n id: string,\n jobId: string,\n step: number | 'runner' | null,\n offset: number,\n): string {\n const stepPart = step === null ? '-' : step === 'runner' ? 'runner' : String(step);\n return `${id}:${jobId}:${stepPart}:${offset}`;\n}\n\n/** The subset of `@benchsdk/cli`'s `resolveAuth` result Actions needs. */\nexport type StoredPlatformAuth = { apiKey?: string; token?: string; orgSlug?: string; orgId?: string };\nexport type StoredPlatformAuthResolver = (opts: { baseUrl: string }) => Promise<StoredPlatformAuth>;\n\nconst NO_CREDENTIALS_HINT =\n 'Set COMPUTE_API_KEY, pass --api-key, or run `compute login`.';\n\n/**\n * Precedence: `--api-key` > `COMPUTE_API_KEY` > `BENCHMARKS_PLATFORM_API_KEY`\n * (legacy) > platform OAuth credentials stored by `compute login`\n * (`~/.benchsdk/credentials.json`, via `@benchsdk/cli`'s `resolveAuth`, which\n * refreshes an expired access token but never opens a browser). `compute\n * login` writes the same store, so a platform login covers these commands.\n */\nexport async function resolveActionsAuth(\n opts: {\n apiKey?: string;\n baseUrl?: string;\n allowUntrustedHost?: boolean;\n /** One-off org override: sent as X-Org-Slug (also settable via COMPUTE_ORG). */\n org?: string;\n },\n resolveStored: StoredPlatformAuthResolver = resolveStoredPlatformAuth,\n): Promise<ActionsAuth> {\n const baseUrl = (\n opts.baseUrl ||\n process.env.COMPUTE_PLATFORM_URL ||\n process.env.BENCHMARKS_PLATFORM_URL || // legacy name\n DEFAULT_BASE_URL\n ).replace(/\\/+$/, '');\n\n // One-off org override: --org flag or COMPUTE_ORG sends X-Org-Slug on every\n // request. Falls back to the stored login's saved org. The platform ignores\n // the header for org API keys (they are already org-scoped).\n let orgSlug = opts.org || process.env.COMPUTE_ORG || undefined;\n\n // The bearer key is attached to every request, so an attacker-controlled\n // --base-url would exfiltrate it. Only trusted hosts are allowed silently;\n // anything else must be opted into with --allow-untrusted-host.\n if (!opts.allowUntrustedHost && !isTrustedActionsHost(baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host',\n `Refusing to send the API key to ${baseUrl} — it is not a computesdk.com or localhost host. ` +\n 'If this is a self-hosted/dev deployment you trust, pass --allow-untrusted-host.',\n );\n }\n // Host trust and transport security are separate: --allow-untrusted-host\n // says who may receive the key, never that it may travel in plaintext.\n if (!isSecureActionsTransport(baseUrl)) {\n throw new ActionsCliError(\n 'insecure_transport',\n `Refusing to send the API key over plaintext HTTP to ${baseUrl}. ` +\n 'Use an https:// base URL; http:// is only allowed for localhost/loopback.',\n );\n }\n\n // `||` not `??`: empty-string env vars (common in CI matrices) should fall\n // through to the next source, not count as configured.\n let apiKey =\n opts.apiKey ||\n process.env.COMPUTE_API_KEY ||\n process.env.BENCHMARKS_PLATFORM_API_KEY || // legacy name\n undefined;\n if (!apiKey) {\n // Stored platform OAuth is only ever resolved (and refreshed) for trusted\n // hosts. --allow-untrusted-host opts an explicit key into a host, not the\n // user's saved session.\n if (!isTrustedActionsHost(baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host_stored_auth',\n `Refusing to use stored platform credentials with untrusted host ${baseUrl}. ` +\n 'Pass --api-key or set COMPUTE_API_KEY to use an explicit key with --allow-untrusted-host.',\n );\n }\n let stored: StoredPlatformAuth;\n try {\n stored = await resolveStored({ baseUrl });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n // `@benchsdk/cli`'s \"nothing stored\" message names `bench` commands and\n // env vars that only apply to that CLI; keep ours for that case and\n // surface the reason only for expired/failed-refresh sessions.\n const detail = reason.startsWith('No credentials found') ? 'No API key.' : reason;\n throw new ActionsCliError('no_credentials', `${detail} ${NO_CREDENTIALS_HINT}`);\n }\n apiKey = stored.apiKey || stored.token || undefined;\n // The stored orgSlug is only a cache of the last `org use` on this\n // machine — the server's consent row is the source of truth, and\n // sending it would pin this machine to a stale org after a switch\n // elsewhere. Only --org/COMPUTE_ORG send X-Org-Slug.\n }\n if (!apiKey) {\n throw new ActionsCliError('no_credentials', `No API key. ${NO_CREDENTIALS_HINT}`);\n }\n return { apiKey, baseUrl, ...(orgSlug && { orgSlug }) };\n}\n\nasync function resolveStoredPlatformAuth(opts: { baseUrl: string }): Promise<StoredPlatformAuth> {\n const { resolveAuth } = await import('@benchsdk/cli');\n const auth = await resolveAuth({ baseUrl: opts.baseUrl });\n return { apiKey: auth.apiKey, token: auth.token, orgSlug: auth.orgSlug, orgId: auth.orgId };\n}\n\nfunction isLoopbackHost(host: string): boolean {\n return host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host === '::1';\n}\n\n/** https://, or http:// to a loopback host only. */\nexport function isSecureActionsTransport(baseUrl: string): boolean {\n let url: URL;\n try {\n url = new URL(baseUrl);\n } catch {\n return false;\n }\n if (url.protocol === 'https:') return true;\n return url.protocol === 'http:' && isLoopbackHost(url.hostname);\n}\n\n/** computesdk.com (and subdomains) or localhost — safe to receive the API key. */\nexport function isTrustedActionsHost(baseUrl: string): boolean {\n let host: string;\n try {\n host = new URL(baseUrl).hostname;\n } catch {\n return false;\n }\n return host === 'computesdk.com' || host.endsWith('.computesdk.com') || isLoopbackHost(host);\n}\n","/**\n * `compute market` — the sell side of the compute market: post listings,\n * reprice/pause/resume/withdraw them, read the book, and read payouts.\n *\n * Auth: identical to `compute actions` — --api-key / COMPUTE_API_KEY / the\n * stored `compute login` (or `compute bench auth login`) session. The key must belong to an org\n * the platform flags `market_provider`; the seller principal (which\n * executor provider these listings sell) is resolved server-side from the\n * key. Types mirror the wire shapes in benchmarks-platform `lib/market/*`\n * describe functions — keep them in sync by hand; the API is the contract.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { ActionsCliError } from './actions-client.js';\nimport {\n client,\n fail,\n output,\n parseInputs,\n safeTerm,\n secretValueClient,\n usageErrorOutput,\n type CommonOpts,\n} from './actions.js';\n\n// ─── Wire types (mirror benchmarks-platform lib/market describes) ───────────\n\nexport type MarketRatePer = 'second' | 'minute' | 'hour';\nexport type MarketAskStatus = 'live' | 'paused' | 'withdrawn';\n\n/** `describeAsk` — one row of GET /api/v1/market/asks. */\nexport interface MarketAsk {\n id: string;\n provider: string;\n region: string | null;\n size: string;\n /** The lane the listing sells into — 'actions' on listings posted before lanes. */\n useCase?: 'actions' | 'sandbox';\n resources: { cpus?: number; memoryMb?: number; ephemeralDiskMb?: number };\n usd: number;\n per: MarketRatePer;\n takeBps: number;\n maxConcurrent: number;\n status: MarketAskStatus;\n /** status === 'live' AND unexpired — a 'live' ask past expiresAt shows as expired. */\n live: boolean;\n expiresAt: string | null;\n rollover: boolean;\n /** A rate edit queued for the next renewal window, when one exists. */\n pendingUsd: number | null;\n pendingPer: MarketRatePer | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface MarketCredentialField {\n name: string;\n label: string;\n secret: boolean;\n required?: boolean;\n placeholder?: string;\n}\n\n/** `describeMarketProviderMe` — GET /api/v1/market/provider. */\nexport interface MarketProvider {\n id: string;\n name: string;\n provider: string;\n organizationId: string | null;\n keyHint: string;\n executorCredentialConnected: boolean;\n revokedAt: string | null;\n createdAt: string;\n /** The lanes this principal is approved to sell into, e.g. [\"actions\", \"sandbox\"]. */\n useCases?: string[];\n /** Size presets the bound executor sells, e.g. small/medium/large. */\n sizes: {\n name: string;\n label: string;\n resources: { cpus?: number; memoryMb?: number; ephemeralDiskMb?: number };\n }[];\n regions: string[];\n /** The credential fields `credential connect` must fill ([] = ambient auth). */\n credentialFields: MarketCredentialField[];\n}\n\n/** `OrderBook` — GET /api/v1/market/book. */\nexport interface MarketOrderBook {\n asks: {\n id: string;\n provider: string;\n providerName: string;\n region: string | null;\n size: string;\n /** The lane the listing sells into — 'actions' on asks posted before lanes. */\n useCase?: 'actions' | 'sandbox';\n usd: number;\n per: MarketRatePer;\n takeBps: number;\n maxConcurrent: number;\n expiresAt: string | null;\n rollover: boolean;\n updatedAt: string;\n }[];\n bids: {\n id: string;\n organizationId: string;\n size: string;\n /** The lane the offer buys on — 'actions' on bids posted before lanes. */\n useCase?: 'actions' | 'sandbox';\n region: string | null;\n maxUsd: number;\n per: MarketRatePer;\n createdAt: string;\n expiresAt: string | null;\n }[];\n fills: {\n id: string;\n askId: string;\n provider: string;\n size: string;\n /** The lane the sale cleared on — 'actions' on fills from before lanes. */\n useCase?: 'actions' | 'sandbox';\n region: string | null;\n usd: number;\n per: MarketRatePer;\n /** 'replaced' = the seller took the capacity back mid-sale. */\n status: 'live' | 'closed' | 'replaced';\n createdAt: string;\n }[];\n prices: { askId: string; usd: number; per: MarketRatePer; changedAt: string }[];\n}\n\n/** One evicted sale — POST /api/v1/market/fills/:id/replace and each entry of the listing replace. */\nexport interface MarketReplacedFill {\n fillId: string;\n askId: string;\n /** Charged to the buyer — the seconds the fill actually lived. */\n settledMicroUsd: number;\n /** An Actions job on the evicted capacity re-places on the buyer's next provider. */\n jobRequeued: boolean;\n}\n\nexport type MarketReplaceFillOutcome =\n | { ok: true; fill: MarketReplacedFill }\n | { ok: false; status: number; error: string };\n\n/** POST /api/v1/market/listings/:id/replace — paused listing + per-fill outcomes. */\nexport interface MarketListingReplaceResult {\n listing: MarketAsk;\n fills: MarketReplaceFillOutcome[];\n}\n\n/** `describeSettlement` — one row of GET /api/v1/market/settlements. */\nexport interface MarketSettlement {\n id: string;\n providerId: string;\n provider?: string;\n periodStart: string;\n periodEnd: string;\n vcpuSeconds: number;\n grossUsd: number;\n netUsd: number;\n grossMicroUsd: number;\n netMicroUsd: number;\n invoiceRef: string | null;\n paidAt: string | null;\n createdAt: string;\n}\n\n// ─── Parsing helpers (pure, exported for tests) ─────────────────────────────\n\nconst USD_RE = /^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/;\nconst RATE_UNITS: MarketRatePer[] = ['second', 'minute', 'hour'];\nconst MARKET_LANES = ['actions', 'sandbox'] as const;\nexport type MarketLane = (typeof MARKET_LANES)[number];\n\n/**\n * `--use-case` → the lane the listing sells into / the book filters to.\n * Absent = 'actions', matching the API default.\n */\nexport function parseMarketLane(value: string | undefined): MarketLane {\n if (value === undefined) return 'actions';\n if (!MARKET_LANES.includes(value as MarketLane)) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--use-case must be ${MARKET_LANES.join(' or ')}, got \"${value}\".`,\n );\n }\n return value as MarketLane;\n}\n\n/**\n * `--price <usd>/<unit>` → the body's `usd`/`per`. The unit is required —\n * either inside the value (`0.12/hour`) or via `--per` — so a bare `--price\n * 0.12` never silently defaults to per-second pricing (same rule as\n * `sandboxes create --max-price`).\n */\nexport function parseRate(\n price: string | undefined,\n per: string | undefined,\n): { usd: number; per: MarketRatePer } {\n if (price === undefined) {\n throw new ActionsCliError('invalid_argument', 'A price is required — pass --price <usd>/<unit>.');\n }\n let usdText = price;\n let unit: string | undefined = per;\n const slash = price.indexOf('/');\n if (slash !== -1) {\n usdText = price.slice(0, slash);\n const inline = price.slice(slash + 1);\n if (per !== undefined && per !== inline) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--price \"${price}\" conflicts with --per \"${per}\".`,\n );\n }\n unit = inline;\n }\n const usd = Number(usdText);\n if (!USD_RE.test(usdText) || !Number.isFinite(usd) || usd <= 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --price \"${price}\". Expected a positive dollar amount (e.g. 0.12/hour).`,\n );\n }\n if (unit === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n '--price needs a unit — write it as <usd>/<unit> (e.g. --price 0.12/hour) or pass --per hour.',\n );\n }\n if (!RATE_UNITS.includes(unit as MarketRatePer)) {\n throw new ActionsCliError(\n 'invalid_argument',\n `The unit must be second, minute, or hour, got \"${unit}\".`,\n );\n }\n return { usd, per: unit as MarketRatePer };\n}\n\n/** `--capacity` → `maxConcurrent`: a positive integer, absent = server default (1). */\nexport function parseCapacity(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n const n = Number(value);\n if (!Number.isInteger(n) || n <= 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --capacity \"${value}\". Expected a positive integer.`,\n );\n }\n return n;\n}\n\n/** `--expires-in` → `expiresInHours`: a positive number of hours. */\nexport function parseExpiresIn(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n const hours = Number(value);\n if (!Number.isFinite(hours) || hours <= 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --expires-in \"${value}\". Expected a positive number of hours.`,\n );\n }\n return hours;\n}\n\n/**\n * The `POST /api/v1/market/asks` create body for `sell`: `{size, region?,\n * usd, per, maxConcurrent?, expiresInHours?, rollover?}`.\n */\nexport function sellBody(opts: {\n size: string;\n price?: string;\n per?: string;\n region?: string;\n capacity?: string;\n expiresIn?: string;\n renew?: boolean;\n useCase?: string;\n}): Record<string, unknown> {\n const rate = parseRate(opts.price, opts.per);\n const maxConcurrent = parseCapacity(opts.capacity);\n const expiresInHours = parseExpiresIn(opts.expiresIn);\n if (opts.renew && expiresInHours === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n '--renew requires --expires-in — a standing listing never expires.',\n );\n }\n return {\n size: opts.size,\n useCase: parseMarketLane(opts.useCase),\n ...(opts.region !== undefined && { region: opts.region }),\n usd: rate.usd,\n per: rate.per,\n ...(maxConcurrent !== undefined && { maxConcurrent }),\n ...(expiresInHours !== undefined && { expiresInHours }),\n ...(opts.renew && { rollover: true }),\n };\n}\n\n/**\n * The `POST /api/v1/market/asks` update body for `price`/`pause`/`resume`:\n * `{askId, usd?, per?, maxConcurrent?, status?}` — exactly one of the\n * change fields must be present.\n */\nexport function listingPatchBody(\n listingId: string,\n change: {\n price?: string;\n per?: string;\n capacity?: string;\n status?: 'live' | 'paused';\n },\n): Record<string, unknown> {\n const body: Record<string, unknown> = { askId: listingId };\n if (change.price !== undefined || change.per !== undefined) {\n const rate = parseRate(change.price, change.per);\n body.usd = rate.usd;\n body.per = rate.per;\n }\n const maxConcurrent = parseCapacity(change.capacity);\n if (maxConcurrent !== undefined) body.maxConcurrent = maxConcurrent;\n if (change.status !== undefined) body.status = change.status;\n if (body.usd === undefined && body.maxConcurrent === undefined && body.status === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Nothing to change — pass --price, --capacity, or a status command.',\n );\n }\n return body;\n}\n\n/**\n * The env var `credential connect` reads a field from: the provider and\n * field names upper-snake-cased — tensorlake + apiKey → TENSORLAKE_API_KEY,\n * blaxel + workspace → BLAXEL_WORKSPACE, namespace + token → NAMESPACE_TOKEN.\n * Secrets belong here (or a session env), never in argv where shell history\n * keeps them.\n */\nexport function credentialEnvVar(providerId: string, fieldName: string): string {\n const snake = (s: string) =>\n s\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^A-Za-z0-9]+/g, '_')\n .toUpperCase();\n return `${snake(providerId)}_${snake(fieldName)}`;\n}\n\nexport interface CredentialResolution {\n /** Every field's value, declared fields only. */\n values: Record<string, string>;\n /** Required fields with no value from either source. */\n missing: MarketCredentialField[];\n /** Field names taken from --field (visible in shell history). */\n fromFlag: string[];\n /** The env var each declared field was looked up under. */\n envNames: Record<string, string>;\n}\n\n/**\n * Resolve each declared credential field: an explicit `--field name=value`\n * wins, then the `<PROVIDER>_<FIELD>` env var. Empty strings count as\n * missing on both.\n */\nexport function credentialValues(\n providerId: string,\n fields: MarketCredentialField[],\n overrides: Record<string, string>,\n env: Record<string, string | undefined> = process.env,\n): CredentialResolution {\n const declared = new Set(fields.map((f) => f.name));\n const unknown = Object.keys(overrides).filter((name) => !declared.has(name));\n if (unknown.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `${providerId} takes no credential field \"${unknown.join('\", \"')}\" — expected one of ${fields\n .map((f) => f.name)\n .join(', ')}.`,\n );\n }\n const values: Record<string, string> = {};\n const fromFlag: string[] = [];\n const missing: MarketCredentialField[] = [];\n const envNames: Record<string, string> = {};\n for (const field of fields) {\n envNames[field.name] = credentialEnvVar(providerId, field.name);\n const fromOverride = overrides[field.name];\n if (fromOverride !== undefined && fromOverride.trim() !== '') {\n values[field.name] = fromOverride.trim();\n fromFlag.push(field.name);\n continue;\n }\n const fromEnv = env[envNames[field.name]];\n if (fromEnv !== undefined && fromEnv.trim() !== '') {\n values[field.name] = fromEnv.trim();\n continue;\n }\n if (field.required !== false) missing.push(field);\n }\n return { values, missing, fromFlag, envNames };\n}\n\n/**\n * The `POST /api/v1/market/provider/credential` body: `{key}` for a\n * single-field executor, `{fields}` for a multi-field one — the same two\n * shapes the org provider-key routes take.\n */\nexport function credentialBody(\n fields: MarketCredentialField[],\n values: Record<string, string>,\n): Record<string, unknown> {\n if (fields.length === 1) {\n return { key: values[fields[0].name] };\n }\n return { fields: values };\n}\n\n// ─── Formatting (pure, exported for tests) ──────────────────────────────────\n\n/** `$0.12`, `$5` — micro-USD-precision dollars without trailing zeros. */\nexport function formatUsd(usd: number): string {\n return `$${usd.toFixed(6).replace(/\\.?0+$/, '')}`;\n}\n\n/** `$0.12/second` — how a listing (or offer, or sale) is priced. */\nexport function formatRate(usd: number, per: string): string {\n return `${formatUsd(usd)}/${per}`;\n}\n\n/** The human status: withdrawn > paused > expired > live. */\nexport function formatListingStatus(ask: Pick<MarketAsk, 'status' | 'live' | 'pendingUsd' | 'pendingPer'>): string {\n let label: string;\n if (ask.status === 'withdrawn') label = pc.gray('withdrawn');\n else if (ask.status === 'paused') label = pc.yellow('paused');\n else if (!ask.live) label = pc.gray('expired');\n else label = pc.green('live');\n if (ask.pendingUsd !== null && ask.pendingPer !== null) {\n label += pc.dim(` → ${formatRate(ask.pendingUsd, ask.pendingPer)} next window`);\n }\n return label;\n}\n\nexport function formatListingRow(ask: MarketAsk): string {\n const expiry = ask.expiresAt\n ? ask.rollover\n ? `renews ${ask.expiresAt}`\n : `expires ${ask.expiresAt}`\n : 'standing';\n return [\n ask.id,\n formatListingStatus(ask),\n pc.dim(ask.useCase === 'sandbox' ? 'sandbox' : 'actions'),\n safeTerm(ask.size),\n safeTerm(ask.region ?? '-'),\n formatRate(ask.usd, ask.per),\n pc.dim(`×${ask.maxConcurrent}`),\n pc.dim(expiry),\n ].join(' ');\n}\n\nexport function formatProviderStatus(p: MarketProvider): string {\n const lines: string[] = [];\n lines.push(`${pc.bold(safeTerm(p.name))} ${pc.dim(`selling ${safeTerm(p.provider)}`)}`);\n lines.push(`id: ${p.id}`);\n lines.push(\n `credential: ${\n p.executorCredentialConnected\n ? pc.green('connected')\n : pc.yellow('not connected — your listings cannot fill until `compute market credential connect`')\n }`,\n );\n if (p.revokedAt) lines.push(pc.red(`revoked: ${p.revokedAt}`));\n lines.push(\n `lanes: ${(p.useCases ?? ['actions']).join(', ')}`,\n );\n lines.push(\n `sizes: ${p.sizes.map((s) => `${s.name} (${s.label})`).join(', ') || '-'}`,\n );\n lines.push(`regions: ${p.regions.join(', ') || '-'}`);\n if (p.credentialFields.length > 0) {\n lines.push(\n `credential fields: ${p.credentialFields\n .map((f) => `${f.name}${f.secret ? ' (secret)' : ''}`)\n .join(', ')}`,\n );\n }\n lines.push(`created: ${p.createdAt}`);\n return lines.join('\\n');\n}\n\n/** The live book, plainly labeled: who's selling, who's buying, what cleared. */\nexport function formatBook(book: MarketOrderBook): string {\n const lines: string[] = [];\n const lane = (useCase?: 'actions' | 'sandbox') =>\n pc.dim(useCase === 'sandbox' ? 'sandbox' : 'actions');\n lines.push(pc.bold(\"sellers' asking prices\"));\n if (book.asks.length === 0) lines.push(pc.dim(' no listings are live'));\n for (const ask of book.asks) {\n const where = ask.region ? safeTerm(ask.region) : 'any region';\n const expiry = ask.expiresAt\n ? pc.dim(ask.rollover ? ` renews ${ask.expiresAt}` : ` until ${ask.expiresAt}`)\n : '';\n lines.push(\n ` ${lane(ask.useCase)} ${formatRate(ask.usd, ask.per)} ${safeTerm(ask.providerName)} ${safeTerm(ask.size)} ${where} up to ${ask.maxConcurrent} at once${expiry}`,\n );\n }\n lines.push('');\n lines.push(pc.bold('buyer offers'));\n if (book.bids.length === 0) lines.push(pc.dim(' no open offers'));\n for (const bid of book.bids) {\n const where = bid.region ? safeTerm(bid.region) : 'anywhere';\n lines.push(\n ` ${lane(bid.useCase)} pays up to ${formatRate(bid.maxUsd, bid.per)} ${safeTerm(bid.size)} ${where} ${pc.dim(`posted ${bid.createdAt}`)}`,\n );\n }\n lines.push('');\n lines.push(pc.bold('recent sales'));\n if (book.fills.length === 0) lines.push(pc.dim(' nothing has sold yet'));\n for (const fill of book.fills) {\n const statusNote =\n fill.status === 'replaced'\n ? pc.yellow(' replaced')\n : fill.status === 'closed'\n ? pc.gray(' closed')\n : '';\n lines.push(\n ` ${pc.dim(fill.id)} ${lane(fill.useCase)} ${formatRate(fill.usd, fill.per)} ${safeTerm(fill.provider)} ${safeTerm(fill.size)} ${safeTerm(fill.region ?? '-')} ${pc.dim(fill.createdAt)}${statusNote}`,\n );\n }\n return lines.join('\\n');\n}\n\n/** `replaced f-1 settled $0.0003` (+ a note when an Actions job re-places). */\nexport function formatReplacedFill(fill: MarketReplacedFill): string {\n const settled = formatUsd(fill.settledMicroUsd / 1e6);\n const job = fill.jobRequeued\n ? pc.dim(\" — job re-places on the buyer's next provider\")\n : '';\n return `replaced ${pc.cyan(fill.fillId)} settled ${settled}${job}`;\n}\n\n/**\n * `compute market replace` resolves to exactly one endpoint: `--fill` evicts\n * one sale, a listing ID pauses the listing and evicts every sale on it.\n */\nexport function replaceTarget(\n listingId: string | undefined,\n fillId: string | undefined,\n): { path: string; scope: 'listing' | 'fill' } {\n if (fillId !== undefined) {\n return {\n path: `/api/v1/market/fills/${encodeURIComponent(fillId)}/replace`,\n scope: 'fill',\n };\n }\n if (listingId === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Nothing to replace — pass a listing ID or --fill <fill-id>.',\n );\n }\n return {\n path: `/api/v1/market/listings/${encodeURIComponent(listingId)}/replace`,\n scope: 'listing',\n };\n}\n\nexport function formatSettlementRow(s: MarketSettlement): string {\n const period = `${s.periodStart.slice(0, 10)} → ${s.periodEnd.slice(0, 10)}`;\n const paid = s.paidAt\n ? pc.green(`paid ${s.paidAt.slice(0, 10)}`)\n : s.invoiceRef\n ? pc.yellow(`invoiced ${safeTerm(s.invoiceRef)}`)\n : pc.dim('unpaid');\n return [\n pc.dim(period),\n `${s.vcpuSeconds.toLocaleString('en-US')} vCPU·s`,\n `gross ${formatUsd(s.grossUsd)}`,\n `net ${formatUsd(s.netUsd)}`,\n paid,\n ].join(' ');\n}\n\n// ─── Commands ───────────────────────────────────────────────────────────────\n\nexport function registerMarketCommands(program: Command): void {\n const market = program\n .command('market')\n .description('Sell compute capacity on the compute market')\n .configureOutput({ outputError: usageErrorOutput });\n\n const common = (cmd: Command) =>\n cmd\n .option('--api-key <key>', 'API key (default: $COMPUTE_API_KEY)')\n .option('--base-url <url>', 'API base URL (default: https://platform.computesdk.com)')\n .option('--org <slug>', 'organization slug for this command (or $COMPUTE_ORG)')\n .option('--allow-untrusted-host', 'send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)')\n .option('--json', 'print machine-readable JSON');\n\n common(\n market\n .command('listings')\n .alias('list')\n .description('Your listings — live, paused, expired, and withdrawn'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { asks } = await (await client(opts)).get<{ asks: MarketAsk[] }>(\n '/api/v1/market/asks',\n );\n output(opts, asks, (rows) => {\n if (rows.length === 0) {\n console.log('No listings yet — post one with `compute market sell`.');\n return;\n }\n for (const ask of rows) console.log(formatListingRow(ask));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('sell')\n .description('Post a listing: sell capacity at a price')\n .requiredOption('--price <usd/unit>', 'price per unit of time (e.g. 0.12/hour)')\n .option('--per <unit>', 'unit for a bare --price usd (second, minute, or hour)')\n .option('--size <tier>', 'size tier to sell (default: medium, else the provider\\'s first tier)')\n .option('--use-case <lane>', 'lane to sell into: actions or sandbox (default: actions)')\n .option('--region <region>', 'region to sell in (default: anywhere the provider runs)')\n .option('--capacity <n>', 'max simultaneous fills (default: 1)')\n .option('--expires-in <hours>', 'delist after this many hours (default: standing)')\n .option('--renew', 're-list for the same window each time it expires (requires --expires-in)'),\n ).action(async (opts: CommonOpts & { price: string; per?: string; size?: string; region?: string; capacity?: string; expiresIn?: string; renew?: boolean; useCase?: string }) => {\n try {\n const c = await client(opts);\n // Validate the lane before any network writes — an unapproved lane\n // still fails server-side with market_lane_not_approved.\n const useCase = parseMarketLane(opts.useCase);\n let size = opts.size;\n if (size === undefined) {\n // The tier is required by the API; when the seller doesn't name one,\n // the provider's middle tier (or first) is the sensible default.\n const { provider } = await c.get<{ provider: MarketProvider }>(\n '/api/v1/market/provider',\n );\n const preset =\n provider.sizes.find((s) => s.name === 'medium') ?? provider.sizes[0];\n if (!preset) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--size is required — ${provider.provider} advertises no size tiers.`,\n );\n }\n size = preset.name;\n console.error(pc.dim(`no --size given — listing at \"${size}\"`));\n }\n const result = await c.post<{ ask: MarketAsk }>(\n '/api/v1/market/asks',\n sellBody({ ...opts, size, useCase }),\n );\n output(opts, result, (r) => {\n console.log(`listed ${pc.cyan(r.ask.id)}`);\n console.log(formatListingRow(r.ask));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('price')\n .description('Reprice a listing')\n .argument('<listing-id>', 'listing ID')\n .requiredOption('--price <usd/unit>', 'new price per unit of time (e.g. 0.08/hour)')\n .option('--per <unit>', 'unit for a bare --price usd (second, minute, or hour)'),\n ).action(async (listingId: string, opts: CommonOpts & { price: string; per?: string }) => {\n try {\n const result = await (await client(opts)).post<{ ask: MarketAsk }>(\n '/api/v1/market/asks',\n listingPatchBody(listingId, { price: opts.price, per: opts.per }),\n );\n output(opts, result, (r) => {\n // A committed-window (rollover) listing keeps its rate in usd/per\n // until the window renews; the new rate sits in pendingUsd/pendingPer.\n const rate =\n r.ask.pendingUsd !== null && r.ask.pendingPer !== null\n ? `${formatRate(r.ask.pendingUsd, r.ask.pendingPer)} ${pc.dim('(applies next window)')}`\n : formatRate(r.ask.usd, r.ask.per);\n console.log(`repriced ${pc.cyan(r.ask.id)} ${rate}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const setStatus = async (\n listingId: string,\n status: 'live' | 'paused',\n opts: CommonOpts,\n ): Promise<void> => {\n try {\n const result = await (await client(opts)).post<{ ask: MarketAsk }>(\n '/api/v1/market/asks',\n listingPatchBody(listingId, { status }),\n );\n output(opts, result, (r) => {\n console.log(`${status === 'live' ? 'resumed' : 'paused'} ${pc.cyan(r.ask.id)}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n };\n\n common(\n market\n .command('pause')\n .description('Pause a listing — it stays posted but cannot fill')\n .argument('<listing-id>', 'listing ID'),\n ).action((listingId: string, opts: CommonOpts) => setStatus(listingId, 'paused', opts));\n\n common(\n market\n .command('resume')\n .description('Resume a paused listing')\n .argument('<listing-id>', 'listing ID'),\n ).action((listingId, opts: CommonOpts) => setStatus(listingId, 'live', opts));\n\n common(\n market\n .command('withdraw')\n .description('Withdraw a listing — it leaves the book for good')\n .argument('<listing-id>', 'listing ID'),\n ).action(async (listingId: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ ask: MarketAsk }>(\n `/api/v1/market/asks?id=${encodeURIComponent(listingId)}`,\n );\n output(opts, result, (r) => {\n console.log(`withdrew ${pc.cyan(r.ask.id)}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('replace')\n .description(\n 'Take capacity back: evict a sale, or pause a listing and evict every sale on it.\\n' +\n \"An evicted Actions job restarts on the buyer's next provider; the buyer pays\\n\" +\n 'only for the seconds the sale actually ran.',\n )\n .argument('[listing-id]', 'listing to pause and evict every sale on')\n .option('--fill <fill-id>', 'evict one sale without touching the listing'),\n ).action(\n async (\n listingId: string | undefined,\n opts: CommonOpts & { fill?: string },\n ) => {\n try {\n const target = replaceTarget(listingId, opts.fill);\n const c = await client(opts);\n if (target.scope === 'fill') {\n const result = await c.post<{ fill: MarketReplacedFill }>(target.path, {});\n output(opts, result, (r) => console.log(formatReplacedFill(r.fill)));\n } else {\n const result = await c.post<MarketListingReplaceResult>(target.path, {});\n output(opts, result, (r) => {\n console.log(`paused ${pc.cyan(r.listing.id)}`);\n if (r.fills.length === 0) {\n console.log(pc.dim(' no live sales to evict'));\n return;\n }\n for (const f of r.fills) {\n if (f.ok) console.log(formatReplacedFill(f.fill));\n else console.log(pc.red(` could not evict a sale — ${f.error}`));\n }\n });\n // A partial eviction is not success: some sales are still running.\n if (result.fills.some((f) => !f.ok)) process.exitCode = 1;\n }\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n common(\n market\n .command('book')\n .description(\"Live prices: sellers' asking prices, buyer offers, recent sales\")\n .option('--use-case <lane>', 'only this lane: actions or sandbox (default: both)'),\n ).action(async (opts: CommonOpts & { useCase?: string }) => {\n try {\n const lane = opts.useCase === undefined ? undefined : parseMarketLane(opts.useCase);\n const book = await (await client(opts)).get<MarketOrderBook>(\n `/api/v1/market/book${lane ? `?useCase=${lane}` : ''}`,\n );\n output(opts, book, (b) => console.log(formatBook(b)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('settlements')\n .description('Your monthly payout reports'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { settlements } = await (await client(opts)).get<{\n settlements: MarketSettlement[];\n }>('/api/v1/market/settlements');\n output(opts, settlements, (rows) => {\n if (rows.length === 0) {\n console.log('No settlements yet.');\n return;\n }\n for (const s of rows) console.log(formatSettlementRow(s));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('status')\n .description('Who you are on the market: seller identity, credential, sizes, regions'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { provider } = await (await client(opts)).get<{\n provider: MarketProvider;\n }>('/api/v1/market/provider');\n output(opts, provider, (p) => console.log(formatProviderStatus(p)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const credential = market\n .command('credential')\n .description('Connect the credential your listings fill under');\n\n common(\n credential\n .command('connect')\n .description(\n 'Save the executor credential your sold capacity runs under. Each field is read from\\n' +\n 'a <PROVIDER>_<FIELD> env var (e.g. TENSORLAKE_API_KEY) — never pass secrets in argv;\\n' +\n '--field name=value overrides a field (visible in shell history)',\n )\n .option('--field <pairs...>', 'credential fields as name=value (prefer env vars for secrets)'),\n ).action(async (opts: CommonOpts & { field?: string[] }) => {\n try {\n const c = await secretValueClient(opts, 'credential values');\n const { provider } = await c.get<{ provider: MarketProvider }>(\n '/api/v1/market/provider',\n );\n if (provider.credentialFields.length === 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `${provider.provider} authenticates with the deployment's own identity — there is no credential to connect.`,\n );\n }\n const resolved = credentialValues(\n provider.provider,\n provider.credentialFields,\n parseInputs(opts.field),\n );\n if (resolved.missing.length > 0) {\n const hints = resolved.missing\n .map((f) => ` export ${resolved.envNames[f.name]}=… # ${f.label}`)\n .join('\\n');\n throw new ActionsCliError(\n 'invalid_argument',\n `Missing credential field${resolved.missing.length === 1 ? '' : 's'}. Set:\\n${hints}`,\n );\n }\n if (resolved.fromFlag.some((name) => provider.credentialFields.find((f) => f.name === name)?.secret)) {\n console.error(\n pc.yellow('note: a secret passed via --field stays in your shell history — prefer the env vars.'),\n );\n }\n const result = await c.post<{ provider: MarketProvider }>(\n '/api/v1/market/provider/credential',\n credentialBody(provider.credentialFields, resolved.values),\n );\n output(opts, result, (r) => {\n console.log(`connected ${pc.cyan(safeTerm(r.provider.name))} credential saved`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n credential\n .command('disconnect')\n .description('Remove the stored credential — listings stop filling until a new one connects'),\n ).action(async (opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ provider: MarketProvider }>(\n '/api/v1/market/provider/credential',\n );\n output(opts, result, (r) => {\n console.log(`disconnected ${pc.cyan(safeTerm(r.provider.name))} credential removed`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * `compute sandboxes` — drive sandboxes placed through the platform's\n * `/api/v1/sandboxes` API: create/list/get/destroy, exec commands, spawn and\n * control detached processes, read/write the filesystem, and resolve port\n * URLs.\n *\n * Auth: identical to `compute actions`/`compute market` — --api-key /\n * COMPUTE_API_KEY / the stored `compute login` session. Types\n * mirror the wire shapes in benchmarks-platform `lib/sandboxes/*` — keep\n * them in sync by hand; the API is the contract.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport type { ActionsClient } from './actions-client.js';\nimport {\n client,\n fail,\n output,\n parseInputs,\n safeTerm,\n usageErrorOutput,\n type CommonOpts,\n} from './actions.js';\n\n/**\n * `--max-price <usd>/<unit>` → the body's `maxPrice` / the quote's\n * maxPriceUsd+maxPricePer params. The unit is required — either inside the\n * value (`0.12/hour`) or via `--max-price-per` — so a bare `--max-price\n * 0.12` never silently defaults to per-second pricing.\n */\nfunction parseMaxPrice(\n value: string | undefined,\n per: string | undefined,\n): { usd: number; per: 'second' | 'minute' | 'hour' } | undefined {\n if (value === undefined) {\n if (per !== undefined) throw new Error('--max-price-per requires --max-price.');\n return undefined;\n }\n let usdText = value;\n let unit: string | undefined = per;\n const slash = value.indexOf('/');\n if (slash !== -1) {\n usdText = value.slice(0, slash);\n const inline = value.slice(slash + 1);\n if (per !== undefined && per !== inline) {\n throw new Error(`--max-price \"${value}\" conflicts with --max-price-per \"${per}\".`);\n }\n unit = inline;\n }\n const usd = Number(usdText);\n if (!/^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/.test(usdText) || !Number.isFinite(usd) || usd <= 0) {\n throw new Error(`Invalid --max-price \"${value}\". Expected a positive dollar amount like 0.12/hour.`);\n }\n if (unit !== 'second' && unit !== 'minute' && unit !== 'hour') {\n throw new Error(\n '--max-price needs a unit — write it as <usd>/<unit> (e.g. --max-price 0.12/hour) or pass --max-price-per hour.',\n );\n }\n return { usd, per: unit };\n}\n\n// ─── Wire types (mirror benchmarks-platform lib/sandboxes) ──────────────────\n\nexport interface SandboxCost {\n rate: { usd: number; unit: string } | null;\n runtimeSeconds: number;\n costUsd: number | null;\n settled: boolean;\n}\n\n/** `toSummary` — one row of GET /api/v1/sandboxes. */\nexport interface SandboxSummary {\n id: string;\n label: string | null;\n provider: string | null;\n providerSandboxId: string | null;\n status: 'creating' | 'running' | 'destroyed' | string;\n placementAttempts: unknown[];\n commandCount: number;\n secrets: string[];\n /** The `boot.image` asked for, and what the provider actually booted. */\n requestedImage: string | null;\n image: string | null;\n createdAt: string;\n lastCommandAt: string | null;\n destroyedAt: string | null;\n destroyError: string | null;\n /** How the sandbox was placed — source, order type, rate, max price, the\n * requested platform `size` and the seller's `box` on a market fill. */\n placement: {\n source: 'market' | 'own-key';\n size?: string | null;\n box?: {\n provider: string;\n sizeName: string | null;\n resources?: { cpus: number | null; memoryMb: number | null; ephemeralDiskMb: number | null };\n };\n orderType?: 'market' | 'limit';\n rate: { usd: number; per: string };\n maxPrice?: { usd: number; per: string };\n } | null;\n cost: SandboxCost;\n}\n\n/** `toDetail` — POST /sandboxes and GET /sandboxes/{id}. */\nexport interface SandboxDetail extends SandboxSummary {\n /** BYOK direct-attach descriptor — null on market fills and ambient providers. */\n attach: { provider: string; providerSandboxId: string; region: string | null } | null;\n}\n\nexport interface SandboxProcess {\n id: string;\n jobId: string;\n pid: number | null;\n command: string;\n cwd: string | null;\n envNames: string[];\n /** Whether the job's stdin pipe is open (spawn `--stdin`). */\n stdin: boolean;\n status: string;\n exitCode: number | null;\n signal: string | null;\n startedAt: string;\n exitedAt: string | null;\n}\n\nexport interface SandboxProcessStatus extends SandboxProcess {\n stdout: string;\n stderr: string;\n}\n\nexport interface CommandResult {\n commandId: string;\n exitCode: number;\n durationMs: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface FileEntry {\n name: string;\n type: 'file' | 'directory';\n size?: number;\n modified?: string;\n}\n\nexport type PathView =\n | { path: string; type: 'file'; content: string }\n | { path: string; type: 'directory'; entries: FileEntry[] };\n\n/** `snapshotView` — one row of GET /sandboxes/{id}/snapshots. */\nexport interface SandboxSnapshot {\n id: string;\n sandboxId: string;\n provider: string;\n region: string | null;\n providerSnapshotId: string;\n label: string | null;\n expiresAt: string | null;\n createdAt: string;\n deletedAt: string | null;\n}\n\n/** POSIX single-quote: argv survives intact through the remote `sh -lc`. */\nfunction shellQuote(arg: string): string {\n return `'${arg.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// ─── Rendering ───────────────────────────────────────────────────────────────\n\nfunction printSandbox(s: SandboxSummary): void {\n const attach = 'attach' in s ? (s as SandboxDetail).attach : undefined;\n console.log(`${pc.cyan(s.id)} ${s.status} ${s.provider ?? '—'} ${s.providerSandboxId ?? '—'}`);\n console.log(` label: ${s.label ?? '—'} commands: ${s.commandCount} created: ${s.createdAt}`);\n if (s.image !== undefined) {\n console.log(` image: ${s.image ?? '—'}${s.requestedImage !== null && s.requestedImage !== s.image ? ` ${pc.dim(`(requested: ${s.requestedImage})`)}` : ''}`);\n }\n if (s.destroyError) console.log(` destroyError: ${pc.red(s.destroyError)}`);\n if (s.placement) {\n const p = s.placement;\n const box = p.box\n ? ` / ${p.box.sizeName ?? 'custom'}${p.box.resources ? ` (${p.box.resources.cpus ?? '?'} vCPU / ${p.box.resources.memoryMb ?? '?'} MB)` : ''}`\n : '';\n console.log(\n ` provider: ${p.box?.provider ?? s.provider ?? '—'}${box}` +\n ` size: ${p.size ?? '—'} order: ${p.orderType ?? '—'} rate: $${p.rate.usd}/${p.rate.per}`,\n );\n }\n if (attach !== undefined) {\n console.log(\n attach === null\n ? ' attach: none (market fill or ambient provider — platform drive only)'\n : ` attach: ${attach.provider} / ${attach.providerSandboxId}${attach.region ? ` (${attach.region})` : ''}`,\n );\n }\n}\n\n/** The GET /sandboxes/quote payload — mirrors SandboxQuote on the platform. */\ninterface SandboxQuoteWire {\n ok: boolean;\n reason?: string;\n providerOrder: string[];\n orderType: 'market' | 'limit';\n placement?: {\n source: 'market' | 'own-key';\n provider: string;\n region: string | null;\n size: string | null;\n box?: {\n provider: string;\n sizeName: string | null;\n resources?: { cpus: number | null; memoryMb: number | null; ephemeralDiskMb: number | null };\n };\n };\n rate?: { usd: number; per: string };\n rateUsd?: { perSecond: number; perMinute: number; perHour: number };\n maxPrice?: { usd: number; per: string };\n estimatedCostUsd?: number;\n marketCapUsdPerHour?: number;\n protectionLimitUsdPerHour?: number;\n cheapestLiveUsdPerHour?: number;\n referenceUsdPerHour?: number;\n liveAskDepth?: number;\n creditBalanceUsd: number;\n requiredHoldUsd?: number;\n topUpPath?: string;\n}\n\nconst usd = (n: number | undefined, suffix = ''): string =>\n n === undefined ? '—' : `$${n.toFixed(4).replace(/0+$/, '').replace(/\\.$/, '.00')}${suffix}`;\n\nfunction printQuote(q: SandboxQuoteWire, timeoutMs?: string): void {\n console.log(`quote: ${q.ok ? pc.green('ok') : pc.red(q.reason ?? 'unfillable')}`);\n const box = q.placement?.box;\n console.log(\n ` size: ${q.placement?.size ?? '—'} provider: ${q.placement?.provider ?? '—'}` +\n (box ? ` box: ${box.sizeName ?? 'custom'} (${box.provider}${box.resources ? `, ${box.resources.cpus ?? '?'} vCPU / ${box.resources.memoryMb ?? '?'} MB` : ''})` : ''),\n );\n console.log(` order type: ${q.orderType} order: ${q.providerOrder.join(', ')}`);\n if (q.rateUsd) {\n console.log(` rate: ${usd(q.rateUsd.perHour, '/hour')} cheapest live: ${usd(q.cheapestLiveUsdPerHour, '/hr')} reference: ${usd(q.referenceUsdPerHour, '/hr')}`);\n } else if (q.rate) {\n console.log(` rate: $${q.rate.usd}/${q.rate.per}`);\n }\n const timeout = timeoutMs !== undefined ? ` for ${timeoutMs}ms` : '';\n console.log(` est. cost${timeout}: ${usd(q.estimatedCostUsd)} required hold: ${usd(q.requiredHoldUsd)}`);\n console.log(\n ` cap: ${q.maxPrice ? `$${q.maxPrice.usd}/${q.maxPrice.per}` : usd(q.marketCapUsdPerHour, '/hr')}` +\n ` protection limit: ${usd(q.protectionLimitUsdPerHour, '/hr')} balance: ${usd(q.creditBalanceUsd)}`,\n );\n if (!q.ok && q.topUpPath) console.log(` ${pc.dim(`→ ${q.topUpPath}`)}`);\n if (q.liveAskDepth !== undefined) console.log(` ${pc.dim(`live asks: ${q.liveAskDepth}`)}`);\n}\n\nfunction printProcess(p: SandboxProcess | SandboxProcessStatus): void {\n const exit = p.status === 'exited' ? `exit=${p.exitCode ?? '?'}${p.signal ? ` (${p.signal})` : ''}` : '';\n const stdin = p.stdin && p.status === 'running' ? ' [stdin open]' : '';\n console.log(`${pc.cyan(p.jobId)} ${p.status}${exit ? ' ' + exit : ''}${stdin} ${p.command}`);\n}\n\nfunction printSnapshot(s: SandboxSnapshot): void {\n const state = s.deletedAt !== null ? ` ${pc.dim(`(deleted ${s.deletedAt})`)}` : '';\n console.log(`${pc.cyan(s.id)} ${s.providerSnapshotId}${state}`);\n console.log(\n ` provider: ${s.provider}${s.region ? ` (${s.region})` : ''} label: ${s.label ?? '—'} created: ${s.createdAt}${s.expiresAt ? ` expires: ${s.expiresAt}` : ''}`,\n );\n}\n\n// ─── Commands ────────────────────────────────────────────────────────────────\n\ninterface LeadOptSpec {\n /** Accepted spellings, e.g. ['-e', '--env']. */\n aliases: string[];\n /** Commander-style camelCase key merged into the parsed options. */\n key: string;\n /** 'bool' takes no value; 'value' takes one; 'repeat' collects repeated values. */\n flag: 'bool' | 'value' | 'repeat';\n}\n\nconst AUTH_LEAD_OPTS: LeadOptSpec[] = [\n { aliases: ['--api-key'], key: 'apiKey', flag: 'value' },\n { aliases: ['--base-url'], key: 'baseUrl', flag: 'value' },\n { aliases: ['--allow-untrusted-host'], key: 'allowUntrustedHost', flag: 'bool' },\n { aliases: ['--org'], key: 'org', flag: 'value' },\n { aliases: ['--json'], key: 'json', flag: 'bool' },\n];\n\nconst EXEC_LEAD_OPTS: LeadOptSpec[] = [\n ...AUTH_LEAD_OPTS,\n { aliases: ['--timeout-ms'], key: 'timeoutMs', flag: 'value' },\n];\n\nconst SPAWN_LEAD_OPTS: LeadOptSpec[] = [\n ...AUTH_LEAD_OPTS,\n { aliases: ['--cwd'], key: 'cwd', flag: 'value' },\n { aliases: ['-e', '--env'], key: 'env', flag: 'repeat' },\n { aliases: ['--stdin'], key: 'stdin', flag: 'bool' },\n];\n\n/**\n * `exec`/`spawn` run under `.passThroughOptions()`: everything after\n * `<sandboxId>` arrives in the variadic `<command...>` untouched, so a flag\n * like `uname -a` or `node -e …` reaches the sandbox instead of being eaten\n * as a CLI option. CLI options still parse when placed *before* the sandbox\n * id; this helper additionally accepts them between the id and the command —\n * parse leading known options, stop at the first non-option word or `--`.\n */\nexport function takeLeadingOptions(\n argv: string[],\n specs: LeadOptSpec[],\n): { command: string[]; inline: Record<string, string | string[] | true> } {\n const byAlias = new Map<string, LeadOptSpec>();\n for (const spec of specs) for (const alias of spec.aliases) byAlias.set(alias, spec);\n const inline: Record<string, string | string[] | true> = {};\n let i = 0;\n for (; i < argv.length; i++) {\n const token = argv[i];\n if (token === '--') {\n i++;\n break;\n }\n if (!token.startsWith('-') || token === '-') break;\n const eq = token.indexOf('=');\n const flag = eq === -1 ? token : token.slice(0, eq);\n let spec = byAlias.get(flag);\n // Attached short-option value, e.g. `-eFOO=bar` (commander accepts the\n // same form before the sandbox id).\n let attached: string | undefined;\n if (!spec && !flag.startsWith('--') && flag.length > 2) {\n const shortSpec = byAlias.get(flag.slice(0, 2));\n if (shortSpec && shortSpec.flag !== 'bool') {\n spec = shortSpec;\n attached = flag.slice(2);\n if (attached.startsWith('=')) attached = attached.slice(1);\n if (eq !== -1) attached += token.slice(eq);\n }\n }\n if (!spec) {\n throw new Error(\n `unknown option '${flag}' — pass CLI options before the command, or use -- to separate them`,\n );\n }\n if (spec.flag === 'bool') {\n if (eq !== -1) throw new Error(`option '${flag}' takes no value`);\n inline[spec.key] = true;\n } else {\n const value = attached ?? (eq !== -1 ? token.slice(eq + 1) : argv[++i]);\n if (value === undefined) throw new Error(`option '${flag}' requires a value`);\n if (spec.flag === 'repeat') {\n ((inline[spec.key] ??= []) as string[]).push(value);\n } else {\n inline[spec.key] = value;\n }\n }\n }\n return { command: argv.slice(i), inline };\n}\n\nfunction mergeLeadOpts<T>(opts: T, inline: Record<string, string | string[] | true>): T {\n const merged = { ...opts } as Record<string, unknown>;\n for (const [key, value] of Object.entries(inline)) {\n if (Array.isArray(value)) {\n merged[key] = [...((merged[key] as string[] | undefined) ?? []), ...value];\n } else {\n merged[key] = value;\n }\n }\n return merged as T;\n}\n\nexport function registerSandboxesCommands(program: Command): void {\n const cmd = program\n .command('sandboxes')\n .alias('sbx')\n .description('Create and drive sandboxes through the platform')\n .enablePositionalOptions()\n .configureOutput({ outputError: usageErrorOutput });\n\n cmd\n .command('create')\n .description('Place a sandbox (provider order walks 1,2,3; \"market\" bids first)')\n .option('--order <providers>', 'provider order, comma-separated (e.g. \"market,blaxel,vercel\")')\n .option('--size <size>', 'platform size: small (1 vCPU/2 GB), medium, large, xlarge (8/16 GB); default medium')\n .option('--label <label>', 'label for the sandbox')\n .option('--image <image>', 'container image to boot')\n .option('--snapshot-id <id>', 'provider snapshot to resume')\n .option('--cpus <n>', 'CPU cores (raw resources — mutually exclusive with --size)')\n .option('--memory-mb <n>', 'memory in MB (raw resources)')\n .option('--disk-mb <n>', 'ephemeral disk in MB (raw resources)')\n .option('--max-price <usd/unit>', 'max price for a market fill (e.g. 0.12/hour); makes the create a limit order')\n .option('--max-price-per <unit>', 'unit for a bare --max-price usd (second, minute, or hour)')\n .option('--market', 'place the create on the compute market (order type \"market\")')\n .option('--order-type <type>', 'explicit market order type: market or limit')\n .option('--timeout-ms <ms>', 'sandbox timeout in ms')\n .option('--secret <name>', 'vault secret name to inject (repeatable)', (v, a: string[]) => a.concat(v), [] as string[])\n .option('--api-key <key>', 'platform API key (or COMPUTE_API_KEY)')\n .option('--base-url <url>', 'platform base URL')\n .option('--allow-untrusted-host', 'allow non-computesdk.com base URLs')\n .option('--json', 'print the raw response')\n .action(async (opts: CommonOpts & {\n order?: string; label?: string; image?: string; snapshotId?: string;\n size?: string; cpus?: string; memoryMb?: string; diskMb?: string; timeoutMs?: string;\n maxPrice?: string; maxPricePer?: string; market?: boolean; orderType?: string;\n secret?: string[];\n }) => {\n try {\n const c = await client(opts);\n const resources: Record<string, number> = {};\n if (opts.cpus) resources.cpus = Number(opts.cpus);\n if (opts.memoryMb) resources.memoryMb = Number(opts.memoryMb);\n if (opts.diskMb) resources.ephemeralDiskMb = Number(opts.diskMb);\n const body: Record<string, unknown> = {};\n if (opts.order) body.providerOrder = opts.order.split(',').map((s) => s.trim());\n if (opts.size) body.size = opts.size;\n if (opts.label) body.label = opts.label;\n if (opts.image) body.image = opts.image;\n if (opts.snapshotId) body.snapshotId = opts.snapshotId;\n if (opts.timeoutMs) body.timeoutMs = Number(opts.timeoutMs);\n if (opts.secret && opts.secret.length > 0) body.secrets = opts.secret;\n if (Object.keys(resources).length > 0) body.resources = resources;\n const maxPrice = parseMaxPrice(opts.maxPrice, opts.maxPricePer);\n if (maxPrice) body.maxPrice = { usd: maxPrice.usd, per: maxPrice.per };\n if (opts.orderType && opts.market) {\n throw new Error('--market and --order-type are mutually exclusive.');\n }\n if (opts.orderType) body.orderType = opts.orderType;\n if (opts.market) body.orderType = 'market';\n const res = await c.post<{ sandbox: SandboxDetail }>('/api/v1/sandboxes', body);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('quote')\n .description('Quote a sandbox create: placement, rate, caps and credits — creates nothing')\n .option('--size <size>', 'platform size (or raw resource flags; default medium)')\n .option('--cpus <n>', 'CPU cores')\n .option('--memory-mb <n>', 'memory in MB')\n .option('--disk-mb <n>', 'ephemeral disk in MB')\n .option('--region <region>', 'pin the placement region')\n .option('--timeout-ms <ms>', 'sandbox timeout in ms')\n .option('--order-type <type>', 'market order type: market or limit')\n .option('--market', 'quote a market order (fills at the live price, protection-bounded)')\n .option('--max-price <usd/unit>', 'max price for a market fill (e.g. 0.12/hour)')\n .option('--max-price-per <unit>', 'unit for a bare --max-price usd (second, minute, or hour)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (opts: CommonOpts & {\n size?: string; cpus?: string; memoryMb?: string; diskMb?: string;\n region?: string; timeoutMs?: string; orderType?: string; market?: boolean;\n maxPrice?: string; maxPricePer?: string;\n }) => {\n try {\n const c = await client(opts);\n const params: Record<string, string | undefined> = {\n size: opts.size,\n cpus: opts.cpus,\n memoryMb: opts.memoryMb,\n ephemeralDiskMb: opts.diskMb,\n region: opts.region,\n timeoutMs: opts.timeoutMs,\n orderType: opts.market ? 'market' : opts.orderType,\n };\n if (opts.orderType && opts.market) {\n throw new Error('--market and --order-type are mutually exclusive.');\n }\n const maxPrice = parseMaxPrice(opts.maxPrice, opts.maxPricePer);\n if (maxPrice) {\n params.maxPriceUsd = String(maxPrice.usd);\n params.maxPricePer = maxPrice.per;\n }\n const res = await c.get<{ quote: SandboxQuoteWire }>(\n '/api/v1/sandboxes/quote',\n params,\n );\n output(opts, res.quote, (quote) => printQuote(quote, opts.timeoutMs));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('list')\n .description('List sandboxes')\n .option('--status <status>', 'creating | running | destroyed')\n .option('--limit <n>', 'page size')\n .option('--cursor <cursor>', 'page cursor from a previous response')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (opts: CommonOpts & { status?: string; limit?: string; cursor?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ sandboxes: SandboxSummary[]; nextCursor: string | null }>(\n '/api/v1/sandboxes',\n { status: opts.status, limit: opts.limit, cursor: opts.cursor },\n );\n output(opts, res, (page) => {\n page.sandboxes.forEach(printSandbox);\n if (page.nextCursor) console.log(pc.dim(`nextCursor: ${page.nextCursor}`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('get <sandboxId>')\n .description('Show one sandbox (includes the BYOK attach descriptor)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ sandbox: SandboxDetail }>(`/api/v1/sandboxes/${sandboxId}`);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('destroy <sandboxId>')\n .description('Destroy a sandbox (verified teardown + cost settle)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.del<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${sandboxId}`);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('exec <sandboxId> <command...>')\n .description('Run a one-shot command and print its result (options before the command; -- also works)')\n .option('--timeout-ms <ms>', 'command timeout in ms')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .passThroughOptions()\n .action(async (sandboxId: string, rawCommand: string[], rawOpts: CommonOpts & { timeoutMs?: string }) => {\n let opts = rawOpts;\n try {\n const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);\n opts = mergeLeadOpts(rawOpts, lead.inline);\n const command = lead.command;\n if (command.length === 0) throw new Error('missing command to run');\n const c = await client(opts);\n const res = await c.post<{ commandId: string } & CommandResult>(\n `/api/v1/sandboxes/${sandboxId}/commands`,\n {\n command: command.map(shellQuote).join(' '),\n ...(opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}),\n },\n );\n output(opts, res, (r) => {\n process.stdout.write(r.stdout);\n if (r.stderr) process.stderr.write(r.stderr);\n if (!r.stdout) console.log(`exit ${r.exitCode} (${r.durationMs}ms)`);\n });\n // exitCode, not exit(): a piped stdout flushes before the CLI exits.\n if (res.exitCode !== 0) process.exitCode = res.exitCode;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('spawn <sandboxId> <command...>')\n .description('Start a detached process that outlives this request (options before the command; -- also works)')\n .option('--cwd <dir>', 'working directory')\n .option('-e, --env <key=value>', 'environment variable (repeatable)', (v, a: string[]) => a.concat(v), [] as string[])\n .option('--stdin', 'keep the process\\'s stdin pipe open for `stdin`/`close-stdin`')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .passThroughOptions()\n .action(async (sandboxId: string, rawCommand: string[], rawOpts: CommonOpts & { cwd?: string; env?: string[]; stdin?: boolean }) => {\n let opts = rawOpts;\n try {\n const lead = takeLeadingOptions(rawCommand, SPAWN_LEAD_OPTS);\n opts = mergeLeadOpts(rawOpts, lead.inline);\n const command = lead.command;\n if (command.length === 0) throw new Error('missing command to spawn');\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${sandboxId}/processes`,\n {\n command: command.map(shellQuote).join(' '),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {}),\n ...(opts.stdin ? { stdin: true } : {}),\n },\n );\n output(opts, res.process, printProcess);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('ps <sandboxId>')\n .description('List the sandbox\\'s tracked processes')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ processes: SandboxProcess[] }>(\n `/api/v1/sandboxes/${sandboxId}/processes`,\n );\n output(opts, res.processes, (list) => list.forEach(printProcess));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('logs <sandboxId> <jobId>')\n .description('Show a process\\'s buffered output (--follow streams until exit)')\n .option('-f, --follow', 'stream output until the process exits')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { follow?: boolean }) => {\n try {\n const c = await client(opts);\n if (opts.follow) {\n await followProcess(c, sandboxId, jobId);\n return;\n }\n const res = await c.get<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`,\n );\n output(opts, res.process, (p) => {\n if (p.stdout) process.stdout.write(p.stdout);\n if (p.stderr) process.stderr.write(p.stderr);\n if (!p.stdout && !p.stderr) printProcess(p);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('wait <sandboxId> <jobId>')\n .description('Block until a process exits')\n .option('--timeout-ms <ms>', 'bound the wait (job keeps running on timeout)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { timeoutMs?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/wait`,\n opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {},\n );\n output(opts, res.process, printProcess);\n if (res.process.status === 'exited') {\n // A null exit code (signal-terminated) is still a failure, not 0.\n process.exitCode = res.process.exitCode ?? 128;\n }\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('kill <sandboxId> <jobId>')\n .description('Signal a process (default SIGTERM)')\n .option('--signal <signal>', 'signal name or number, e.g. SIGKILL or 9')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { signal?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/kill`,\n opts.signal ? { signal: opts.signal } : {},\n );\n output(opts, res.process, printProcess);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('stdin <sandboxId> <jobId>')\n .description('Write to a process\\'s stdin pipe (spawn with --stdin; --data, --file, or piped)')\n .option('--data <text>', 'data to write')\n .option('--file <local>', 'read data from a local file')\n .option('--base64', 'base64-encode the input before sending (binary-safe)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { data?: string; file?: string; base64?: boolean }) => {\n try {\n let data = opts.data;\n if (data === undefined && opts.file) {\n const { readFile } = await import('node:fs/promises');\n data = opts.base64\n ? (await readFile(opts.file)).toString('base64')\n : await readFile(opts.file, 'utf8');\n }\n if (data === undefined && !process.stdin.isTTY) {\n // Buffer raw bytes — decoding as utf8 first would corrupt binary\n // input before --base64 could encode it.\n const piped = await new Promise<Buffer>((resolve) => {\n const chunks: Buffer[] = [];\n process.stdin.on('data', (chunk) => chunks.push(chunk));\n process.stdin.on('end', () => resolve(Buffer.concat(chunks)));\n });\n data = opts.base64 ? piped.toString('base64') : piped.toString('utf8');\n }\n if (data === undefined || data === '') {\n console.error(pc.red('Pass --data, --file, or pipe stdin'));\n process.exit(1);\n }\n if (opts.base64 && opts.data !== undefined) {\n data = Buffer.from(data).toString('base64');\n }\n const c = await client(opts);\n const res = await c.post<{ ok: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/stdin`,\n { data, ...(opts.base64 ? { encoding: 'base64' } : {}) },\n );\n output(opts, res, () => console.log(`wrote ${data.length} chars to ${jobId}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('close-stdin <sandboxId> <jobId>')\n .description('Close a process\\'s stdin pipe')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ ok: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/close-stdin`,\n {},\n );\n output(opts, res, () => console.log(`closed stdin on ${jobId}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('ls <sandboxId> [path]')\n .description('List a directory (or stat a path) inside the sandbox')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string | undefined, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${sandboxId}/files`, {\n path: path ?? '/',\n });\n output(opts, res, (view) => {\n if (view.type === 'directory') {\n for (const e of view.entries) {\n console.log(`${e.type === 'directory' ? pc.blue('d') : ' '} ${e.name}${e.size !== undefined ? ` ${pc.dim(String(e.size))}` : ''}`);\n }\n } else {\n console.log(`${view.path} file ${view.content.length} chars`);\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('cat <sandboxId> <path>')\n .description('Print a file\\'s contents')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${sandboxId}/files`, { path });\n output(opts, res, (view) => {\n if (view.type !== 'file') {\n console.error(pc.red(`${view.path} is a directory`));\n process.exit(1);\n }\n process.stdout.write(view.content);\n if (!view.content.endsWith('\\n')) process.stdout.write('\\n');\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('write <sandboxId> <path>')\n .description('Write a file inside the sandbox (--content or --file <local>, else stdin)')\n .option('--content <text>', 'file contents')\n .option('--file <local>', 'read contents from a local file')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts & { content?: string; file?: string }) => {\n try {\n let content = opts.content;\n if (content === undefined && opts.file) {\n const { readFile } = await import('node:fs/promises');\n content = await readFile(opts.file, 'utf8');\n }\n if (content === undefined && !process.stdin.isTTY) {\n content = await new Promise<string>((resolve) => {\n let data = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk) => (data += chunk));\n process.stdin.on('end', () => resolve(data));\n });\n }\n if (content === undefined) {\n console.error(pc.red('Pass --content, --file, or pipe stdin'));\n process.exit(1);\n }\n const c = await client(opts);\n const res = await c.post<{ path: string; type: string }>(\n `/api/v1/sandboxes/${sandboxId}/files`,\n { path, content },\n );\n output(opts, res, (r) => console.log(`wrote ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('mkdir <sandboxId> <path>')\n .description('Create a directory (parents included)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ path: string }>(`/api/v1/sandboxes/${sandboxId}/files`, {\n path,\n mkdir: true,\n });\n output(opts, res, (r) => console.log(`created ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('rm <sandboxId> <path>')\n .description('Remove a file or directory inside the sandbox')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.del<{ path: string; removed: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/files?path=${encodeURIComponent(path)}`,\n );\n output(opts, res, (r) => console.log(`removed ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('url <sandboxId>')\n .description('Resolve the provider\\'s public URL for a port')\n .requiredOption('--port <n>', 'port the service listens on')\n .option('--protocol <protocol>', 'protocol (default provider-chosen)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts & { port: string; protocol?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ url: string }>(`/api/v1/sandboxes/${sandboxId}/urls`, {\n port: opts.port,\n protocol: opts.protocol,\n });\n output(opts, res, (r) => console.log(safeTerm(r.url)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('snapshots <sandboxId>')\n .description('List the sandbox\\'s snapshots')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ snapshots: SandboxSnapshot[] }>(\n `/api/v1/sandboxes/${sandboxId}/snapshots`,\n );\n output(opts, res.snapshots, (list) => list.forEach(printSnapshot));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('snapshot <sandboxId>')\n .description('Snapshot a running sandbox through its provider')\n .option('--label <label>', 'label for the snapshot')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts & { label?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ snapshot: SandboxSnapshot }>(\n `/api/v1/sandboxes/${sandboxId}/snapshots`,\n opts.label ? { label: opts.label } : {},\n );\n output(opts, res.snapshot, printSnapshot);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('snapshot-delete <sandboxId> <snapshotId>')\n .description('Delete a snapshot\\'s provider artifact')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, snapshotId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.del<{ ok: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/snapshots/${snapshotId}`,\n );\n output(opts, res, () => console.log(`deleted snapshot ${snapshotId}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n // One-off org override on every subcommand — sent as X-Org-Slug.\n for (const sub of cmd.commands) {\n sub.option('--org <slug>', 'organization slug for this command (or $COMPUTE_ORG)');\n }\n}\n\n/** Streams a process's daemon-buffered output to the console until `exit`. */\nasync function followProcess(\n c: ActionsClient,\n sandboxId: string,\n jobId: string,\n): Promise<void> {\n let exitCode = 0;\n for await (const { event, data } of c.sseNamed(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`,\n )) {\n const payload = data as Record<string, unknown>;\n if (event === 'stdout') process.stdout.write(String(payload.chunk ?? ''));\n else if (event === 'stderr') process.stderr.write(String(payload.chunk ?? ''));\n else if (event === 'exit') {\n // A null exit code means a signal killed the process — still a failure.\n exitCode = typeof payload.exitCode === 'number' ? payload.exitCode : 128;\n return finish();\n } else if (event === 'error') {\n console.error(pc.red(`Error: ${String(payload.error ?? 'stream error')}`));\n return finish(1);\n }\n }\n // The stream ended without an `exit` event — the process may still be\n // running; reporting success would be wrong either way.\n console.error(pc.yellow('stream ended before the process exited'));\n return finish(2);\n\n function finish(code?: number): void {\n if (code !== undefined) exitCode = code;\n if (exitCode !== 0) process.exitCode = exitCode;\n }\n}\n"],"mappings":";;;AAeA,OAAO;AACP,SAAS,eAAe;AACxB,YAAY,OAAO;AACnB,OAAOA,SAAQ;AACf,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,QAAAC,aAAY;;;ACE9B,IAAM,eAAgD;AAAA,EACpD,KAAK,EAAE,aAAa,CAAC,CAAC,aAAa,CAAC,GAAG,YAAY,EAAE,aAAa,SAAS,EAAE;AAAA,EAC7E,SAAS,EAAE,aAAa,CAAC,CAAC,mBAAmB,CAAC,GAAG,YAAY,EAAE,mBAAmB,QAAQ,EAAE;AAAA,EAC5F,OAAO;AAAA,IACL,aAAa,CAAC,CAAC,kBAAkB,oBAAoB,CAAC;AAAA,IACtD,YAAY,EAAE,gBAAgB,WAAW,oBAAoB,cAAc;AAAA,EAC7E;AAAA,EACA,QAAQ;AAAA,IACN,aAAa,CAAC,CAAC,gBAAgB,kBAAkB,mBAAmB,GAAG,CAAC,mBAAmB,CAAC;AAAA,IAC5F,YAAY;AAAA,MACV,cAAc;AAAA,MACd,gBAAgB;AAAA,MAChB,mBAAmB;AAAA,IACrB;AAAA,EACF;AAAA,EACA,SAAS,EAAE,aAAa,CAAC,CAAC,iBAAiB,CAAC,GAAG,YAAY,EAAE,iBAAiB,SAAS,EAAE;AAAA,EACzF,WAAW;AAAA,IACT,a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,EAChB,OAAO,MAAM;AAEd,CAAC;AAOH,eAAe,OAAO;AACpB,MAAI,QAAQ,KAAK,CAAC,MAAM,WAAW,QAAQ,KAAK,CAAC,MAAM,aAAa;AAClE,UAAM,EAAE,KAAK,SAAS,IAAI,MAAM,OAAO,kBAAkB;AACzD,UAAM,SAAS,QAAQ,KAAK,MAAM,CAAC,CAAC;AACpC;AAAA,EACF;AACA,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAMA,IAAG,IAAI;AAAA,SAAY,MAAM,OAAO,EAAE,CAAC;AACjD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["pc","readFileSync","join","client","p","usd","program","org","pc","usd","pc","p","program","pc","usd","pc","p","program","__filename","__dirname","readFileSync","join","pc","org"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/providers.ts","../src/actions.ts","../src/actions-client.ts","../src/market.ts","../src/sandboxes.ts"],"sourcesContent":["/**\n * @computesdk/cli\n *\n * ComputeSDK CLI — platform commands and the benchmarks CLI.\n *\n * Usage:\n * compute login # OAuth device login (benchsdk-cli)\n * compute logout # clear stored credentials\n * compute providers # list configured providers\n * compute actions … # Actions API\n * compute market … # market sell-side commands\n * compute sandboxes … # platform sandbox control plane\n * compute bench … # benchmarks platform CLI\n */\n\nimport 'dotenv/config';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { getProviderStatus } from './providers.js';\nimport { registerActionsCommands } from './actions.js';\nimport { registerMarketCommands } from './market.js';\nimport { registerSandboxesCommands } from './sandboxes.js';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst packageJson = JSON.parse(\n readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')\n);\n\n// Detect if running from dev workspace\nconst isDevBuild = import.meta.url.includes('worktrees') ||\n import.meta.url.includes('/packages/cli/');\nconst VERSION = isDevBuild ? `${packageJson.version}-dev` : packageJson.version;\n\n// stdout closed early (`compute … | jq -r`, `| head`): exit quietly — the\n// consumer already has what it wanted. stderr closed: swallow the write\n// error but let the command finish, so a failed command keeps its nonzero\n// exit instead of masking as success. Other stream errors still throw.\nprocess.stdout.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE') process.exit(0);\n throw err;\n});\nprocess.stderr.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE') return;\n throw err;\n});\n\nconst program = new Command();\n\nprogram\n .name('compute')\n .description('ComputeSDK CLI')\n .version(VERSION)\n .enablePositionalOptions()\n .passThroughOptions();\n\nfunction envBaseUrl(): string | undefined {\n return process.env.COMPUTE_PLATFORM_URL ?? process.env.BENCHMARKS_PLATFORM_URL;\n}\n\nasync function benchAuth(opts: { baseUrl?: string } = {}) {\n const { resolveAuth } = await import('@benchsdk/cli');\n return resolveAuth({ baseUrl: opts.baseUrl ?? envBaseUrl() });\n}\n\nasync function printSessionLine(options?: { baseUrl?: string }): Promise<void> {\n try {\n const { getMe } = await import('@benchsdk/cli');\n const me = await getMe(await benchAuth({ baseUrl: options?.baseUrl }));\n const active = me.organizations.find((o) => o.id === me.activeOrganizationId);\n const who = me.user.email ?? me.user.name ?? me.user.id;\n if (active) {\n p.log.success(\n `Logged in as ${who} — active org: ${active.slug}. Change with \\`compute org use <slug>\\`.`,\n );\n } else {\n p.log.success(`Logged in as ${who} — no active org`);\n }\n } catch {\n p.log.warn('Logged in, but could not fetch session info.');\n }\n}\n\n// `compute login` and `bench auth login` are the same login: the\n// `benchsdk-cli` OAuth client with the full first-party scope set, stored\n// once in ~/.benchsdk/credentials.json.\nasync function runLogin(options?: { baseUrl?: string }): Promise<void> {\n const { oauthLogin } = await import('@benchsdk/cli');\n await oauthLogin({\n baseUrl: options?.baseUrl ?? envBaseUrl(),\n });\n}\n\nasync function runLogout(): Promise<void> {\n const { clearCredentials } = await import('@benchsdk/cli');\n await clearCredentials();\n}\n\n// ─── Default action: Show help ─────────────────────────────────────────────\n\nprogram\n .option('--login', 'force re-authentication')\n .option('--logout', 'clear stored credentials')\n .option('--org <slug>', 'organization slug override for this invocation (or $COMPUTE_ORG)')\n .action(async (opts) => {\n if (opts.logout) {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await runLogout();\n p.log.success('Logged out. Stored credentials removed.');\n p.outro(pc.green('Done!'));\n process.exit(0);\n }\n\n if (opts.login) {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await runLogin();\n await printSessionLine();\n p.outro(pc.green('Authenticated!'));\n process.exit(0);\n }\n\n // Show help by default\n program.help();\n });\n\n// `compute --org <slug> <group> …` (leading position): forward to the env the\n// client layer reads. A trailing --org on the subcommand still wins —\n// resolveActionsAuth reads opts.org before COMPUTE_ORG.\nprogram.hook('preAction', (thisCommand) => {\n const org = thisCommand.opts().org;\n if (org) process.env.COMPUTE_ORG = org;\n});\n\n// ─── providers ───────────────────────────────────────────────────────────────\n\nprogram\n .command('providers')\n .description('List all providers and their configuration status')\n .action(async () => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n const statuses = getProviderStatus();\n\n console.log();\n for (const status of statuses) {\n const icon = status.ready ? pc.green('●') : pc.gray('○');\n const name = status.ready ? pc.white(status.name) : pc.gray(status.name);\n const detail = status.ready\n ? pc.green('ready')\n : pc.gray(`missing: ${status.missing.join(', ')}`);\n console.log(` ${icon} ${name} ${detail}`);\n }\n console.log();\n });\n\n// ─── login / logout ──────────────────────────────────────────────────────────\n\nprogram\n .command('login')\n .description('Authenticate with ComputeSDK (OAuth device flow)')\n .option('--base-url <url>', 'platform URL to authenticate against')\n .action(async (opts) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await runLogin({ baseUrl: opts.baseUrl });\n await printSessionLine({ baseUrl: opts.baseUrl });\n p.outro(pc.green('Authenticated!'));\n });\n\nprogram\n .command('logout')\n .description('Clear stored credentials')\n .option('--json', 'print machine-readable JSON')\n .action(async (opts) => {\n await runLogout();\n if (opts.json) {\n console.log(JSON.stringify({ loggedOut: true }, null, 2));\n return;\n }\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n p.log.success('Logged out. Stored credentials removed.');\n p.outro(pc.green('Done!'));\n });\n\n// ─── org ────────────────────────────────────────────────────────────────────\n// Mirrors `bench org` — same credential store and /api/v1/organizations calls\n// through @benchsdk/cli. The active org is per user+client, shared by every\n// CLI on every machine.\n\nasync function printWhoami(options: { json?: boolean; baseUrl?: string } = {}): Promise<void> {\n const { getMe } = await import('@benchsdk/cli');\n const me = await getMe(await benchAuth({ baseUrl: options.baseUrl }));\n if (options.json) {\n console.log(JSON.stringify(me, null, 2));\n return;\n }\n const active = me.organizations.find((o) => o.id === me.activeOrganizationId);\n console.log(me.user.email ?? me.user.name ?? me.user.id);\n console.log(\n `active org: ${active ? `${active.slug} (${active.id})` : '—'}${me.organizations.length > 1 ? ' — change with `compute org use <slug>`' : ''}`,\n );\n}\n\nconst org = program.command('org').description('Manage the active organization');\n\norg\n .command('list')\n .description('List your organizations')\n .option('--json', 'print machine-readable JSON')\n .action(async (opts) => {\n const { listOrganizations, getMe } = await import('@benchsdk/cli');\n const auth = await benchAuth();\n const [organizations, me] = await Promise.all([listOrganizations(auth), getMe(auth)]);\n if (opts.json) {\n console.log(JSON.stringify(organizations, null, 2));\n return;\n }\n for (const o of organizations) {\n const marker = o.id === me.activeOrganizationId ? pc.green('*') : ' ';\n console.log(`${marker} ${pc.cyan(o.slug)} ${o.name ?? ''} ${pc.dim(o.id)}`);\n }\n });\n\norg\n .command('use <slug>')\n .description('Set the active organization (persisted to the stored login)')\n .action(async (slug: string) => {\n const { loadCredentials, saveCredentials, createApiClient, setActiveOrganization } =\n await import('@benchsdk/cli');\n const credentials = (await loadCredentials()) ?? {};\n const { auth } = await createApiClient({ baseUrl: envBaseUrl() });\n const result = await setActiveOrganization(auth, slug);\n if (!result.organization) {\n throw new Error(`Could not set active organization to ${slug}`);\n }\n await saveCredentials({\n ...credentials,\n baseUrl: auth.baseUrl,\n // An API-key login must not be rewritten as an OAuth one — keep its\n // key and kind, and only stamp token fields when this auth actually\n // is a token session.\n ...(auth.token\n ? {\n token: auth.token,\n refreshToken: auth.refreshToken,\n tokenExpiresAt: auth.tokenExpiresAt,\n refreshExpiresAt: auth.refreshExpiresAt,\n kind: 'oauth' as const,\n }\n : {}),\n orgSlug: result.organization.slug,\n orgId: result.organization.id,\n });\n console.log(`Active organization set to ${result.organization.slug} (${result.organization.id})`);\n });\n\norg\n .command('current')\n .description('Show the current user and active organization')\n .option('--base-url <url>', 'platform URL to query')\n .option('--json', 'print machine-readable JSON')\n .action((opts) => printWhoami(opts));\n\nprogram\n .command('whoami')\n .description('Show the current user and active organization')\n .option('--base-url <url>', 'platform URL to query')\n .option('--json', 'print machine-readable JSON')\n .action((opts) => printWhoami(opts));\n\n// ─── actions ─────────────────────────────────────────────────────────────────\n\nregisterActionsCommands(program);\n\n// ─── market ──────────────────────────────────────────────────────────────────\n// `compute market` is the sell side of the compute market — same platform\n// API and auth as `compute actions`, for orgs flagged `market_provider`.\n\nregisterMarketCommands(program);\n\n// ─── sandboxes ───────────────────────────────────────────────────────────────\n// `compute sandboxes` drives /api/v1/sandboxes — the customer-facing sandbox\n// control plane (create/exec/processes/files/urls). Same auth as actions.\n\nregisterSandboxesCommands(program);\n\n// ─── bench ───────────────────────────────────────────────────────────────────\n// `compute bench` is the benchmarks-platform CLI (@benchsdk/runner's `bench`\n// binary) folded under compute: run/check/auth/org/benchmarks/runs/results/\n// iterations/artifacts/logs/export all dispatch through it.\n\nprogram\n .command('bench')\n .description('Benchmarks platform CLI (run, auth, org, benchmarks, runs, results, artifacts, export, ...)')\n .allowUnknownOption()\n .helpOption(false)\n .action(() => {\n // Never reached: bench args are dispatched pre-parse below.\n });\n\n// ─── Run ─────────────────────────────────────────────────────────────────────\n\n// Bench args are opaque to commander (its own --flags, `--` separators, file\n// paths), so they dispatch before parsing. `@benchsdk/runner`'s run() owns the\n// process — it exits itself after dispatch.\nasync function main() {\n if (process.argv[2] === 'bench' || process.argv[2] === 'benchmark') {\n const { run: benchRun } = await import('@benchsdk/runner');\n await benchRun(process.argv.slice(3));\n return;\n }\n await program.parseAsync(process.argv);\n}\n\nmain().catch((error) => {\n console.error(pc.red(`\\nError: ${error.message}`));\n process.exit(1);\n});\n","/**\n * Provider detection and validation\n *\n * Detection is local: each provider declares the env vars its credentials come\n * from, and \"ready\" means all of them are set. This used to import helpers from\n * `computesdk` that the package no longer exports, which made every `compute`\n * invocation fail at module load.\n */\n\ninterface ProviderEnvSpec {\n /**\n * Alternative complete credential sets — the provider is usable when every\n * var in any one set is present (e.g. Vercel: the traditional tuple OR\n * VERCEL_OIDC_TOKEN; Namespace: NSC_TOKEN or NSC_TOKEN_FILE).\n */\n authOptions: string[][];\n /**\n * Maps each env var to the provider's nested config key (the field names in\n * the provider package's config interface, e.g. `apiKey`, `tokenId`).\n */\n configKeys: Record<string, string>;\n}\n\nconst PROVIDER_ENV: Record<string, ProviderEnvSpec> = {\n e2b: { authOptions: [['E2B_API_KEY']], configKeys: { E2B_API_KEY: 'apiKey' } },\n railway: { authOptions: [['RAILWAY_API_TOKEN']], configKeys: { RAILWAY_API_TOKEN: 'token' } },\n modal: {\n authOptions: [['MODAL_TOKEN_ID', 'MODAL_TOKEN_SECRET']],\n configKeys: { MODAL_TOKEN_ID: 'tokenId', MODAL_TOKEN_SECRET: 'tokenSecret' },\n },\n vercel: {\n authOptions: [['VERCEL_TOKEN', 'VERCEL_TEAM_ID', 'VERCEL_PROJECT_ID'], ['VERCEL_OIDC_TOKEN']],\n configKeys: {\n VERCEL_TOKEN: 'token',\n VERCEL_TEAM_ID: 'teamId',\n VERCEL_PROJECT_ID: 'projectId',\n },\n },\n daytona: { authOptions: [['DAYTONA_API_KEY']], configKeys: { DAYTONA_API_KEY: 'apiKey' } },\n namespace: {\n authOptions: [['NSC_TOKEN'], ['NSC_TOKEN_FILE']],\n configKeys: { NSC_TOKEN: 'token', NSC_TOKEN_FILE: 'tokenFile' },\n },\n blaxel: {\n authOptions: [['BL_API_KEY', 'BL_WORKSPACE']],\n configKeys: { BL_API_KEY: 'apiKey', BL_WORKSPACE: 'workspace' },\n },\n codesandbox: { authOptions: [['CSB_API_KEY']], configKeys: { CSB_API_KEY: 'apiKey' } },\n render: { authOptions: [['RENDER_API_KEY']], configKeys: { RENDER_API_KEY: 'apiKey' } },\n};\n\nconst PROVIDER_NAMES = Object.keys(PROVIDER_ENV);\n\n/** Missing vars from whichever auth option is closest to complete. */\nfunction missingEnvVars(provider: string): string[] {\n const spec = PROVIDER_ENV[provider];\n if (!spec) return [];\n let best: string[] | null = null;\n for (const option of spec.authOptions) {\n const missing = option.filter((name) => !process.env[name]);\n if (missing.length === 0) return [];\n if (!best || missing.length < best.length) best = missing;\n }\n return best ?? [];\n}\n\nfunction isProviderAuthComplete(provider: string): boolean {\n return missingEnvVars(provider).length === 0;\n}\n\n/**\n * Provider status info\n */\nexport interface ProviderStatus {\n name: string;\n ready: boolean;\n missing: string[];\n}\n\n/**\n * Detect all available providers from environment variables\n */\nexport function detectAvailableProviders(): string[] {\n const available: string[] = [];\n\n for (const provider of PROVIDER_NAMES) {\n if (isProviderAuthComplete(provider)) {\n available.push(provider);\n }\n }\n\n return available;\n}\n\n/**\n * Get status of all providers\n */\nexport function getProviderStatus(): ProviderStatus[] {\n const statuses: ProviderStatus[] = [];\n\n for (const provider of PROVIDER_NAMES) {\n statuses.push({\n name: provider,\n ready: isProviderAuthComplete(provider),\n missing: missingEnvVars(provider),\n });\n }\n\n return statuses;\n}\n","/** A file/dir name reduced to a safe basename — strips `..` and separators. */\nfunction sanitizePathPart(name: string): string {\n const base = basename(name);\n if (base === '' || base === '.' || base === '..') return 'artifact';\n return base;\n}\n\n/**\n * `compute actions` — drive the benchmarks-platform Actions API end-to-end:\n * dispatch workflows, watch runs, inspect run context, stream logs,\n * manage artifacts.\n *\n * Auth: --api-key, else COMPUTE_API_KEY, else the platform OAuth credentials\n * `compute login` (or `compute bench auth login`) stored (refreshed silently,\n * never prompts). --base-url overrides the\n * https://platform.computesdk.com default; a non-computesdk host needs\n * --allow-untrusted-host and an explicit key — stored OAuth is never sent there.\n * Every subcommand takes --json for machine-readable output — on success the\n * data, on failure the `{ ok: false, error: {...} }` envelope on stderr.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { basename, join } from 'path';\nimport {\n ActionsApiError,\n ActionsCliError,\n ActionsClient,\n encodeWatchCursor,\n isTrustedActionsHost,\n resolveActionsAuth,\n toErrorEnvelope,\n type ActionsAuth,\n type CiArtifactListItem,\n type CiJob,\n type CiLogSlice,\n type CiProviderInfo,\n type CiProviderKeyResponse,\n type CiProvidersResponse,\n type CiRepo,\n type CiRepoConnectResponse,\n type CiRepoPatchResponse,\n type CiReposResponse,\n type CiRun,\n type CiRunHistory,\n type CiRunInspection,\n type CiRunSummary,\n type CiVaultDeleteResponse,\n type CiVaultItem,\n type CiVaultKind,\n type CiVaultListResponse,\n type CiVaultRevealResponse,\n type CiVaultSaveResponse,\n type CiWorkflow,\n} from './actions-client.js';\n\n/** The jobs inside a `/state` response — a subset of CiJob, no name/steps. */\ninterface CiLiveStateJob {\n id: string;\n state: CiJob['state'];\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n placementAttempts: CiJob['placementAttempts'];\n}\n\nexport type JsonOpts = { json?: boolean };\n\nexport interface CommonOpts extends JsonOpts {\n apiKey?: string;\n baseUrl?: string;\n allowUntrustedHost?: boolean;\n /** One-off org override sent as X-Org-Slug (or set $COMPUTE_ORG). */\n org?: string;\n}\n\n/** The platform API client behind both `compute actions` and `compute market`. */\nexport async function client(opts: CommonOpts): Promise<ActionsClient> {\n return new ActionsClient(await resolveActionsAuth(opts));\n}\n\n/**\n * Commands that send or read a local secret value (vault set/get, market\n * credential connect) only ever talk to a trusted host: --allow-untrusted-host\n * opts an explicit API key into a host, not the secrets themselves.\n */\nexport function assertSecretValueHost(auth: ActionsAuth, what: string): void {\n if (!isTrustedActionsHost(auth.baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host',\n `Refusing to send or read ${what} at ${auth.baseUrl} — only computesdk.com and localhost hosts are allowed, even with --allow-untrusted-host.`,\n );\n }\n}\n\nexport function assertVaultValueHost(auth: ActionsAuth): void {\n assertSecretValueHost(auth, 'vault values');\n}\n\n/** A client for commands carrying a local secret value — trusted hosts only. */\nexport async function secretValueClient(opts: CommonOpts, what: string): Promise<ActionsClient> {\n const auth = await resolveActionsAuth(opts);\n assertSecretValueHost(auth, what);\n return new ActionsClient(auth);\n}\n\nasync function vaultValueClient(opts: CommonOpts): Promise<ActionsClient> {\n return secretValueClient(opts, 'vault values');\n}\n\n/** Print `data` as JSON when --json was passed; otherwise call `render`. */\nexport function output<T>(opts: JsonOpts, data: T, render: (data: T) => void): void {\n if (opts.json) {\n process.stdout.write(JSON.stringify(data, null, 2) + '\\n');\n } else {\n render(data);\n }\n}\n\n/** The run's job list: full detail when the runs detail route exists, else the\n * live-state route (which predates it and lists jobs without names). */\nasync function listRunJobs(c: ActionsClient, runId: string): Promise<CiJob[]> {\n try {\n const run = await c.get<CiRun>(`/api/v1/actions/runs/${runId}`);\n return run.jobs;\n } catch (e) {\n if (!(e instanceof ActionsApiError) || e.status !== 404) throw e;\n }\n const state = await c.get<{ jobs: CiLiveStateJob[] }>(`/api/v1/actions/runs/${runId}/state`);\n return state.jobs.map((j) => ({\n id: j.id,\n name: j.id.slice(0, 8), // the live-state route does not carry job names\n needs: [],\n workflowJobId: null,\n matrix: null,\n state: j.state,\n provider: j.provider,\n region: j.region,\n sandboxId: j.sandboxId,\n placementAttempts: j.placementAttempts,\n durationMs: null,\n steps: [],\n }));\n}\n\n/** The run's failure digest; null when the summary cannot be fetched. */\nasync function fetchRunSummary(c: ActionsClient, runId: string): Promise<CiRunSummary | null> {\n try {\n return await c.get<CiRunSummary>(`/api/v1/actions/runs/${runId}/summary`);\n } catch (e) {\n // The digest rides along with `actions run`; a deployment without the\n // route or a summary error must not hide the run detail itself. The\n // `summary` command fetches directly so its own errors still surface.\n if (!(e instanceof ActionsApiError && e.status === 404)) {\n console.error(\n pc.dim(`summary unavailable: ${e instanceof Error ? e.message : String(e)}`),\n );\n }\n return null;\n }\n}\n\n/**\n * Report an error and exit 1. With --json the stderr line is the stable\n * envelope from `toErrorEnvelope` (stdout stays empty, so a consumer can parse\n * either stream without guessing); otherwise a one-line human message.\n */\nexport function fail(error: unknown, opts: JsonOpts = {}): never {\n if (opts.json) {\n process.stderr.write(JSON.stringify(toErrorEnvelope(error)) + '\\n');\n } else if (error instanceof ActionsApiError) {\n console.error(pc.red(`Error (${error.status}): ${error.message}`));\n } else {\n console.error(pc.red(`Error: ${error instanceof Error ? error.message : String(error)}`));\n }\n process.exit(1);\n}\n\n/**\n * Commander's own usage errors (unknown option, missing required option or\n * argument) are raised before any action runs, so `fail` never sees them.\n * Route them through the same envelope when --json is among the raw args.\n */\nexport function usageErrorOutput(str: string, write: (str: string) => void, argv: string[] = process.argv): void {\n if (argv.includes('--json')) {\n const message = str.replace(/^error:\\s*/i, '').trim();\n write(JSON.stringify(toErrorEnvelope(new ActionsCliError('invalid_argument', message))) + '\\n');\n } else {\n write(str);\n }\n}\n\n// ─── Formatting (pure, exported for tests) ──────────────────────────────────\n\nexport function formatDuration(ms: number | null | undefined): string {\n if (ms === null || ms === undefined) return '-';\n if (ms < 1000) return `${ms}ms`;\n const s = Math.round(ms / 1000);\n if (s < 60) return `${s}s`;\n const m = Math.floor(s / 60);\n if (m < 60) return `${m}m${s % 60}s`;\n const h = Math.floor(m / 60);\n return `${h}h${m % 60}m`;\n}\n\nexport function shortSha(sha: string): string {\n return sha.slice(0, 8);\n}\n\nexport function conclusionLabel(conclusion: string): string {\n switch (conclusion) {\n case 'passed': return pc.green('passed');\n case 'failed': return pc.red('failed');\n case 'running': return pc.yellow('running');\n case 'cancelled': return pc.gray('cancelled');\n case 'none': return pc.yellow('queued');\n default: return conclusion;\n }\n}\n\nexport function formatRunRow(run: CiRun): string {\n const num = run.runNumber === null ? '-' : `#${run.runNumber}`;\n return [\n run.id,\n pc.dim(num),\n run.workflowName || run.workflowPath,\n conclusionLabel(run.conclusion),\n pc.dim(`${run.repoFullName}@${run.ref}`),\n shortSha(run.headSha),\n formatDuration(run.durationMs),\n run.startedAt,\n ].join(' ');\n}\n\nexport function formatRunDetail(run: CiRun, runUrl?: string): string {\n const lines: string[] = [];\n lines.push(`${pc.bold(run.workflowName || run.workflowPath)} ${conclusionLabel(run.conclusion)}`);\n lines.push(pc.dim(`run ${run.id}${run.runNumber === null ? '' : ` #${run.runNumber}`}`));\n lines.push(`${run.repoFullName} @ ${run.ref} ${shortSha(run.headSha)} ${run.event}${run.prNumber ? ` PR #${run.prNumber}` : ''}`);\n lines.push(`title: ${run.title}`);\n lines.push(`started: ${run.startedAt} duration: ${formatDuration(run.durationMs)}`);\n if (run.cancellationReason) lines.push(`cancelled: ${run.cancellationReason}`);\n if (run.providerOverride) lines.push(`dispatched to: ${run.providerOverride}`);\n if (run.supersededByRunId) lines.push(`superseded by: ${run.supersededByRunId}`);\n if (runUrl) lines.push(`url: ${runUrl}`);\n if (run.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of run.jobs) {\n const placement = job.provider\n ? `${job.provider}${job.region ? `:${job.region}` : ''}`\n : '-';\n lines.push(` ${job.id} ${job.name} ${conclusionLabel(job.state)} ${placement} ${formatDuration(job.durationMs)}`);\n for (const attempt of job.placementAttempts) {\n lines.push(pc.dim(` placement failed on ${attempt.provider}${attempt.region ? `:${attempt.region}` : ''}: ${attempt.error}`));\n }\n for (const step of job.steps) {\n const exit = step.exitCode === null ? '' : ` (exit ${step.exitCode})`;\n lines.push(pc.dim(` ${step.name} ${step.state}${exit} ${formatDuration(step.durationMs)}`));\n }\n }\n }\n return lines.join('\\n');\n}\n\n/** `compute actions inspect` — the run plus everything that shaped it. */\nexport function formatRunInspection(run: CiRunInspection): string {\n const lines: string[] = [];\n lines.push(`${pc.bold('run')} ${conclusionLabel(run.conclusion)}${run.runNumber === null ? '' : ` #${run.runNumber}`}`);\n lines.push(pc.dim(run.id));\n lines.push(`${safeTerm(run.ref)} ${shortSha(run.headSha)} ${safeTerm(run.event)}`);\n lines.push(`queued: ${run.queuedAt} started: ${run.startedAt} finished: ${run.finishedAt}`);\n if (run.cancellationReason) lines.push(`cancelled: ${run.cancellationReason}`);\n if (run.supersededByRunId) lines.push(`superseded by: ${run.supersededByRunId}`);\n if (run.blockedReason) lines.push(pc.red(`blocked: ${safeTerm(run.blockedReason)}`));\n if (run.concurrencyGroup) lines.push(`concurrency: ${safeTerm(run.concurrencyGroup)}`);\n if (run.providerOverride) lines.push(`dispatched to: ${safeTerm(run.providerOverride)}`);\n if (run.definitionStale) {\n const parsed = run.workflowParsedFromSha ? shortSha(run.workflowParsedFromSha) : 'unknown';\n lines.push(pc.yellow(`definition: stored parse is from ${parsed}, not this head — context may be newer than the run`));\n }\n if (run.dispatchInputs && Object.keys(run.dispatchInputs).length > 0) {\n lines.push(`inputs: ${Object.entries(run.dispatchInputs).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(' ')}`);\n }\n if (run.secrets) {\n const names = run.secrets.names.length > 0 ? run.secrets.names.map(safeTerm).join(', ') : 'none';\n lines.push(`secrets (${run.secrets.access}${run.secrets.env ? ', exported to env' : ''}): ${names}`);\n }\n if (run.caches.length > 0) {\n lines.push('');\n lines.push(pc.bold('caches'));\n for (const cache of run.caches) {\n const action = [cache.restoredAt ? 'restored' : null, cache.savedAt ? 'saved' : null]\n .filter(Boolean)\n .join('+');\n lines.push(` ${safeTerm(cache.key)} ${pc.dim(`${action} ${safeTerm(cache.scopeRef)} ${cache.sizeBytes}B`)}`);\n }\n }\n if (run.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of run.jobs) {\n const placement = job.provider\n ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ''}`\n : '-';\n lines.push(` ${safeTerm(job.name)} ${conclusionLabel(job.state)} ${placement}`);\n lines.push(pc.dim(` ${job.id}`));\n if (job.runsOn.length > 0 || job.resolvedRunsOn !== null) {\n const resolved =\n job.resolvedRunsOn !== null && job.resolvedRunsOn.join(',') !== job.runsOn.join(',')\n ? ` → ${job.resolvedRunsOn.map(safeTerm).join(', ')}`\n : '';\n lines.push(` runs-on: ${job.runsOn.map(safeTerm).join(', ') || '(none)'}${resolved}`);\n }\n if (job.runsOnHasExpression) lines.push(pc.dim(' runs-on resolves at runtime (expression)'));\n if (job.container) lines.push(` container: ${safeTerm(job.container)}`);\n if (job.runnerImage) lines.push(` image: ${safeTerm(job.runnerImage)}`);\n if (job.placementHint) {\n lines.push(` pinned: ${safeTerm(job.placementHint.label)}`);\n }\n if (job.concurrencyGroup) {\n lines.push(` concurrency: ${safeTerm(job.concurrencyGroup)}${job.concurrencyCancelInProgress ? ' (cancel-in-progress)' : ''}`);\n }\n const overrides = [\n job.timeoutMinutes !== null ? `timeout ${job.timeoutMinutes}m` : null,\n job.fetchDepth !== null ? `fetch-depth ${job.fetchDepth}` : null,\n ].filter(Boolean);\n if (overrides.length > 0) lines.push(` ${overrides.join(' ')}`);\n if (job.matrix) {\n lines.push(` matrix: ${Object.entries(job.matrix).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(' ')}`);\n }\n if (job.failureReason) lines.push(pc.red(` failed: ${safeTerm(job.failureReason)}`));\n for (const attempt of job.placementAttempts) {\n lines.push(pc.dim(` placement failed on ${safeTerm(attempt.provider)}${attempt.region ? `:${safeTerm(attempt.region)}` : ''}: ${safeTerm(attempt.error)}`));\n }\n }\n }\n return lines.join('\\n');\n}\n\n/** The failure digest rendered for humans — shared by `run` and `summary`. */\nexport function formatRunSummary(summary: CiRunSummary): string {\n const lines: string[] = [];\n lines.push(pc.bold(`failures — run ${summary.runId} ${conclusionLabel(summary.conclusion)}`));\n if (summary.failures.length === 0) {\n lines.push(' no failed jobs');\n return lines.join('\\n');\n }\n for (const job of summary.failures) {\n const placement = job.provider\n ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ''}`\n : '-';\n lines.push(` ${job.id} ${safeTerm(job.name)} ${conclusionLabel(job.conclusion)} ${placement}`);\n if (job.failureReason) lines.push(pc.dim(` ${safeTerm(job.failureReason)}`));\n for (const step of job.failedSteps) {\n const exit = step.exitCode === null ? '' : ` (exit ${step.exitCode})`;\n lines.push(` step ${step.ordinal} ${safeTerm(step.name)}${exit}`);\n }\n if (job.excerpt) {\n const scope = job.excerpt.stepOrdinal === null ? 'job log' : `step ${job.excerpt.stepOrdinal}`;\n const cut = job.excerpt.truncated ? ', truncated' : '';\n lines.push(pc.dim(` ── ${scope} tail${cut} ──`));\n for (const line of job.excerpt.text.split('\\n')) lines.push(` ${safeTerm(line)}`);\n }\n }\n return lines.join('\\n');\n}\n\n// ─── Parsing helpers (pure, exported for tests) ─────────────────────────────\n\n/** `--inputs k=v` pairs → a dispatch inputs object. `k=v` with no `=` is an error. */\nexport function parseInputs(pairs: string[] | undefined): Record<string, string> {\n const inputs: Record<string, string> = {};\n for (const pair of pairs ?? []) {\n const eq = pair.indexOf('=');\n if (eq === -1) {\n throw new ActionsCliError('invalid_argument', `Invalid --inputs entry \"${pair}\". Expected key=value.`);\n }\n inputs[pair.slice(0, eq)] = pair.slice(eq + 1);\n }\n return inputs;\n}\n\n/** Match `--workflow` to a workflow by path first, then by name. */\nexport function matchWorkflow(\n workflows: CiWorkflow[],\n selector: string,\n): CiWorkflow | undefined {\n return (\n workflows.find((w) => w.path === selector) ??\n workflows.find((w) => w.name === selector) ??\n workflows.find((w) => w.id === selector)\n );\n}\n\n/** Match `--job` to a run's job by id, then by name. */\nexport function matchJob(jobs: CiJob[], selector: string): CiJob | undefined {\n return jobs.find((j) => j.id === selector) ?? jobs.find((j) => j.name === selector);\n}\n\n// ─── Logs ───────────────────────────────────────────────────────────────────\n\nasync function readWholeJobLog(client: ActionsClient, jobId: string, step?: string): Promise<CiLogSlice> {\n const segments: CiLogSlice['segments'] = [];\n let offset = 0;\n let slice: CiLogSlice;\n do {\n slice = await client.get<CiLogSlice>(`/api/v1/actions/jobs/${jobId}/logs`, {\n offset: String(offset),\n step,\n });\n segments.push(...slice.segments);\n offset = slice.nextOffset;\n } while (slice.truncated);\n return { ...slice, segments };\n}\n\n/** Follow one job's log over the SSE `follow=1` slice stream, resuming on reconnect. */\nasync function* followJobLog(client: ActionsClient, jobId: string, step?: string): AsyncGenerator<CiLogSlice> {\n let offset = 0;\n for (;;) {\n let terminal = false;\n for await (const raw of client.sse(`/api/v1/actions/jobs/${jobId}/logs`, {\n offset: String(offset),\n follow: '1',\n step,\n })) {\n const slice = raw as CiLogSlice;\n offset = slice.nextOffset;\n if (slice.segments.length > 0 || slice.state !== 'running') yield slice;\n if (slice.state !== 'running' && slice.state !== 'pending' && !slice.truncated) {\n terminal = true;\n }\n }\n if (terminal) return;\n // The connection ended (server-side ceiling or a drop): resume from the\n // offset we hold — resumable cursors make this a continuation, not a replay.\n }\n}\n\n/** `--step` CLI value → the watch-cursor step field. */\nexport function parseStep(step: string | undefined): number | 'runner' | null {\n if (step === undefined) return null;\n if (step === 'runner') return 'runner';\n const n = Number(step);\n if (!Number.isInteger(n) || n < 0) {\n throw new ActionsCliError('invalid_argument', `Invalid --step \"${step}\". Expected a step ordinal or \"runner\".`);\n }\n return n;\n}\n\n/** Follow a run's logs across jobs via the multiplexed run stream. */\nasync function* followRunLogs(\n client: ActionsClient,\n runId: string,\n jobs: CiJob[],\n step?: string,\n): AsyncGenerator<{ job: CiJob; slice: CiLogSlice }> {\n const cursorStep = parseStep(step);\n const offsets = new Map<string, number>(jobs.map((j) => [j.id, 0]));\n const byCursor = new Map<string, CiJob>(jobs.map((j, i) => [`j${i}`, j]));\n for (;;) {\n let done = false;\n const watch = jobs.map((j, i) =>\n encodeWatchCursor(`j${i}`, j.id, cursorStep, offsets.get(j.id) ?? 0),\n );\n for await (const raw of client.sse(`/api/v1/actions/runs/${runId}/stream`, { watch })) {\n const msg = raw as\n | { type: 'state'; state: unknown }\n | { type: 'log'; cursor: string; slice: CiLogSlice }\n | { type: 'done' }\n | { type: 'reconnect' };\n if (msg.type === 'log') {\n const job = byCursor.get(msg.cursor);\n if (job) {\n offsets.set(msg.slice.jobId, msg.slice.nextOffset);\n yield { job, slice: msg.slice };\n }\n } else if (msg.type === 'done') {\n done = true;\n break;\n } else if (msg.type === 'reconnect') {\n break;\n }\n }\n if (done) return;\n // Both an explicit `reconnect` event and an unexpected EOF resume from the\n // offsets we hold; back off briefly so a repeatedly-closing server doesn't\n // spin the loop.\n await new Promise((r) => setTimeout(r, 1000));\n }\n}\n\n// Job and step names come from workflow files — potentially attacker-controlled\n// in a PR context — so strip control characters before writing to the terminal.\nexport function safeTerm(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/[\\u0000-\\u001F\\u007F-\\u009F]/g, '�');\n}\n\nexport function formatRunHistory(history: CiRunHistory): string {\n const lines: string[] = [];\n const parts = (Object.entries(history.conclusions) as [string, number][])\n .map(([c, n]) => `${n} ${c}`)\n .join(', ');\n lines.push(`last ${history.runCount} runs: ${parts || 'none'}`);\n if (history.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of history.jobs) {\n const rate = job.runs > 0 ? Math.round((job.failedRuns / job.runs) * 100) : 0;\n const platform = job.failedBeforeSteps > 0 ? pc.dim(` (${job.failedBeforeSteps} failed before steps)`) : '';\n const count = `${job.failedRuns}/${job.runs} runs failed`;\n const label = job.failedRuns > 0 ? pc.red(count) : pc.green(count);\n lines.push(` ${safeTerm(job.job)} ${label} ${rate}%${platform}`);\n for (const step of job.steps) {\n lines.push(pc.dim(` step \"${safeTerm(step.step)}\" failed in ${step.failedRuns} run${step.failedRuns === 1 ? '' : 's'}`));\n }\n }\n }\n const failed = history.runs.filter(\n (r) => r.conclusion === 'failed' || r.failedJobs.length > 0,\n );\n if (failed.length > 0) {\n lines.push('');\n lines.push(pc.bold('failed runs'));\n for (const run of failed) {\n const blame = run.failedJobs.length > 0\n ? run.failedJobs.map((j) => safeTerm(j.step === null ? j.job : `${j.job}:${j.step}`)).join(', ')\n : pc.dim('(no failed job recorded)');\n lines.push(` ${shortSha(run.headSha)} ${pc.dim(run.startedAt)} ${blame}`);\n }\n }\n return lines.join('\\n');\n}\n\nexport function formatProviderRow(p: CiProviderInfo): string {\n const icon = p.usable ? pc.green('●') : pc.gray('○');\n const name = p.usable ? pc.white(p.provider) : pc.gray(p.provider);\n const flags = [\n p.credential,\n p.actCapable ? pc.green('act') : pc.gray('no-act'),\n p.regions.length > 0 ? `regions: ${p.regions.join(',')}` : 'no region choice',\n p.position === null ? pc.gray('not in provider order') : `order #${p.position}`,\n ].join(' ');\n return ` ${icon} ${name} ${flags}`;\n}\n\nexport function formatVerifyResult(r: CiProviderKeyResponse): string {\n const ok = r.verified === true;\n const head = ok ? pc.green('verified') : pc.red('not verified');\n const detail = r.key.statusDetail ? pc.dim(` ${r.key.statusDetail}`) : '';\n const act = r.key.actCapable ? pc.green(' act-capable') : '';\n return `${head} ${r.key.provider}${act}${detail}`;\n}\n\nfunction formatRepoRow(r: CiRepo): string {\n const head = r.enabled ? pc.green('enabled') : pc.dim('disabled');\n const via = r.authType === 'github_app' ? 'github-app' : r.authType;\n const workflows =\n r.workflowPaths.length > 0\n ? `${r.workflowPaths.length} workflow${r.workflowPaths.length === 1 ? '' : 's'}`\n : 'no workflows yet';\n const error = r.lastPollError ? pc.red(` poll error: ${safeTerm(r.lastPollError)}`) : '';\n return `${head} ${safeTerm(r.fullName)} ${pc.dim(`${safeTerm(via)} · ${safeTerm(r.defaultBranch)} · ${workflows}`)}${error}`;\n}\n\n/** Print what an enable/connect discovered — one dim line, nothing on a clean run. */\nfunction printDiscovery(d: { workflowsFound: boolean; seeded: boolean; error: string | null }): void {\n if (d.error) {\n console.log(pc.yellow(`discovery: ${safeTerm(d.error)} (the poll cron retries)`));\n return;\n }\n console.log(pc.dim(`discovery: ${d.workflowsFound ? 'workflows found' : 'no workflows yet'}${d.seeded ? ', cursors seeded' : ''}`));\n}\n\n// ─── Commands ───────────────────────────────────────────────────────────────\n\n/**\n * The `POST /api/v1/actions/dispatch` body for `dispatch`. Without --manual a\n * workflow must declare `workflow_dispatch`. With it, a workflow that doesn't\n * is run anyway; such a run has no inputs, so any given are refused rather\n * than silently dropped. A dispatchable workflow keeps its inputs either way.\n */\nexport function dispatchBody(\n workflow: CiWorkflow,\n opts: {\n ref?: string;\n inputs?: string[];\n manual?: boolean;\n provider?: string;\n providerRegion?: string;\n maxBid?: string;\n maxBidPer?: string;\n },\n): Record<string, unknown> {\n if (!workflow.dispatchable && !opts.manual) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${workflow.path}\" does not declare workflow_dispatch. Pass --manual to run it anyway (no inputs).`,\n );\n }\n if (!workflow.dispatchable && opts.inputs !== undefined && opts.inputs.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${workflow.path}\" has no workflow_dispatch inputs; --manual runs of it take no --inputs.`,\n );\n }\n const ref = opts.ref ?? workflow.refs[0];\n if (!ref) throw new ActionsCliError('invalid_argument', 'No --ref given and the workflow has no watched refs.');\n if (opts.providerRegion !== undefined && opts.provider === undefined) {\n throw new ActionsCliError('invalid_argument', '--provider-region requires --provider.');\n }\n const maxPrice = maxPriceFields(opts.maxBid, opts.maxBidPer);\n return {\n workflowId: workflow.id,\n ref,\n inputs: parseInputs(opts.inputs),\n ...(opts.manual && { manual: true }),\n ...(opts.provider !== undefined && {\n provider: opts.provider,\n ...(opts.providerRegion !== undefined && { providerRegion: opts.providerRegion }),\n }),\n ...(maxPrice !== undefined && maxPrice),\n };\n}\n\n/**\n * `--max-bid`/`--max-bid-per` → the dispatch body's market price ceiling\n * fields. Undefined when no ceiling is set; the ceiling only applies to a\n * market fill — jobs that can't be filled at the price fall through to the\n * next provider-order entry.\n */\nexport function maxPriceFields(\n maxBid: string | undefined,\n maxBidPer: string | undefined,\n): { maxPriceUsd: number; maxPricePer: 'second' | 'minute' | 'hour' } | undefined {\n if (maxBidPer !== undefined && maxBid === undefined) {\n throw new ActionsCliError('invalid_argument', '--max-bid-per requires --max-bid.');\n }\n if (maxBid === undefined) return undefined;\n const usd = Number(maxBid);\n if (!/^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/.test(maxBid) || !Number.isFinite(usd) || usd <= 0) {\n throw new ActionsCliError('invalid_argument', `Invalid --max-bid \"${maxBid}\". Expected a positive dollar amount (e.g. 0.12).`);\n }\n const per = maxBidPer ?? 'second';\n if (per !== 'second' && per !== 'minute' && per !== 'hour') {\n throw new ActionsCliError('invalid_argument', `--max-bid-per must be second, minute, or hour, got \"${maxBidPer}\".`);\n }\n return { maxPriceUsd: usd, maxPricePer: per };\n}\n\n/** `--kind` for the vault commands: `secret` unless told otherwise. */\nexport function parseVaultKind(kind: string | undefined): CiVaultKind {\n if (kind === undefined || kind === 'secret' || kind === 'variable') return kind ?? 'secret';\n throw new ActionsCliError('invalid_argument', `--kind must be secret or variable, got \"${kind}\".`);\n}\n\n/** A vault route path with its scope in the query string. */\nexport function vaultPath(\n path: string,\n params: { repo?: string; kind?: CiVaultKind; name?: string },\n): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) search.set(key, value);\n }\n const query = search.toString();\n return query ? `${path}?${query}` : path;\n}\n\n/**\n * The `PUT /api/v1/vault` body for `vault set`. The value is sent exactly as\n * read — never trimmed — because whitespace can be part of a key.\n */\nexport function vaultSetBody(\n name: string,\n value: string,\n opts: { kind: CiVaultKind; revealable?: boolean; description?: string; labels?: string[] },\n): Record<string, unknown> {\n if (value === '') throw new ActionsCliError('invalid_argument', 'The value is empty.');\n if (opts.revealable && opts.kind === 'variable') {\n throw new ActionsCliError('invalid_argument', '--revealable applies to secrets; variables are always readable.');\n }\n return {\n name,\n kind: opts.kind,\n value,\n ...(opts.revealable && { revealable: true }),\n ...(opts.description !== undefined && { description: opts.description }),\n ...(opts.labels !== undefined && opts.labels.length > 0 && { labels: opts.labels }),\n };\n}\n\nexport function formatVaultRow(item: CiVaultItem): string {\n const flags = [\n item.kind,\n ...(item.revealable && item.kind === 'secret' ? ['revealable'] : []),\n `v${item.version}`,\n ...(item.source === 'organization' ? ['inherited'] : []),\n ...(item.overridesOrganization ? ['overrides org'] : []),\n ];\n return `${pc.cyan(safeTerm(item.name))} ${pc.dim(flags.join(', '))} ${pc.dim(`updated ${safeTerm(item.updatedAt)}`)}`;\n}\n\nexport function registerActionsCommands(program: Command): void {\n const actions = program\n .command('actions')\n .alias('ci')\n .description('Drive the benchmarks-platform Actions API')\n .configureOutput({ outputError: usageErrorOutput });\n\n const common = (cmd: Command) =>\n cmd\n .option('--api-key <key>', 'API key (default: $COMPUTE_API_KEY)')\n .option('--base-url <url>', 'API base URL (default: https://platform.computesdk.com)')\n .option('--org <slug>', 'organization slug for this command (or $COMPUTE_ORG)')\n .option('--allow-untrusted-host', 'send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)')\n .option('--json', 'print machine-readable JSON');\n\n common(\n actions\n .command('dispatch')\n .description('Dispatch a workflow_dispatch run (or any workflow with --manual)')\n .argument('<repo>', 'repository in owner/repo format')\n .requiredOption('--workflow <path|name>', 'workflow path or name')\n .option('--ref <ref>', 'git ref to run (default: the workflow\\'s first watched ref)')\n .option('--inputs <pairs...>', 'workflow inputs as key=value (workflow_dispatch inputs only)')\n .option('--manual', 'run a workflow even if it does not declare workflow_dispatch (such runs take no --inputs)')\n .option('--provider <id>', 'place the run on one provider (e.g. namespace, vercel:sfo1) instead of the org provider order')\n .option('--provider-region <region>', 'region for --provider (same as --provider <id>:<region>)')\n .option('--max-bid <usd>', 'max price per vCPU for a market fill (e.g. 0.12); unfilled jobs fall through to the next provider')\n .option('--max-bid-per <unit>', 'time unit --max-bid is priced in: second, minute, or hour (default: second)'),\n ).action(async (repo: string, opts: CommonOpts & { workflow: string; ref?: string; inputs?: string[]; manual?: boolean; provider?: string; providerRegion?: string; maxBid?: string; maxBidPer?: string }) => {\n try {\n const c = await client(opts);\n const { workflows } = await c.get<{ workflows: CiWorkflow[] }>(\n '/api/v1/actions/workflows',\n { repo },\n );\n const workflow = matchWorkflow(workflows, opts.workflow);\n if (!workflow) {\n const choices = workflows.map((w) => `${w.path} (${w.name})`).join(', ') || 'none';\n throw new ActionsCliError(\n 'workflow_not_found',\n `No workflow \"${opts.workflow}\" in ${repo}. Available: ${choices}`,\n );\n }\n const body = dispatchBody(workflow, opts);\n const result = await c.post<{ runId: string; created: boolean; headSha: string }>(\n '/api/v1/actions/dispatch',\n body,\n );\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${result.runId}`;\n output(opts, { ...result, url }, (r) => {\n console.log(`${r.created ? 'dispatched' : 'already running'} ${pc.cyan(r.runId)}`);\n console.log(`sha: ${r.headSha}`);\n console.log(`url: ${r.url}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('runs')\n .description('List recent runs for a repo')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--status <status...>', 'filter by conclusion: passed, failed, running, cancelled, none')\n .option('--branch <branch...>', 'filter by branch/ref'),\n ).action(async (repo: string, opts: CommonOpts & { status?: string[]; branch?: string[] }) => {\n try {\n const { runs } = await (await client(opts)).get<{ runs: CiRun[] }>(\n '/api/v1/actions/runs',\n { repo, status: opts.status, branch: opts.branch },\n );\n output(opts, runs, (rs) => {\n if (rs.length === 0) {\n console.log('No runs found.');\n return;\n }\n for (const run of rs) console.log(formatRunRow(run));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('history')\n .description('Recent run history for a workflow — per-job/step failure rates (is this failure flaky?)')\n .argument('<repo>', 'repository in owner/repo format')\n .requiredOption('--workflow <path|name>', 'workflow path or name')\n .option('--branch <branch...>', 'narrow the window to branches/refs')\n .option('--job <job>', 'narrow the rollup to one job name or workflow job id')\n .option('--limit <n>', 'runs in the window (default 10, max 50)'),\n ).action(async (repo: string, opts: CommonOpts & { workflow: string; branch?: string[]; job?: string; limit?: string }) => {\n try {\n const c = await client(opts);\n const { workflows } = await c.get<{ workflows: CiWorkflow[] }>(\n '/api/v1/actions/workflows',\n { repo },\n );\n const workflow = matchWorkflow(workflows, opts.workflow) ?? workflows.find((w) => w.path === opts.workflow);\n const workflowPath = workflow?.path ?? opts.workflow;\n const history = await c.get<CiRunHistory>('/api/v1/actions/history', {\n repo,\n workflow: workflowPath,\n branch: opts.branch,\n job: opts.job,\n limit: opts.limit,\n });\n output(opts, history, (h) => console.log(formatRunHistory(h)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('run')\n .description('Show a run: jobs, provider:region placement, placement attempts')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const run = await c.get<CiRun>(`/api/v1/actions/runs/${runId}`);\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${run.id}`;\n // A failed run's interesting part is its failure digest; on deployments\n // that have the summary route it prints inline, saving a second command.\n const summary = run.conclusion === 'failed' ? await fetchRunSummary(c, runId) : null;\n output(opts, { ...run, url, summary }, (r) => {\n console.log(formatRunDetail(r, r.url));\n if (summary && summary.failures.length > 0) {\n console.log('');\n console.log(formatRunSummary(summary));\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('summary')\n .description('Show a run\\'s failure digest: failed jobs, failed steps, bounded log tails')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const summary = await (await client(opts)).get<CiRunSummary>(`/api/v1/actions/runs/${runId}/summary`);\n output(opts, summary, (s) => console.log(formatRunSummary(s)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('inspect')\n .description('Inspect a run: resolved runner image, caches, secret names, concurrency, placement context')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const inspection = await c.get<CiRunInspection>(\n `/api/v1/actions/runs/${runId}/state`,\n );\n output(opts, inspection, (r) => console.log(formatRunInspection(r)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('logs')\n .description('Print or follow a run\\'s job logs')\n .argument('<run-id>', 'run ID')\n .option('--job <job>', 'job ID or name (default: all jobs)')\n .option('--step <step>', 'step ordinal or \"runner\" (default: whole job)')\n .option('--follow', 'stream logs while the run is live'),\n ).action(async (runId: string, opts: CommonOpts & { job?: string; step?: string; follow?: boolean }) => {\n try {\n const c = await client(opts);\n let jobs = await listRunJobs(c, runId);\n if (opts.job) {\n const job = matchJob(jobs, opts.job);\n if (!job) {\n throw new Error(\n `No job \"${opts.job}\" in run ${runId}. Jobs: ${jobs.map((j) => j.name).join(', ') || 'none'}`,\n );\n }\n jobs = [job];\n }\n if (jobs.length === 0) {\n if (opts.json) output(opts, { segments: [] }, () => {});\n else console.error('Run has no jobs yet.');\n return;\n }\n\n if (!opts.follow) {\n for (const job of jobs) {\n const slice = await readWholeJobLog(c, job.id, opts.step);\n if (opts.json) {\n process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + '\\n');\n } else {\n if (jobs.length > 1) console.log(pc.bold(`── ${job.name} ──`));\n for (const seg of slice.segments) process.stdout.write(seg.text);\n }\n }\n return;\n }\n\n if (jobs.length === 1) {\n // Single job: the slice endpoint's own SSE, resumed on reconnect.\n for await (const slice of followJobLog(c, jobs[0].id, opts.step)) {\n if (opts.json) {\n process.stdout.write(JSON.stringify(slice) + '\\n');\n } else {\n for (const seg of slice.segments) process.stdout.write(seg.text);\n }\n }\n return;\n }\n\n // Multiple jobs: one multiplexed stream, each slice tagged by job.\n for await (const { job, slice } of followRunLogs(c, runId, jobs, opts.step)) {\n if (opts.json) {\n process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + '\\n');\n } else {\n for (const seg of slice.segments) {\n const text = seg.text.replace(/\\n/g, `\\n[${job.name}] `);\n process.stdout.write(`[${job.name}] ${text}`);\n }\n }\n }\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const providers = actions\n .command('providers')\n .description('List the org\\'s registered compute providers (regions, act/usable status)');\n common(providers).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiProvidersResponse>('/api/v1/actions/providers');\n output(opts, data, (d) => {\n for (const p of d.providers) console.log(formatProviderRow(p));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('configure')\n .description('Save the org\\'s credential for a provider (owner/admin API key)')\n .argument('<provider>', 'provider id (e.g. tensorlake, blaxel)')\n .option('--key <key>', 'provider API key (single-field credentials)')\n .option('--field <pair...>', 'credential fields as name=value (multi-field providers)')\n .option('--verify', 'run the placement probe after saving'),\n ).action(async (provider: string, opts: CommonOpts & { key?: string; field?: string[]; verify?: boolean }) => {\n try {\n const c = await client(opts);\n let body: Record<string, unknown>;\n if (opts.field !== undefined) {\n if (opts.key !== undefined) throw new Error('Pass either --key or --field, not both.');\n body = { fields: parseInputs(opts.field) };\n } else if (opts.key !== undefined) {\n body = { key: opts.key };\n } else {\n throw new Error('Pass --key <key> or --field name=value.');\n }\n const saved = await c.put<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/key`,\n body,\n );\n const verification = opts.verify\n ? await c.post<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/verify`,\n )\n : undefined;\n output(opts, verification ? { key: saved.key, verification } : saved, () => {\n console.log(`saved ${saved.key.provider} ${pc.dim(saved.key.keyHint)} ${saved.key.status}`);\n if (verification) console.log(formatVerifyResult(verification));\n });\n if (verification?.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('verify')\n .description('Probe the stored provider key with a real sandbox (\"Test\" in Settings)')\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/verify`,\n );\n output(opts, result, (r) => console.log(formatVerifyResult(r)));\n if (result.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('remove')\n .description('Delete the org\\'s stored credential for a provider')\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ provider: string; deleted: boolean }>(\n `/api/v1/actions/providers/${provider}/key`,\n );\n output(opts, result, (r) => {\n console.log(r.deleted ? `deleted ${r.provider}` : `no key stored for ${r.provider}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const repos = actions\n .command('repos')\n .description('List the org\\'s connected repositories');\n common(repos).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiReposResponse>('/api/v1/actions/repos');\n output(opts, data, (d) => {\n for (const r of d.repos) console.log(formatRepoRow(r));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('connect')\n .description('Connect a git remote (validated by a real ls-remote; lands enabled)')\n .argument('<cloneUrl>', 'http(s) or ssh git remote URL')\n .option('--name <owner/repo>', 'repo name override (default: derived from cloneUrl)')\n .option('--branch <branch>', 'default branch (default: main, else the remote\\'s first)')\n .option('--token <token>', 'credential for private http(s) remotes')\n .option('--username <user>', 'username — with --token, makes auth \"basic\" instead of \"token\"')\n .option('--ssh-key-file <path>', 'OpenSSH/PEM private key file for ssh remotes')\n .option('--known-hosts-file <path>', 'known_hosts pin for ssh remotes'),\n ).action(async (cloneUrl: string, opts: CommonOpts & { name?: string; branch?: string; token?: string; username?: string; sshKeyFile?: string; knownHostsFile?: string }) => {\n try {\n let body: Record<string, unknown>;\n if (opts.sshKeyFile !== undefined) {\n if (opts.token !== undefined || opts.username !== undefined) {\n throw new Error('Pass either --ssh-key-file or --token/--username, not both.');\n }\n body = {\n authType: 'ssh',\n credential: readFileSync(opts.sshKeyFile, 'utf8'),\n ...(opts.knownHostsFile !== undefined && {\n knownHosts: readFileSync(opts.knownHostsFile, 'utf8'),\n }),\n };\n } else if (opts.username !== undefined) {\n if (opts.token === undefined) throw new Error('--username requires --token.');\n body = { authType: 'basic', username: opts.username, credential: opts.token };\n } else if (opts.token !== undefined) {\n body = { authType: 'token', credential: opts.token };\n } else {\n body = { authType: 'none' };\n }\n if (opts.knownHostsFile !== undefined && opts.sshKeyFile === undefined) {\n throw new Error('--known-hosts-file requires --ssh-key-file.');\n }\n const result = await (await client(opts)).post<CiRepoConnectResponse>('/api/v1/actions/repos', {\n cloneUrl,\n ...body,\n ...(opts.name !== undefined && { name: opts.name }),\n ...(opts.branch !== undefined && { defaultBranch: opts.branch }),\n });\n output(opts, result, (r) => {\n console.log(`connected ${pc.cyan(safeTerm(r.fullName))} ${pc.dim(`(${safeTerm(r.authType)}, ${safeTerm(r.defaultBranch)})`)}`);\n printDiscovery(r.discovery);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('enable')\n .description('Enable a repo the org can already see (granted by a GitHub App install, or a connected remote)')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--repo-id <id>', 'scope to one row when two installations grant the same name'),\n ).action(async (repo: string, opts: CommonOpts & { repoId?: string }) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: true,\n ...(opts.repoId !== undefined && { repoId: opts.repoId }),\n });\n output(opts, result, (r) => {\n console.log(`enabled ${pc.cyan(safeTerm(r.fullName))}`);\n if (r.discovery) printDiscovery(r.discovery);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('disable')\n .description('Disable a repo — it stays connected but no runs are scheduled')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--repo-id <id>', 'scope to one row when two installations grant the same name'),\n ).action(async (repo: string, opts: CommonOpts & { repoId?: string }) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: false,\n ...(opts.repoId !== undefined && { repoId: opts.repoId }),\n });\n output(opts, result, (r) => console.log(`disabled ${pc.cyan(safeTerm(r.fullName))}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const vault = actions\n .command('vault')\n .description('The org vault: secrets and variables (owner/admin key)');\n const vaultScope = (cmd: Command) =>\n common(cmd)\n .option('--repo <owner/repo>', 'scope to a repo\\'s own items instead of the org\\'s')\n .option('--kind <kind>', 'secret or variable', 'secret');\n type VaultOpts = CommonOpts & { repo?: string; kind?: string };\n\n vaultScope(\n vault.command('ls').description('List names and metadata (never values)'),\n ).action(async (opts: VaultOpts) => {\n try {\n const path = vaultPath('/api/v1/vault', { repo: opts.repo, kind: parseVaultKind(opts.kind) });\n const data = await (await client(opts)).get<CiVaultListResponse>(path);\n output(opts, data, (d) => {\n for (const item of d.items) console.log(formatVaultRow(item));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('set')\n .description('Store a value, read from stdin (or --from-file) and sent exactly as read')\n .argument('<name>', 'item name, e.g. NPM_TOKEN')\n .option('--from-file <path>', 'read the value from a file instead of stdin')\n .option('--revealable', 'let the value be read back with `vault get` (secrets; fixed at creation)')\n .option('--description <text>', 'what the item is for')\n .option('--labels <labels...>', 'labels (fixed at creation)'),\n ).action(async (name: string, opts: VaultOpts & { fromFile?: string; revealable?: boolean; description?: string; labels?: string[] }) => {\n try {\n if (opts.fromFile === undefined && process.stdin.isTTY) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Pipe the value on stdin (e.g. printf %s \"$VALUE\" | compute actions vault set NAME) or pass --from-file.',\n );\n }\n const value = readFileSync(opts.fromFile ?? 0, 'utf8');\n const kind = parseVaultKind(opts.kind);\n const body = vaultSetBody(name, value, { ...opts, kind });\n const result = await (await vaultValueClient(opts)).put<CiVaultSaveResponse>(\n vaultPath('/api/v1/vault', { repo: opts.repo }),\n body,\n );\n output(opts, result, (r) => {\n const where = opts.repo ? safeTerm(opts.repo) : 'org';\n console.log(`saved ${pc.cyan(safeTerm(r.item.name))} ${pc.dim(`(${r.item.kind}, v${r.item.version}, ${where})`)}`);\n if (/\\r?\\n$/.test(value)) {\n console.error(pc.yellow('note: the stored value ends with a newline; use printf %s rather than echo to avoid one.'));\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('get')\n .description('Print a value: any variable, or a secret created --revealable')\n .argument('<name>', 'item name'),\n ).action(async (name: string, opts: VaultOpts) => {\n try {\n const kind = parseVaultKind(opts.kind);\n const result = await (await vaultValueClient(opts)).post<CiVaultRevealResponse>(\n vaultPath('/api/v1/vault/reveal', { repo: opts.repo }),\n { name, kind },\n );\n output(opts, result, (r) => process.stdout.write(r.value));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('rm')\n .description('Delete an item (with --repo, only the repo\\'s override)')\n .argument('<name>', 'item name'),\n ).action(async (name: string, opts: VaultOpts) => {\n try {\n const path = vaultPath('/api/v1/vault', { repo: opts.repo, kind: parseVaultKind(opts.kind), name });\n const result = await (await client(opts)).del<CiVaultDeleteResponse>(path);\n output(opts, result, (r) => console.log(`deleted ${pc.cyan(safeTerm(r.name))} ${pc.dim(`(${r.kind})`)}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('cancel')\n .description('Cancel a run')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<{ cancelled: boolean }>(\n `/api/v1/actions/runs/${runId}/cancel`,\n );\n output(opts, result, (r) => {\n console.log(r.cancelled ? `Cancelled ${runId}` : `Run ${runId} was already finished`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('rerun')\n .description('Re-run a finished run at the same commit')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const result = await c.post<{ runId: string; created: boolean }>(\n `/api/v1/actions/runs/${runId}/rerun`,\n );\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${result.runId}`;\n output(opts, { ...result, url }, (r) => {\n console.log(`${r.created ? 'rerun dispatched' : 'rerun already running'} ${pc.cyan(r.runId)}`);\n console.log(`url: ${r.url}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('artifacts')\n .description('List or download a run\\'s artifacts')\n .argument('<run-id>', 'run ID')\n .option('--job <job>', 'job ID or name (default: all jobs)')\n .option('--out <dir>', 'download artifacts into this directory instead of listing'),\n ).action(async (runId: string, opts: CommonOpts & { job?: string; out?: string }) => {\n try {\n const c = await client(opts);\n let jobs = await listRunJobs(c, runId);\n if (opts.job) {\n const job = matchJob(jobs, opts.job);\n if (!job) throw new Error(`No job \"${opts.job}\" in run ${runId}.`);\n jobs = [job];\n }\n const entries: { job: CiJob; artifacts: CiArtifactListItem[] }[] = [];\n for (const job of jobs) {\n const artifacts = await c.get<CiArtifactListItem[]>(\n `/api/v1/actions/jobs/${job.id}/artifacts`,\n );\n entries.push({ job, artifacts });\n }\n\n if (opts.out) {\n const written: { jobId: string; id: string; file: string }[] = [];\n for (const { job, artifacts } of entries) {\n // Per-job directory: artifact names are not unique across jobs.\n const jobDir = join(opts.out, sanitizePathPart(job.name || job.id));\n mkdirSync(jobDir, { recursive: true });\n for (const artifact of artifacts) {\n if (artifact.expired || artifact.skippedReason) continue;\n const bytes = await c.download(\n `/api/v1/actions/jobs/${job.id}/artifacts/${artifact.id}`,\n );\n const file = join(jobDir, sanitizePathPart(artifact.fileName || artifact.name));\n writeFileSync(file, bytes);\n written.push({ jobId: job.id, id: artifact.id, file });\n }\n }\n output(opts, written, (ws) => {\n for (const w of ws) console.log(`wrote ${w.file}`);\n if (ws.length === 0) console.log('No downloadable artifacts.');\n });\n return;\n }\n\n output(opts, entries.map((e) => ({ jobId: e.job.id, job: e.job.name, artifacts: e.artifacts })), (es) => {\n let any = false;\n for (const { job, artifacts } of es) {\n for (const a of artifacts) {\n any = true;\n const flags = a.expired ? ' expired' : a.skippedReason ? ` skipped: ${a.skippedReason}` : '';\n console.log(\n `${job} ${a.id} ${a.name} ${a.contentType} ${a.byteLength}B${flags}`,\n );\n }\n }\n if (!any) console.log('No artifacts.');\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * Thin client for the benchmarks-platform Actions v1 API.\n * Types mirror the wire shapes in benchmarks-platform `lib/ci/types.ts` —\n * keep them in sync by hand; the API is the contract.\n */\n\n\nexport const DEFAULT_BASE_URL = 'https://platform.computesdk.com';\n\nexport interface ActionsAuth {\n apiKey: string;\n baseUrl: string;\n /** Sent as `X-Org-Slug` when set (--org / COMPUTE_ORG / stored login org). */\n orgSlug?: string;\n}\n\nexport interface CiWorkflowInput {\n name: string;\n description: string;\n type: 'string' | 'number' | 'boolean' | 'choice' | 'environment';\n required: boolean;\n default: string;\n options?: string[];\n}\n\nexport interface CiWorkflow {\n id: string;\n repoFullName: string;\n name: string;\n path: string;\n dispatchable: boolean;\n refs: string[];\n inputs: CiWorkflowInput[];\n schedules: unknown[];\n}\n\nexport type CiConclusion = 'passed' | 'failed' | 'running' | 'cancelled' | 'none';\nexport type CiJobState =\n | 'queued'\n | 'running'\n | 'passed'\n | 'failed'\n | 'skipped'\n | 'cancelled';\n\nexport interface CiPlacementAttempt {\n provider: string;\n region?: string | null;\n error: string;\n}\n\nexport interface CiStep {\n name: string;\n state: CiJobState;\n durationMs: number | null;\n exitCode: number | null;\n}\n\nexport interface CiJob {\n id: string;\n name: string;\n needs: string[];\n workflowJobId: string | null;\n matrix: Record<string, string> | null;\n state: CiJobState;\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n placementAttempts: CiPlacementAttempt[];\n durationMs: number | null;\n steps: CiStep[];\n}\n\nexport interface CiRun {\n id: string;\n repoFullName: string;\n ref: string;\n branchReason: string | null;\n headSha: string;\n event: string;\n prNumber: number | null;\n runNumber: number | null;\n title: string;\n workflowPath: string;\n workflowName: string;\n conclusion: CiConclusion;\n startedAt: string;\n durationMs: number | null;\n supersededByRunId: string | null;\n concurrencyGroup: string | null;\n cancellationReason: string | null;\n /** `provider[:region]` the dispatch pinned this run to, else null. */\n providerOverride?: string | null;\n jobs: CiJob[];\n logTail: string[];\n}\n\n/**\n * One job of `GET /api/v1/actions/runs/{id}/state`: the live fields plus the\n * context that decided how the job ran — resolved runner image, container\n * pin, concurrency group, timeout/fetch-depth overrides.\n */\nexport interface CiJobInspection {\n id: string;\n name: string;\n state: CiJobState;\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n startedAt: string | null;\n finishedAt: string | null;\n placementAttempts: CiPlacementAttempt[];\n /** Why the platform failed the job before steps ran, when it did. */\n failureReason: string | null;\n /** The `runs-on:` labels as declared. */\n runsOn: string[];\n /** The `computesdk:` placement pin the labels carried, when one did. */\n placementHint: { provider: string; region: string | null; label: string } | null;\n /** Labels act actually read (placement labels stripped, default substituted). */\n resolvedRunsOn: string[] | null;\n runsOnHasExpression: boolean;\n /** The image the job's steps ran in: container pin, else the mapped label. */\n runnerImage: string | null;\n /** The literal `container:` image the job declared, if any. */\n container: string | null;\n timeoutMinutes: number | null;\n /** Deepest `fetch-depth` a checkout step pinned (0 = full history). */\n fetchDepth: number | null;\n concurrencyGroup: string | null;\n concurrencyCancelInProgress: boolean;\n matrix: Record<string, string> | null;\n steps: {\n ordinal: number;\n name: string;\n state: CiJobState;\n exitCode: number | null;\n startedAt: string | null;\n finishedAt: string | null;\n }[];\n}\n\n/** A cache entry the run's window touched (saved or restored). */\nexport interface CiRunCacheTouch {\n key: string;\n version: string;\n scopeRef: string;\n sizeBytes: number;\n savedAt: string | null;\n restoredAt: string | null;\n}\n\n/** `GET /api/v1/actions/runs/{id}/state` — a run plus its effective context. */\nexport interface CiRunInspection {\n id: string;\n conclusion: CiConclusion;\n runNumber: number | null;\n ref: string;\n headSha: string;\n event: string;\n queuedAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n supersededByRunId: string | null;\n cancellationReason: string | null;\n /** Why the run was refused before placement, when it was. */\n blockedReason: string | null;\n concurrencyGroup: string | null;\n dispatchInputs: Record<string, string> | null;\n providerOverride: string | null;\n /** The commit the stored workflow definition was parsed from. */\n workflowParsedFromSha: string | null;\n /**\n * True when the stored parse came from a different commit than the run's\n * head — the definition-derived fields may then describe a newer workflow\n * than the run used (a fork pull request always shows this by design).\n */\n definitionStale: boolean;\n /** Secret *names* the jobs could reference — never values. */\n secrets: {\n access: 'declared' | 'all';\n /** Whether named secrets are also exported as job env vars. */\n env: boolean;\n names: string[];\n } | null;\n caches: CiRunCacheTouch[];\n jobs: CiJobInspection[];\n}\n\n/**\n * `GET /api/v1/actions/runs/{runId}/summary` — a run's failure digest.\n * Wire shape mirrors `CiRunSummary` in benchmarks-platform `lib/ci/run-summary.ts`.\n */\nexport interface CiRunSummaryJob {\n id: string;\n name: string;\n conclusion: CiJobState;\n provider: string | null;\n region: string | null;\n}\n\nexport interface CiRunSummaryFailedStep {\n ordinal: number;\n name: string;\n exitCode: number | null;\n}\n\nexport interface CiRunSummaryFailure extends CiRunSummaryJob {\n failureReason: string | null;\n failedSteps: CiRunSummaryFailedStep[];\n excerpt: {\n stepOrdinal: number | null;\n text: string;\n truncated: boolean;\n } | null;\n}\n\nexport interface CiRunSummary {\n runId: string;\n conclusion: CiConclusion;\n jobs: CiRunSummaryJob[];\n failures: CiRunSummaryFailure[];\n}\n\nexport interface CiArtifactListItem {\n id: string;\n name: string;\n fileName: string;\n contentType: string;\n byteLength: number;\n fileCount: number;\n skippedReason: string | null;\n expiresAt: string;\n expired: boolean;\n}\n\nexport interface CiLogSegment {\n byteOffset: number;\n stream: 'stdout' | 'stderr';\n stepOrdinal: number | null;\n text: string;\n}\n\n/** One resumable read of a job log. Resume from `nextOffset`. */\nexport interface CiLogSlice {\n jobId: string;\n fromOffset: number;\n nextOffset: number;\n totalBytes: number;\n segments: CiLogSegment[];\n state: 'running' | 'complete' | 'failed' | 'cancelled' | 'expired' | 'pending';\n truncated: boolean;\n}\n\nexport interface CiProviderInfo {\n provider: string;\n /** Selectable regions for `provider:region` order entries; empty when unknown. */\n regions: string[];\n credential: 'ambient' | 'configured' | 'not-configured';\n /** In the effective act set: built-ins, CI_ACT_PROVIDERS override, act-probe-verified keys. */\n actCapable: boolean;\n /** A placement reaching the provider finds credentials. */\n usable: boolean;\n /** 1-based position in the effective provider order, null when absent. */\n position: number | null;\n}\n\nexport interface CiProvidersResponse {\n providerOrder: string[];\n providers: CiProviderInfo[];\n}\n\n/** A saved provider credential — never carries key material, only the hint. */\nexport interface CiProviderKeyRecord {\n provider: string;\n keyHint: string;\n lastCheckedAt: string | null;\n status: 'connected' | 'error' | 'unconfigured';\n statusDetail: string | null;\n actCapable: boolean;\n credential: 'key';\n fields: unknown[];\n}\n\nexport interface CiProviderKeyResponse {\n key: CiProviderKeyRecord;\n /** Present on the verify response. */\n verified?: boolean;\n}\n\n/** One failed job inside a run-history entry — step is the first failed step. */\nexport interface CiRunJobFailure {\n job: string;\n workflowJobId: string | null;\n step: string | null;\n stepOrdinal: number | null;\n}\n\nexport interface CiRunHistoryEntry {\n id: string;\n ref: string;\n headSha: string;\n runNumber: number | null;\n conclusion: CiConclusion;\n startedAt: string;\n failedJobs: CiRunJobFailure[];\n}\n\nexport interface CiJobHistory {\n job: string;\n /** The workflow job key, when recorded; disambiguates same-named jobs. */\n workflowJobId: string | null;\n /** Runs in the window that contained this job. */\n runs: number;\n failedRuns: number;\n /** Runs where the job failed with no step blamed (platform failures). */\n failedBeforeSteps: number;\n steps: { step: string; ordinal: number; failedRuns: number }[];\n}\n\n/** `GET /api/v1/actions/history` — the window plus the rollup over it. */\nexport interface CiRunHistory {\n runCount: number;\n conclusions: Partial<Record<CiConclusion, number>>;\n jobs: CiJobHistory[];\n runs: CiRunHistoryEntry[];\n}\n\nexport interface ActionsOrg {\n organizationId: string;\n name: string;\n slug: string;\n}\n\n/**\n * One row of `GET /api/v1/actions/repos`: a repo the org can run CI on,\n * GitHub-App-granted or a generic git remote.\n */\nexport interface CiRepo {\n repoId: string;\n fullName: string;\n defaultBranch: string;\n enabled: boolean;\n private: boolean;\n forkPullRequests: boolean;\n /** `github_app` for App-granted repos; `none`/`token`/`basic`/`ssh` for remotes. */\n authType: string;\n cloneUrl: string | null;\n githubInstallationId: number | null;\n workflowPaths: string[];\n disabledWorkflowCount: number;\n lastPolledAt: string | null;\n lastPollError: string | null;\n}\n\nexport interface CiReposResponse {\n repos: CiRepo[];\n}\n\n/** What an enable/remote-connect discovered before answering. */\nexport interface CiRepoDiscovery {\n workflowsFound: boolean;\n seeded: boolean;\n error: string | null;\n}\n\nexport interface CiRepoConnectResponse {\n repoId: string | null;\n fullName: string;\n defaultBranch: string;\n authType: string;\n discovery: CiRepoDiscovery;\n}\n\nexport interface CiRepoPatchResponse {\n fullName: string;\n enabled?: boolean;\n forkPullRequests?: boolean;\n discovery: CiRepoDiscovery | null;\n}\n\nexport type CiVaultKind = 'secret' | 'variable';\n\n/** One row of `GET /api/v1/vault` — metadata only; values never list. */\nexport interface CiVaultItem {\n name: string;\n kind: CiVaultKind;\n description: string | null;\n revealable: boolean;\n labels: string[];\n version: number;\n createdAt: string;\n updatedAt: string;\n /** Present when listing or writing with `?repo=`. */\n source?: 'organization' | 'repository';\n overridesOrganization?: boolean;\n}\n\nexport interface CiVaultListResponse {\n items: CiVaultItem[];\n}\n\nexport interface CiVaultSaveResponse {\n item: CiVaultItem;\n}\n\nexport interface CiVaultRevealResponse {\n name: string;\n kind: CiVaultKind;\n value: string;\n}\n\nexport interface CiVaultDeleteResponse {\n name: string;\n kind: CiVaultKind;\n deleted: true;\n}\n\nexport class ActionsApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public body?: unknown,\n ) {\n super(message);\n this.name = 'ActionsApiError';\n }\n}\n\n/** Stable machine-readable codes for errors raised by the CLI itself. */\nexport type ActionsCliErrorCode =\n | 'no_credentials'\n | 'untrusted_host'\n | 'untrusted_host_stored_auth'\n | 'insecure_transport'\n | 'invalid_argument'\n | 'workflow_not_found';\n\n/** An error the CLI raised before or instead of an API call. */\nexport class ActionsCliError extends Error {\n constructor(\n public code: ActionsCliErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'ActionsCliError';\n }\n}\n\n/** The `--json` error envelope; `code` is stable, `message` is for humans. */\nexport interface ActionsErrorEnvelope {\n ok: false;\n error: {\n code: string;\n message: string;\n /** Present when the platform answered; absent for local/transport failures. */\n httpStatus?: number;\n retryable: boolean;\n /** The platform's `details` object, when its error response carried one. */\n details?: Record<string, unknown>;\n };\n}\n\nfunction codeForStatus(status: number): string {\n switch (status) {\n case 400: return 'bad_request';\n case 401: return 'unauthenticated';\n case 403: return 'forbidden';\n case 404: return 'not_found';\n case 409: return 'conflict';\n case 413: return 'payload_too_large';\n case 429: return 'rate_limited';\n default: return status >= 500 ? 'server_error' : 'http_error';\n }\n}\n\nfunction errorDetails(body: unknown): Record<string, unknown> | undefined {\n if (body && typeof body === 'object' && 'details' in body) {\n const details = (body as { details: unknown }).details;\n if (details && typeof details === 'object' && !Array.isArray(details)) {\n return details as Record<string, unknown>;\n }\n }\n return undefined;\n}\n\n/**\n * Classify any error thrown by an Actions command. API errors carry the HTTP\n * status; CLI errors carry their own code; a fetch rejection (DNS, refused\n * connection, TLS) is `network`; anything else is `unknown`.\n */\nexport function toErrorEnvelope(error: unknown): ActionsErrorEnvelope {\n if (error instanceof ActionsApiError) {\n const details = errorDetails(error.body);\n // The platform's OAuth layer answers 403 insufficient_scope when the\n // stored login's grant doesn't cover the call — point at re-login rather\n // than leaving the raw error.\n const insufficientScope =\n error.message.includes('insufficient_scope') ||\n (typeof error.body === 'string' && error.body.includes('insufficient_scope')) ||\n (typeof error.body === 'object' && error.body !== null &&\n JSON.stringify(error.body).includes('insufficient_scope'));\n return {\n ok: false,\n error: {\n code: codeForStatus(error.status),\n message: insufficientScope\n ? `${error.message} — run \\`compute login\\` to sign in again.`\n : error.message,\n httpStatus: error.status,\n retryable: error.status === 429 || error.status === 502 || error.status === 503 || error.status === 504,\n ...(details !== undefined && { details }),\n },\n };\n }\n if (error instanceof ActionsCliError) {\n return { ok: false, error: { code: error.code, message: error.message, retryable: false } };\n }\n // undici/Node fetch rejects with a TypeError whose cause is the socket error.\n if (error instanceof TypeError && /fetch failed/i.test(error.message)) {\n const cause = (error as { cause?: unknown }).cause;\n const detail = cause instanceof Error ? `: ${cause.message}` : '';\n return {\n ok: false,\n error: { code: 'network', message: `${error.message}${detail}`, retryable: true },\n };\n }\n return {\n ok: false,\n error: {\n code: 'unknown',\n message: error instanceof Error ? error.message : String(error),\n retryable: false,\n },\n };\n}\n\nexport class ActionsClient {\n private orgPromise: Promise<ActionsOrg> | null = null;\n\n constructor(\n private readonly auth: ActionsAuth,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {}\n\n get baseUrl(): string {\n return this.auth.baseUrl;\n }\n\n /** The credential's org — fetched once, needed for dashboard URLs. */\n org(): Promise<ActionsOrg> {\n this.orgPromise ??= this.get<ActionsOrg>('/api/v1/actions/org');\n return this.orgPromise;\n }\n\n async get<T>(path: string, params?: Record<string, string | string[] | undefined>): Promise<T> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, { headers: this.headers() });\n return this.parse<T>(res);\n }\n\n async post<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'POST',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async put<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'PUT',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async patch<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'PATCH',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async del<T>(path: string): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'DELETE',\n headers: this.headers(),\n });\n return this.parse<T>(res);\n }\n\n /**\n * One `data:` JSON payload per SSE event. `next()` resolves to the payload,\n * or null when the stream ends. Call `close()` to abort.\n */\n async *sse(path: string, params?: Record<string, string | string[] | undefined>): AsyncGenerator<unknown> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, {\n headers: { ...this.headers(), accept: 'text/event-stream' },\n });\n if (!res.ok) {\n await this.parse(res); // throws\n }\n if (!res.body) throw new Error('SSE response has no body');\n yield* readSseEvents(res.body);\n }\n\n /**\n * `sse()` with the frame's `event:` name preserved — for streams whose\n * events are distinguished by name rather than payload shape (process\n * follow: stdout/stderr share a `{chunk}` payload).\n */\n async *sseNamed(\n path: string,\n params?: Record<string, string | string[] | undefined>,\n ): AsyncGenerator<{ event: string; data: unknown }> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, {\n headers: { ...this.headers(), accept: 'text/event-stream' },\n });\n if (!res.ok) {\n await this.parse(res); // throws\n }\n if (!res.body) throw new Error('SSE response has no body');\n yield* readSseNamedEvents(res.body);\n }\n\n /** Download bytes following redirects (artifact URLs 302 to storage). */\n async download(path: string): Promise<Uint8Array> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n headers: this.headers(),\n redirect: 'follow',\n });\n if (!res.ok) {\n const body = await res.json().catch(() => undefined);\n throw new ActionsApiError(res.status, errorMessage(body, res.status), body);\n }\n return new Uint8Array(await res.arrayBuffer());\n }\n\n private headers(): Record<string, string> {\n const headers: Record<string, string> = {\n authorization: `Bearer ${this.auth.apiKey}`,\n accept: 'application/json',\n };\n if (this.auth.orgSlug) headers['X-Org-Slug'] = this.auth.orgSlug;\n return headers;\n }\n\n private async parse<T>(res: Response): Promise<T> {\n const body = await res.json().catch(() => undefined);\n if (!res.ok) throw new ActionsApiError(res.status, errorMessage(body, res.status), body);\n return body as T;\n }\n}\n\nfunction errorMessage(body: unknown, status: number): string {\n if (body && typeof body === 'object' && 'error' in body && typeof (body as { error: unknown }).error === 'string') {\n return (body as { error: string }).error;\n }\n return `Request failed with status ${status}`;\n}\n\n/** Minimal SSE reader: yields the JSON payload of each `data:` event. */\nexport async function* readSseEvents(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<unknown> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let idx;\n while ((idx = buffer.indexOf('\\n\\n')) !== -1) {\n const event = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n for (const line of event.split('\\n')) {\n if (line.startsWith('data: ')) {\n yield JSON.parse(line.slice(6));\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/** `readSseEvents` with the `event:` name preserved alongside the JSON payload. */\nexport async function* readSseNamedEvents(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<{ event: string; data: unknown }> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let idx;\n while ((idx = buffer.indexOf('\\n\\n')) !== -1) {\n const frame = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n let event = 'message';\n const dataLines: string[] = [];\n for (const line of frame.split('\\n')) {\n if (line.startsWith('event: ')) event = line.slice(7);\n else if (line.startsWith('data: ')) dataLines.push(line.slice(6));\n }\n if (dataLines.length > 0) {\n yield { event, data: JSON.parse(dataLines.join('\\n')) };\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/** `id:jobId:step:offset` — the run-stream watch cursor wire format. */\nexport function encodeWatchCursor(\n id: string,\n jobId: string,\n step: number | 'runner' | null,\n offset: number,\n): string {\n const stepPart = step === null ? '-' : step === 'runner' ? 'runner' : String(step);\n return `${id}:${jobId}:${stepPart}:${offset}`;\n}\n\n/** The subset of `@benchsdk/cli`'s `resolveAuth` result Actions needs. */\nexport type StoredPlatformAuth = { apiKey?: string; token?: string; orgSlug?: string; orgId?: string };\nexport type StoredPlatformAuthResolver = (opts: { baseUrl: string }) => Promise<StoredPlatformAuth>;\n\nconst NO_CREDENTIALS_HINT =\n 'Set COMPUTE_API_KEY, pass --api-key, or run `compute login`.';\n\n/**\n * Precedence: `--api-key` > `COMPUTE_API_KEY` > `BENCHMARKS_PLATFORM_API_KEY`\n * (legacy) > platform OAuth credentials stored by `compute login`\n * (`~/.benchsdk/credentials.json`, via `@benchsdk/cli`'s `resolveAuth`, which\n * refreshes an expired access token but never opens a browser). `compute\n * login` writes the same store, so a platform login covers these commands.\n */\nexport async function resolveActionsAuth(\n opts: {\n apiKey?: string;\n baseUrl?: string;\n allowUntrustedHost?: boolean;\n /** One-off org override: sent as X-Org-Slug (also settable via COMPUTE_ORG). */\n org?: string;\n },\n resolveStored: StoredPlatformAuthResolver = resolveStoredPlatformAuth,\n): Promise<ActionsAuth> {\n const baseUrl = (\n opts.baseUrl ||\n process.env.COMPUTE_PLATFORM_URL ||\n process.env.BENCHMARKS_PLATFORM_URL || // legacy name\n DEFAULT_BASE_URL\n ).replace(/\\/+$/, '');\n\n // One-off org override: --org flag or COMPUTE_ORG sends X-Org-Slug on every\n // request. Falls back to the stored login's saved org. The platform ignores\n // the header for org API keys (they are already org-scoped).\n let orgSlug = opts.org || process.env.COMPUTE_ORG || undefined;\n\n // The bearer key is attached to every request, so an attacker-controlled\n // --base-url would exfiltrate it. Only trusted hosts are allowed silently;\n // anything else must be opted into with --allow-untrusted-host.\n if (!opts.allowUntrustedHost && !isTrustedActionsHost(baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host',\n `Refusing to send the API key to ${baseUrl} — it is not a computesdk.com or localhost host. ` +\n 'If this is a self-hosted/dev deployment you trust, pass --allow-untrusted-host.',\n );\n }\n // Host trust and transport security are separate: --allow-untrusted-host\n // says who may receive the key, never that it may travel in plaintext.\n if (!isSecureActionsTransport(baseUrl)) {\n throw new ActionsCliError(\n 'insecure_transport',\n `Refusing to send the API key over plaintext HTTP to ${baseUrl}. ` +\n 'Use an https:// base URL; http:// is only allowed for localhost/loopback.',\n );\n }\n\n // `||` not `??`: empty-string env vars (common in CI matrices) should fall\n // through to the next source, not count as configured.\n let apiKey =\n opts.apiKey ||\n process.env.COMPUTE_API_KEY ||\n process.env.BENCHMARKS_PLATFORM_API_KEY || // legacy name\n undefined;\n if (!apiKey) {\n // Stored platform OAuth is only ever resolved (and refreshed) for trusted\n // hosts. --allow-untrusted-host opts an explicit key into a host, not the\n // user's saved session.\n if (!isTrustedActionsHost(baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host_stored_auth',\n `Refusing to use stored platform credentials with untrusted host ${baseUrl}. ` +\n 'Pass --api-key or set COMPUTE_API_KEY to use an explicit key with --allow-untrusted-host.',\n );\n }\n let stored: StoredPlatformAuth;\n try {\n stored = await resolveStored({ baseUrl });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n // `@benchsdk/cli`'s \"nothing stored\" message names `bench` commands and\n // env vars that only apply to that CLI; keep ours for that case and\n // surface the reason only for expired/failed-refresh sessions.\n const detail = reason.startsWith('No credentials found') ? 'No API key.' : reason;\n throw new ActionsCliError('no_credentials', `${detail} ${NO_CREDENTIALS_HINT}`);\n }\n apiKey = stored.apiKey || stored.token || undefined;\n // The stored orgSlug is only a cache of the last `org use` on this\n // machine — the server's consent row is the source of truth, and\n // sending it would pin this machine to a stale org after a switch\n // elsewhere. Only --org/COMPUTE_ORG send X-Org-Slug.\n }\n if (!apiKey) {\n throw new ActionsCliError('no_credentials', `No API key. ${NO_CREDENTIALS_HINT}`);\n }\n return { apiKey, baseUrl, ...(orgSlug && { orgSlug }) };\n}\n\nasync function resolveStoredPlatformAuth(opts: { baseUrl: string }): Promise<StoredPlatformAuth> {\n const { resolveAuth } = await import('@benchsdk/cli');\n const auth = await resolveAuth({ baseUrl: opts.baseUrl });\n return { apiKey: auth.apiKey, token: auth.token, orgSlug: auth.orgSlug, orgId: auth.orgId };\n}\n\nfunction isLoopbackHost(host: string): boolean {\n return host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host === '::1';\n}\n\n/** https://, or http:// to a loopback host only. */\nexport function isSecureActionsTransport(baseUrl: string): boolean {\n let url: URL;\n try {\n url = new URL(baseUrl);\n } catch {\n return false;\n }\n if (url.protocol === 'https:') return true;\n return url.protocol === 'http:' && isLoopbackHost(url.hostname);\n}\n\n/** computesdk.com (and subdomains) or localhost — safe to receive the API key. */\nexport function isTrustedActionsHost(baseUrl: string): boolean {\n let host: string;\n try {\n host = new URL(baseUrl).hostname;\n } catch {\n return false;\n }\n return host === 'computesdk.com' || host.endsWith('.computesdk.com') || isLoopbackHost(host);\n}\n","/**\n * `compute market` — the sell side of the compute market: post listings,\n * reprice/pause/resume/withdraw them, read the book, and read payouts.\n *\n * Auth: identical to `compute actions` — --api-key / COMPUTE_API_KEY / the\n * stored `compute login` (or `compute bench auth login`) session. The key must belong to an org\n * the platform flags `market_provider`; the seller principal (which\n * executor provider these listings sell) is resolved server-side from the\n * key. Types mirror the wire shapes in benchmarks-platform `lib/market/*`\n * describe functions — keep them in sync by hand; the API is the contract.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { ActionsCliError } from './actions-client.js';\nimport {\n client,\n fail,\n output,\n parseInputs,\n safeTerm,\n secretValueClient,\n usageErrorOutput,\n type CommonOpts,\n} from './actions.js';\n\n// ─── Wire types (mirror benchmarks-platform lib/market describes) ───────────\n\nexport type MarketRatePer = 'second' | 'minute' | 'hour';\nexport type MarketAskStatus = 'live' | 'paused' | 'withdrawn';\n\n/** `describeAsk` — one row of GET /api/v1/market/asks. */\nexport interface MarketAsk {\n id: string;\n provider: string;\n region: string | null;\n size: string;\n /** The lane the listing sells into — 'actions' on listings posted before lanes. */\n useCase?: 'actions' | 'sandbox';\n resources: { cpus?: number; memoryMb?: number; ephemeralDiskMb?: number };\n usd: number;\n per: MarketRatePer;\n takeBps: number;\n maxConcurrent: number;\n status: MarketAskStatus;\n /** status === 'live' AND unexpired — a 'live' ask past expiresAt shows as expired. */\n live: boolean;\n expiresAt: string | null;\n rollover: boolean;\n /** A rate edit queued for the next renewal window, when one exists. */\n pendingUsd: number | null;\n pendingPer: MarketRatePer | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface MarketCredentialField {\n name: string;\n label: string;\n secret: boolean;\n required?: boolean;\n placeholder?: string;\n}\n\n/** `describeMarketProviderMe` — GET /api/v1/market/provider. */\nexport interface MarketProvider {\n id: string;\n name: string;\n provider: string;\n organizationId: string | null;\n keyHint: string;\n executorCredentialConnected: boolean;\n revokedAt: string | null;\n createdAt: string;\n /** The lanes this principal is approved to sell into, e.g. [\"actions\", \"sandbox\"]. */\n useCases?: string[];\n /** Size presets the bound executor sells, e.g. small/medium/large. */\n sizes: {\n name: string;\n label: string;\n resources: { cpus?: number; memoryMb?: number; ephemeralDiskMb?: number };\n }[];\n regions: string[];\n /** The credential fields `credential connect` must fill ([] = ambient auth). */\n credentialFields: MarketCredentialField[];\n}\n\n/** `OrderBook` — GET /api/v1/market/book. */\nexport interface MarketOrderBook {\n asks: {\n id: string;\n provider: string;\n providerName: string;\n region: string | null;\n size: string;\n /** The lane the listing sells into — 'actions' on asks posted before lanes. */\n useCase?: 'actions' | 'sandbox';\n usd: number;\n per: MarketRatePer;\n takeBps: number;\n maxConcurrent: number;\n expiresAt: string | null;\n rollover: boolean;\n updatedAt: string;\n }[];\n bids: {\n id: string;\n /** Buyer org ids are never exposed — `mine` marks this org's own offer. */\n mine: boolean;\n size: string;\n /** The lane the offer buys on — 'actions' on bids posted before lanes. */\n useCase?: 'actions' | 'sandbox';\n region: string | null;\n maxUsd: number;\n per: MarketRatePer;\n createdAt: string;\n expiresAt: string | null;\n }[];\n fills: {\n id: string;\n askId: string;\n provider: string;\n size: string;\n /** The lane the sale cleared on — 'actions' on fills from before lanes. */\n useCase?: 'actions' | 'sandbox';\n region: string | null;\n usd: number;\n per: MarketRatePer;\n /** 'replaced' = the seller took the capacity back mid-sale. */\n status: 'live' | 'closed' | 'replaced';\n createdAt: string;\n }[];\n prices: { askId: string; usd: number; per: MarketRatePer; changedAt: string }[];\n}\n\n/** One evicted sale — POST /api/v1/market/fills/:id/replace and each entry of the listing replace. */\nexport interface MarketReplacedFill {\n fillId: string;\n askId: string;\n /** Charged to the buyer — the seconds the fill actually lived. */\n settledMicroUsd: number;\n /** An Actions job on the evicted capacity re-places on the buyer's next provider. */\n jobRequeued: boolean;\n}\n\nexport type MarketReplaceFillOutcome =\n | { ok: true; fill: MarketReplacedFill }\n | { ok: false; status: number; error: string };\n\n/** POST /api/v1/market/listings/:id/replace — paused listing + per-fill outcomes. */\nexport interface MarketListingReplaceResult {\n listing: MarketAsk;\n fills: MarketReplaceFillOutcome[];\n}\n\n/** `describeSettlement` — one row of GET /api/v1/market/settlements. */\nexport interface MarketSettlement {\n id: string;\n providerId: string;\n provider?: string;\n periodStart: string;\n periodEnd: string;\n vcpuSeconds: number;\n grossUsd: number;\n netUsd: number;\n grossMicroUsd: number;\n netMicroUsd: number;\n invoiceRef: string | null;\n paidAt: string | null;\n createdAt: string;\n}\n\n// ─── Parsing helpers (pure, exported for tests) ─────────────────────────────\n\nconst USD_RE = /^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/;\nconst RATE_UNITS: MarketRatePer[] = ['second', 'minute', 'hour'];\nconst MARKET_LANES = ['actions', 'sandbox'] as const;\nexport type MarketLane = (typeof MARKET_LANES)[number];\n\n/**\n * `--use-case` → the lane the listing sells into / the book filters to.\n * Absent = 'actions', matching the API default.\n */\nexport function parseMarketLane(value: string | undefined): MarketLane {\n if (value === undefined) return 'actions';\n if (!MARKET_LANES.includes(value as MarketLane)) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--use-case must be ${MARKET_LANES.join(' or ')}, got \"${value}\".`,\n );\n }\n return value as MarketLane;\n}\n\n/**\n * `--price <usd>/<unit>` → the body's `usd`/`per`. The unit is required —\n * either inside the value (`0.12/hour`) or via `--per` — so a bare `--price\n * 0.12` never silently defaults to per-second pricing (same rule as\n * `sandboxes create --max-price`).\n */\nexport function parseRate(\n price: string | undefined,\n per: string | undefined,\n): { usd: number; per: MarketRatePer } {\n if (price === undefined) {\n throw new ActionsCliError('invalid_argument', 'A price is required — pass --price <usd>/<unit>.');\n }\n let usdText = price;\n let unit: string | undefined = per;\n const slash = price.indexOf('/');\n if (slash !== -1) {\n usdText = price.slice(0, slash);\n const inline = price.slice(slash + 1);\n if (per !== undefined && per !== inline) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--price \"${price}\" conflicts with --per \"${per}\".`,\n );\n }\n unit = inline;\n }\n const usd = Number(usdText);\n if (!USD_RE.test(usdText) || !Number.isFinite(usd) || usd <= 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --price \"${price}\". Expected a positive dollar amount (e.g. 0.12/hour).`,\n );\n }\n if (unit === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n '--price needs a unit — write it as <usd>/<unit> (e.g. --price 0.12/hour) or pass --per hour.',\n );\n }\n if (!RATE_UNITS.includes(unit as MarketRatePer)) {\n throw new ActionsCliError(\n 'invalid_argument',\n `The unit must be second, minute, or hour, got \"${unit}\".`,\n );\n }\n return { usd, per: unit as MarketRatePer };\n}\n\n/** `--capacity` → `maxConcurrent`: a positive integer, absent = server default (1). */\nexport function parseCapacity(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n const n = Number(value);\n if (!Number.isInteger(n) || n <= 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --capacity \"${value}\". Expected a positive integer.`,\n );\n }\n return n;\n}\n\n/** `--expires-in` → `expiresInHours`: a positive number of hours. */\nexport function parseExpiresIn(value: string | undefined): number | undefined {\n if (value === undefined) return undefined;\n const hours = Number(value);\n if (!Number.isFinite(hours) || hours <= 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --expires-in \"${value}\". Expected a positive number of hours.`,\n );\n }\n return hours;\n}\n\n/**\n * The `POST /api/v1/market/asks` create body for `sell`: `{size, region?,\n * usd, per, maxConcurrent?, expiresInHours?, rollover?}`.\n */\nexport function sellBody(opts: {\n size: string;\n price?: string;\n per?: string;\n region?: string;\n capacity?: string;\n expiresIn?: string;\n renew?: boolean;\n useCase?: string;\n}): Record<string, unknown> {\n const rate = parseRate(opts.price, opts.per);\n const maxConcurrent = parseCapacity(opts.capacity);\n const expiresInHours = parseExpiresIn(opts.expiresIn);\n if (opts.renew && expiresInHours === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n '--renew requires --expires-in — a standing listing never expires.',\n );\n }\n return {\n size: opts.size,\n useCase: parseMarketLane(opts.useCase),\n ...(opts.region !== undefined && { region: opts.region }),\n usd: rate.usd,\n per: rate.per,\n ...(maxConcurrent !== undefined && { maxConcurrent }),\n ...(expiresInHours !== undefined && { expiresInHours }),\n ...(opts.renew && { rollover: true }),\n };\n}\n\n/**\n * The `POST /api/v1/market/asks` update body for `price`/`pause`/`resume`:\n * `{askId, usd?, per?, maxConcurrent?, status?}` — exactly one of the\n * change fields must be present.\n */\nexport function listingPatchBody(\n listingId: string,\n change: {\n price?: string;\n per?: string;\n capacity?: string;\n status?: 'live' | 'paused';\n },\n): Record<string, unknown> {\n const body: Record<string, unknown> = { askId: listingId };\n if (change.price !== undefined || change.per !== undefined) {\n const rate = parseRate(change.price, change.per);\n body.usd = rate.usd;\n body.per = rate.per;\n }\n const maxConcurrent = parseCapacity(change.capacity);\n if (maxConcurrent !== undefined) body.maxConcurrent = maxConcurrent;\n if (change.status !== undefined) body.status = change.status;\n if (body.usd === undefined && body.maxConcurrent === undefined && body.status === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Nothing to change — pass --price, --capacity, or a status command.',\n );\n }\n return body;\n}\n\n/**\n * The env var `credential connect` reads a field from: the provider and\n * field names upper-snake-cased — tensorlake + apiKey → TENSORLAKE_API_KEY,\n * blaxel + workspace → BLAXEL_WORKSPACE, namespace + token → NAMESPACE_TOKEN.\n * Secrets belong here (or a session env), never in argv where shell history\n * keeps them.\n */\nexport function credentialEnvVar(providerId: string, fieldName: string): string {\n const snake = (s: string) =>\n s\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^A-Za-z0-9]+/g, '_')\n .toUpperCase();\n return `${snake(providerId)}_${snake(fieldName)}`;\n}\n\nexport interface CredentialResolution {\n /** Every field's value, declared fields only. */\n values: Record<string, string>;\n /** Required fields with no value from either source. */\n missing: MarketCredentialField[];\n /** Field names taken from --field (visible in shell history). */\n fromFlag: string[];\n /** The env var each declared field was looked up under. */\n envNames: Record<string, string>;\n}\n\n/**\n * Resolve each declared credential field: an explicit `--field name=value`\n * wins, then the `<PROVIDER>_<FIELD>` env var. Empty strings count as\n * missing on both.\n */\nexport function credentialValues(\n providerId: string,\n fields: MarketCredentialField[],\n overrides: Record<string, string>,\n env: Record<string, string | undefined> = process.env,\n): CredentialResolution {\n const declared = new Set(fields.map((f) => f.name));\n const unknown = Object.keys(overrides).filter((name) => !declared.has(name));\n if (unknown.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `${providerId} takes no credential field \"${unknown.join('\", \"')}\" — expected one of ${fields\n .map((f) => f.name)\n .join(', ')}.`,\n );\n }\n const values: Record<string, string> = {};\n const fromFlag: string[] = [];\n const missing: MarketCredentialField[] = [];\n const envNames: Record<string, string> = {};\n for (const field of fields) {\n envNames[field.name] = credentialEnvVar(providerId, field.name);\n const fromOverride = overrides[field.name];\n if (fromOverride !== undefined && fromOverride.trim() !== '') {\n values[field.name] = fromOverride.trim();\n fromFlag.push(field.name);\n continue;\n }\n const fromEnv = env[envNames[field.name]];\n if (fromEnv !== undefined && fromEnv.trim() !== '') {\n values[field.name] = fromEnv.trim();\n continue;\n }\n if (field.required !== false) missing.push(field);\n }\n return { values, missing, fromFlag, envNames };\n}\n\n/**\n * The `POST /api/v1/market/provider/credential` body: `{key}` for a\n * single-field executor, `{fields}` for a multi-field one — the same two\n * shapes the org provider-key routes take.\n */\nexport function credentialBody(\n fields: MarketCredentialField[],\n values: Record<string, string>,\n): Record<string, unknown> {\n if (fields.length === 1) {\n return { key: values[fields[0].name] };\n }\n return { fields: values };\n}\n\n// ─── Formatting (pure, exported for tests) ──────────────────────────────────\n\n/** `$0.12`, `$5` — micro-USD-precision dollars without trailing zeros. */\nexport function formatUsd(usd: number): string {\n return `$${usd.toFixed(6).replace(/\\.?0+$/, '')}`;\n}\n\n/** `$0.12/second` — how a listing (or offer, or sale) is priced. */\nexport function formatRate(usd: number, per: string): string {\n return `${formatUsd(usd)}/${per}`;\n}\n\n/** The human status: withdrawn > paused > expired > live. */\nexport function formatListingStatus(ask: Pick<MarketAsk, 'status' | 'live' | 'pendingUsd' | 'pendingPer'>): string {\n let label: string;\n if (ask.status === 'withdrawn') label = pc.gray('withdrawn');\n else if (ask.status === 'paused') label = pc.yellow('paused');\n else if (!ask.live) label = pc.gray('expired');\n else label = pc.green('live');\n if (ask.pendingUsd !== null && ask.pendingPer !== null) {\n label += pc.dim(` → ${formatRate(ask.pendingUsd, ask.pendingPer)} next window`);\n }\n return label;\n}\n\nexport function formatListingRow(ask: MarketAsk): string {\n const expiry = ask.expiresAt\n ? ask.rollover\n ? `renews ${ask.expiresAt}`\n : `expires ${ask.expiresAt}`\n : 'standing';\n return [\n ask.id,\n formatListingStatus(ask),\n pc.dim(ask.useCase === 'sandbox' ? 'sandbox' : 'actions'),\n safeTerm(ask.size),\n safeTerm(ask.region ?? '-'),\n formatRate(ask.usd, ask.per),\n pc.dim(`×${ask.maxConcurrent}`),\n pc.dim(expiry),\n ].join(' ');\n}\n\nexport function formatProviderStatus(p: MarketProvider): string {\n const lines: string[] = [];\n lines.push(`${pc.bold(safeTerm(p.name))} ${pc.dim(`selling ${safeTerm(p.provider)}`)}`);\n lines.push(`id: ${p.id}`);\n lines.push(\n `credential: ${\n p.executorCredentialConnected\n ? pc.green('connected')\n : pc.yellow('not connected — your listings cannot fill until `compute market credential connect`')\n }`,\n );\n if (p.revokedAt) lines.push(pc.red(`revoked: ${p.revokedAt}`));\n lines.push(\n `lanes: ${(p.useCases ?? ['actions']).join(', ')}`,\n );\n lines.push(\n `sizes: ${p.sizes.map((s) => `${s.name} (${s.label})`).join(', ') || '-'}`,\n );\n lines.push(`regions: ${p.regions.join(', ') || '-'}`);\n if (p.credentialFields.length > 0) {\n lines.push(\n `credential fields: ${p.credentialFields\n .map((f) => `${f.name}${f.secret ? ' (secret)' : ''}`)\n .join(', ')}`,\n );\n }\n lines.push(`created: ${p.createdAt}`);\n return lines.join('\\n');\n}\n\n/** The live book, plainly labeled: who's selling, who's buying, what cleared. */\nexport function formatBook(book: MarketOrderBook): string {\n const lines: string[] = [];\n const lane = (useCase?: 'actions' | 'sandbox') =>\n pc.dim(useCase === 'sandbox' ? 'sandbox' : 'actions');\n lines.push(pc.bold(\"sellers' asking prices\"));\n if (book.asks.length === 0) lines.push(pc.dim(' no listings are live'));\n for (const ask of book.asks) {\n const where = ask.region ? safeTerm(ask.region) : 'any region';\n const expiry = ask.expiresAt\n ? pc.dim(ask.rollover ? ` renews ${ask.expiresAt}` : ` until ${ask.expiresAt}`)\n : '';\n lines.push(\n ` ${lane(ask.useCase)} ${formatRate(ask.usd, ask.per)} ${safeTerm(ask.providerName)} ${safeTerm(ask.size)} ${where} up to ${ask.maxConcurrent} at once${expiry}`,\n );\n }\n lines.push('');\n lines.push(pc.bold('buyer offers'));\n if (book.bids.length === 0) lines.push(pc.dim(' no open offers'));\n for (const bid of book.bids) {\n const where = bid.region ? safeTerm(bid.region) : 'anywhere';\n const yours = bid.mine ? pc.cyan(' (yours)') : '';\n lines.push(\n ` ${lane(bid.useCase)} pays up to ${formatRate(bid.maxUsd, bid.per)} ${safeTerm(bid.size)} ${where} ${pc.dim(`posted ${bid.createdAt}`)}${yours}`,\n );\n }\n lines.push('');\n lines.push(pc.bold('recent sales'));\n if (book.fills.length === 0) lines.push(pc.dim(' nothing has sold yet'));\n for (const fill of book.fills) {\n const statusNote =\n fill.status === 'replaced'\n ? pc.yellow(' replaced')\n : fill.status === 'closed'\n ? pc.gray(' closed')\n : '';\n lines.push(\n ` ${pc.dim(fill.id)} ${lane(fill.useCase)} ${formatRate(fill.usd, fill.per)} ${safeTerm(fill.provider)} ${safeTerm(fill.size)} ${safeTerm(fill.region ?? '-')} ${pc.dim(fill.createdAt)}${statusNote}`,\n );\n }\n return lines.join('\\n');\n}\n\n/** `replaced f-1 settled $0.0003` (+ a note when an Actions job re-places). */\nexport function formatReplacedFill(fill: MarketReplacedFill): string {\n const settled = formatUsd(fill.settledMicroUsd / 1e6);\n const job = fill.jobRequeued\n ? pc.dim(\" — job re-places on the buyer's next provider\")\n : '';\n return `replaced ${pc.cyan(fill.fillId)} settled ${settled}${job}`;\n}\n\n/**\n * `compute market replace` resolves to exactly one endpoint: `--fill` evicts\n * one sale, a listing ID pauses the listing and evicts every sale on it.\n */\nexport function replaceTarget(\n listingId: string | undefined,\n fillId: string | undefined,\n): { path: string; scope: 'listing' | 'fill' } {\n if (fillId !== undefined) {\n return {\n path: `/api/v1/market/fills/${encodeURIComponent(fillId)}/replace`,\n scope: 'fill',\n };\n }\n if (listingId === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Nothing to replace — pass a listing ID or --fill <fill-id>.',\n );\n }\n return {\n path: `/api/v1/market/listings/${encodeURIComponent(listingId)}/replace`,\n scope: 'listing',\n };\n}\n\nexport function formatSettlementRow(s: MarketSettlement): string {\n const period = `${s.periodStart.slice(0, 10)} → ${s.periodEnd.slice(0, 10)}`;\n const paid = s.paidAt\n ? pc.green(`paid ${s.paidAt.slice(0, 10)}`)\n : s.invoiceRef\n ? pc.yellow(`invoiced ${safeTerm(s.invoiceRef)}`)\n : pc.dim('unpaid');\n return [\n pc.dim(period),\n `${s.vcpuSeconds.toLocaleString('en-US')} vCPU·s`,\n `gross ${formatUsd(s.grossUsd)}`,\n `net ${formatUsd(s.netUsd)}`,\n paid,\n ].join(' ');\n}\n\n// ─── Commands ───────────────────────────────────────────────────────────────\n\nexport function registerMarketCommands(program: Command): void {\n const market = program\n .command('market')\n .description('Sell compute capacity on the compute market')\n .configureOutput({ outputError: usageErrorOutput });\n\n const common = (cmd: Command) =>\n cmd\n .option('--api-key <key>', 'API key (default: $COMPUTE_API_KEY)')\n .option('--base-url <url>', 'API base URL (default: https://platform.computesdk.com)')\n .option('--org <slug>', 'organization slug for this command (or $COMPUTE_ORG)')\n .option('--allow-untrusted-host', 'send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)')\n .option('--json', 'print machine-readable JSON');\n\n common(\n market\n .command('listings')\n .alias('list')\n .description('Your listings — live, paused, expired, and withdrawn'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { asks } = await (await client(opts)).get<{ asks: MarketAsk[] }>(\n '/api/v1/market/asks',\n );\n output(opts, asks, (rows) => {\n if (rows.length === 0) {\n console.log('No listings yet — post one with `compute market sell`.');\n return;\n }\n for (const ask of rows) console.log(formatListingRow(ask));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('sell')\n .description('Post a listing: sell capacity at a price')\n .requiredOption('--price <usd/unit>', 'price per unit of time (e.g. 0.12/hour)')\n .option('--per <unit>', 'unit for a bare --price usd (second, minute, or hour)')\n .option('--size <tier>', 'size tier to sell (default: medium, else the provider\\'s first tier)')\n .option('--use-case <lane>', 'lane to sell into: actions or sandbox (default: actions)')\n .option('--region <region>', 'region to sell in (default: anywhere the provider runs)')\n .option('--capacity <n>', 'max simultaneous fills (default: 1)')\n .option('--expires-in <hours>', 'delist after this many hours (default: standing)')\n .option('--renew', 're-list for the same window each time it expires (requires --expires-in)'),\n ).action(async (opts: CommonOpts & { price: string; per?: string; size?: string; region?: string; capacity?: string; expiresIn?: string; renew?: boolean; useCase?: string }) => {\n try {\n const c = await client(opts);\n // Validate the lane before any network writes — an unapproved lane\n // still fails server-side with market_lane_not_approved.\n const useCase = parseMarketLane(opts.useCase);\n let size = opts.size;\n if (size === undefined) {\n // The tier is required by the API; when the seller doesn't name one,\n // the provider's middle tier (or first) is the sensible default.\n const { provider } = await c.get<{ provider: MarketProvider }>(\n '/api/v1/market/provider',\n );\n const preset =\n provider.sizes.find((s) => s.name === 'medium') ?? provider.sizes[0];\n if (!preset) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--size is required — ${provider.provider} advertises no size tiers.`,\n );\n }\n size = preset.name;\n console.error(pc.dim(`no --size given — listing at \"${size}\"`));\n }\n const result = await c.post<{ ask: MarketAsk }>(\n '/api/v1/market/asks',\n sellBody({ ...opts, size, useCase }),\n );\n output(opts, result, (r) => {\n console.log(`listed ${pc.cyan(r.ask.id)}`);\n console.log(formatListingRow(r.ask));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('price')\n .description('Reprice a listing')\n .argument('<listing-id>', 'listing ID')\n .requiredOption('--price <usd/unit>', 'new price per unit of time (e.g. 0.08/hour)')\n .option('--per <unit>', 'unit for a bare --price usd (second, minute, or hour)'),\n ).action(async (listingId: string, opts: CommonOpts & { price: string; per?: string }) => {\n try {\n const result = await (await client(opts)).post<{ ask: MarketAsk }>(\n '/api/v1/market/asks',\n listingPatchBody(listingId, { price: opts.price, per: opts.per }),\n );\n output(opts, result, (r) => {\n // A committed-window (rollover) listing keeps its rate in usd/per\n // until the window renews; the new rate sits in pendingUsd/pendingPer.\n const rate =\n r.ask.pendingUsd !== null && r.ask.pendingPer !== null\n ? `${formatRate(r.ask.pendingUsd, r.ask.pendingPer)} ${pc.dim('(applies next window)')}`\n : formatRate(r.ask.usd, r.ask.per);\n console.log(`repriced ${pc.cyan(r.ask.id)} ${rate}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const setStatus = async (\n listingId: string,\n status: 'live' | 'paused',\n opts: CommonOpts,\n ): Promise<void> => {\n try {\n const result = await (await client(opts)).post<{ ask: MarketAsk }>(\n '/api/v1/market/asks',\n listingPatchBody(listingId, { status }),\n );\n output(opts, result, (r) => {\n console.log(`${status === 'live' ? 'resumed' : 'paused'} ${pc.cyan(r.ask.id)}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n };\n\n common(\n market\n .command('pause')\n .description('Pause a listing — it stays posted but cannot fill')\n .argument('<listing-id>', 'listing ID'),\n ).action((listingId: string, opts: CommonOpts) => setStatus(listingId, 'paused', opts));\n\n common(\n market\n .command('resume')\n .description('Resume a paused listing')\n .argument('<listing-id>', 'listing ID'),\n ).action((listingId, opts: CommonOpts) => setStatus(listingId, 'live', opts));\n\n common(\n market\n .command('withdraw')\n .description('Withdraw a listing — it leaves the book for good')\n .argument('<listing-id>', 'listing ID'),\n ).action(async (listingId: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ ask: MarketAsk }>(\n `/api/v1/market/asks?id=${encodeURIComponent(listingId)}`,\n );\n output(opts, result, (r) => {\n console.log(`withdrew ${pc.cyan(r.ask.id)}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('replace')\n .description(\n 'Take capacity back: evict a sale, or pause a listing and evict every sale on it.\\n' +\n \"An evicted Actions job restarts on the buyer's next provider; the buyer pays\\n\" +\n 'only for the seconds the sale actually ran.',\n )\n .argument('[listing-id]', 'listing to pause and evict every sale on')\n .option('--fill <fill-id>', 'evict one sale without touching the listing'),\n ).action(\n async (\n listingId: string | undefined,\n opts: CommonOpts & { fill?: string },\n ) => {\n try {\n const target = replaceTarget(listingId, opts.fill);\n const c = await client(opts);\n if (target.scope === 'fill') {\n const result = await c.post<{ fill: MarketReplacedFill }>(target.path, {});\n output(opts, result, (r) => console.log(formatReplacedFill(r.fill)));\n } else {\n const result = await c.post<MarketListingReplaceResult>(target.path, {});\n output(opts, result, (r) => {\n console.log(`paused ${pc.cyan(r.listing.id)}`);\n if (r.fills.length === 0) {\n console.log(pc.dim(' no live sales to evict'));\n return;\n }\n for (const f of r.fills) {\n if (f.ok) console.log(formatReplacedFill(f.fill));\n else console.log(pc.red(` could not evict a sale — ${f.error}`));\n }\n });\n // A partial eviction is not success: some sales are still running.\n if (result.fills.some((f) => !f.ok)) process.exitCode = 1;\n }\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n common(\n market\n .command('book')\n .description(\"Live prices: sellers' asking prices, buyer offers, recent sales\")\n .option('--use-case <lane>', 'only this lane: actions or sandbox (default: both)'),\n ).action(async (opts: CommonOpts & { useCase?: string }) => {\n try {\n const lane = opts.useCase === undefined ? undefined : parseMarketLane(opts.useCase);\n const book = await (await client(opts)).get<MarketOrderBook>(\n `/api/v1/market/book${lane ? `?useCase=${lane}` : ''}`,\n );\n output(opts, book, (b) => console.log(formatBook(b)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('settlements')\n .description('Your monthly payout reports'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { settlements } = await (await client(opts)).get<{\n settlements: MarketSettlement[];\n }>('/api/v1/market/settlements');\n output(opts, settlements, (rows) => {\n if (rows.length === 0) {\n console.log('No settlements yet.');\n return;\n }\n for (const s of rows) console.log(formatSettlementRow(s));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('status')\n .description('Who you are on the market: seller identity, credential, sizes, regions'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { provider } = await (await client(opts)).get<{\n provider: MarketProvider;\n }>('/api/v1/market/provider');\n output(opts, provider, (p) => console.log(formatProviderStatus(p)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const credential = market\n .command('credential')\n .description('Connect the credential your listings fill under');\n\n common(\n credential\n .command('connect')\n .description(\n 'Save the executor credential your sold capacity runs under. Each field is read from\\n' +\n 'a <PROVIDER>_<FIELD> env var (e.g. TENSORLAKE_API_KEY) — never pass secrets in argv;\\n' +\n '--field name=value overrides a field (visible in shell history)',\n )\n .option('--field <pairs...>', 'credential fields as name=value (prefer env vars for secrets)'),\n ).action(async (opts: CommonOpts & { field?: string[] }) => {\n try {\n const c = await secretValueClient(opts, 'credential values');\n const { provider } = await c.get<{ provider: MarketProvider }>(\n '/api/v1/market/provider',\n );\n if (provider.credentialFields.length === 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `${provider.provider} authenticates with the deployment's own identity — there is no credential to connect.`,\n );\n }\n const resolved = credentialValues(\n provider.provider,\n provider.credentialFields,\n parseInputs(opts.field),\n );\n if (resolved.missing.length > 0) {\n const hints = resolved.missing\n .map((f) => ` export ${resolved.envNames[f.name]}=… # ${f.label}`)\n .join('\\n');\n throw new ActionsCliError(\n 'invalid_argument',\n `Missing credential field${resolved.missing.length === 1 ? '' : 's'}. Set:\\n${hints}`,\n );\n }\n if (resolved.fromFlag.some((name) => provider.credentialFields.find((f) => f.name === name)?.secret)) {\n console.error(\n pc.yellow('note: a secret passed via --field stays in your shell history — prefer the env vars.'),\n );\n }\n const result = await c.post<{ provider: MarketProvider }>(\n '/api/v1/market/provider/credential',\n credentialBody(provider.credentialFields, resolved.values),\n );\n output(opts, result, (r) => {\n console.log(`connected ${pc.cyan(safeTerm(r.provider.name))} credential saved`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n credential\n .command('disconnect')\n .description('Remove the stored credential — listings stop filling until a new one connects'),\n ).action(async (opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ provider: MarketProvider }>(\n '/api/v1/market/provider/credential',\n );\n output(opts, result, (r) => {\n console.log(`disconnected ${pc.cyan(safeTerm(r.provider.name))} credential removed`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * `compute sandboxes` — drive sandboxes placed through the platform's\n * `/api/v1/sandboxes` API: create/list/get/destroy, exec commands, spawn and\n * control detached processes, read/write the filesystem, and resolve port\n * URLs.\n *\n * Auth: identical to `compute actions`/`compute market` — --api-key /\n * COMPUTE_API_KEY / the stored `compute login` session. Types\n * mirror the wire shapes in benchmarks-platform `lib/sandboxes/*` — keep\n * them in sync by hand; the API is the contract.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport type { ActionsClient } from './actions-client.js';\nimport {\n client,\n fail,\n output,\n parseInputs,\n safeTerm,\n usageErrorOutput,\n type CommonOpts,\n} from './actions.js';\n\n/**\n * `--max-price <usd>/<unit>` → the body's `maxPrice` / the quote's\n * maxPriceUsd+maxPricePer params. The unit is required — either inside the\n * value (`0.12/hour`) or via `--max-price-per` — so a bare `--max-price\n * 0.12` never silently defaults to per-second pricing.\n */\nfunction parseMaxPrice(\n value: string | undefined,\n per: string | undefined,\n): { usd: number; per: 'second' | 'minute' | 'hour' } | undefined {\n if (value === undefined) {\n if (per !== undefined) throw new Error('--max-price-per requires --max-price.');\n return undefined;\n }\n let usdText = value;\n let unit: string | undefined = per;\n const slash = value.indexOf('/');\n if (slash !== -1) {\n usdText = value.slice(0, slash);\n const inline = value.slice(slash + 1);\n if (per !== undefined && per !== inline) {\n throw new Error(`--max-price \"${value}\" conflicts with --max-price-per \"${per}\".`);\n }\n unit = inline;\n }\n const usd = Number(usdText);\n if (!/^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/.test(usdText) || !Number.isFinite(usd) || usd <= 0) {\n throw new Error(`Invalid --max-price \"${value}\". Expected a positive dollar amount like 0.12/hour.`);\n }\n if (unit !== 'second' && unit !== 'minute' && unit !== 'hour') {\n throw new Error(\n '--max-price needs a unit — write it as <usd>/<unit> (e.g. --max-price 0.12/hour) or pass --max-price-per hour.',\n );\n }\n return { usd, per: unit };\n}\n\n// ─── Wire types (mirror benchmarks-platform lib/sandboxes) ──────────────────\n\nexport interface SandboxCost {\n rate: { usd: number; unit: string } | null;\n runtimeSeconds: number;\n costUsd: number | null;\n settled: boolean;\n}\n\n/** `toSummary` — one row of GET /api/v1/sandboxes. */\nexport interface SandboxSummary {\n id: string;\n label: string | null;\n provider: string | null;\n providerSandboxId: string | null;\n status: 'creating' | 'running' | 'destroyed' | string;\n placementAttempts: unknown[];\n commandCount: number;\n secrets: string[];\n /** The `boot.image` asked for, and what the provider actually booted. */\n requestedImage: string | null;\n image: string | null;\n createdAt: string;\n lastCommandAt: string | null;\n destroyedAt: string | null;\n destroyError: string | null;\n /** How the sandbox was placed — source, order type, rate, max price, the\n * requested platform `size` and the seller's `box` on a market fill. */\n placement: {\n source: 'market' | 'own-key';\n size?: string | null;\n box?: {\n provider: string;\n sizeName: string | null;\n resources?: { cpus: number | null; memoryMb: number | null; ephemeralDiskMb: number | null };\n };\n orderType?: 'market' | 'limit';\n rate: { usd: number; per: string };\n maxPrice?: { usd: number; per: string };\n } | null;\n cost: SandboxCost;\n}\n\n/** `toDetail` — POST /sandboxes and GET /sandboxes/{id}. */\nexport interface SandboxDetail extends SandboxSummary {\n /** BYOK direct-attach descriptor — null on market fills and ambient providers. */\n attach: { provider: string; providerSandboxId: string; region: string | null } | null;\n}\n\nexport interface SandboxProcess {\n id: string;\n jobId: string;\n pid: number | null;\n command: string;\n cwd: string | null;\n envNames: string[];\n /** Whether the job's stdin pipe is open (spawn `--stdin`). */\n stdin: boolean;\n status: string;\n exitCode: number | null;\n signal: string | null;\n startedAt: string;\n exitedAt: string | null;\n}\n\nexport interface SandboxProcessStatus extends SandboxProcess {\n stdout: string;\n stderr: string;\n}\n\nexport interface CommandResult {\n commandId: string;\n exitCode: number;\n durationMs: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface FileEntry {\n name: string;\n type: 'file' | 'directory';\n size?: number;\n modified?: string;\n}\n\nexport type PathView =\n | { path: string; type: 'file'; content: string }\n | { path: string; type: 'directory'; entries: FileEntry[] };\n\n/** `snapshotView` — one row of GET /sandboxes/{id}/snapshots. */\nexport interface SandboxSnapshot {\n id: string;\n sandboxId: string;\n provider: string;\n region: string | null;\n providerSnapshotId: string;\n label: string | null;\n expiresAt: string | null;\n createdAt: string;\n deletedAt: string | null;\n}\n\n/** POSIX single-quote: argv survives intact through the remote `sh -lc`. */\nfunction shellQuote(arg: string): string {\n return `'${arg.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// ─── Rendering ───────────────────────────────────────────────────────────────\n\nfunction printSandbox(s: SandboxSummary): void {\n const attach = 'attach' in s ? (s as SandboxDetail).attach : undefined;\n console.log(`${pc.cyan(s.id)} ${s.status} ${s.provider ?? '—'} ${s.providerSandboxId ?? '—'}`);\n console.log(` label: ${s.label ?? '—'} commands: ${s.commandCount} created: ${s.createdAt}`);\n if (s.image !== undefined) {\n console.log(` image: ${s.image ?? '—'}${s.requestedImage !== null && s.requestedImage !== s.image ? ` ${pc.dim(`(requested: ${s.requestedImage})`)}` : ''}`);\n }\n if (s.destroyError) console.log(` destroyError: ${pc.red(s.destroyError)}`);\n if (s.placement) {\n const p = s.placement;\n const box = p.box\n ? ` / ${p.box.sizeName ?? 'custom'}${p.box.resources ? ` (${p.box.resources.cpus ?? '?'} vCPU / ${p.box.resources.memoryMb ?? '?'} MB)` : ''}`\n : '';\n console.log(\n ` provider: ${p.box?.provider ?? s.provider ?? '—'}${box}` +\n ` size: ${p.size ?? '—'} order: ${p.orderType ?? '—'} rate: $${p.rate.usd}/${p.rate.per}`,\n );\n }\n if (attach !== undefined) {\n console.log(\n attach === null\n ? ' attach: none (market fill or ambient provider — platform drive only)'\n : ` attach: ${attach.provider} / ${attach.providerSandboxId}${attach.region ? ` (${attach.region})` : ''}`,\n );\n }\n}\n\n/** The GET /sandboxes/quote payload — mirrors SandboxQuote on the platform. */\ninterface SandboxQuoteWire {\n ok: boolean;\n reason?: string;\n providerOrder: string[];\n orderType: 'market' | 'limit';\n placement?: {\n source: 'market' | 'own-key';\n provider: string;\n region: string | null;\n size: string | null;\n box?: {\n provider: string;\n sizeName: string | null;\n resources?: { cpus: number | null; memoryMb: number | null; ephemeralDiskMb: number | null };\n };\n };\n rate?: { usd: number; per: string };\n rateUsd?: { perSecond: number; perMinute: number; perHour: number };\n maxPrice?: { usd: number; per: string };\n estimatedCostUsd?: number;\n marketCapUsdPerHour?: number;\n protectionLimitUsdPerHour?: number;\n cheapestLiveUsdPerHour?: number;\n referenceUsdPerHour?: number;\n liveAskDepth?: number;\n creditBalanceUsd: number;\n requiredHoldUsd?: number;\n topUpPath?: string;\n}\n\nconst usd = (n: number | undefined, suffix = ''): string =>\n n === undefined ? '—' : `$${n.toFixed(4).replace(/0+$/, '').replace(/\\.$/, '.00')}${suffix}`;\n\nfunction printQuote(q: SandboxQuoteWire, timeoutMs?: string): void {\n console.log(`quote: ${q.ok ? pc.green('ok') : pc.red(q.reason ?? 'unfillable')}`);\n const box = q.placement?.box;\n console.log(\n ` size: ${q.placement?.size ?? '—'} provider: ${q.placement?.provider ?? '—'}` +\n (box ? ` box: ${box.sizeName ?? 'custom'} (${box.provider}${box.resources ? `, ${box.resources.cpus ?? '?'} vCPU / ${box.resources.memoryMb ?? '?'} MB` : ''})` : ''),\n );\n console.log(` order type: ${q.orderType} order: ${q.providerOrder.join(', ')}`);\n if (q.rateUsd) {\n console.log(` rate: ${usd(q.rateUsd.perHour, '/hour')} cheapest live: ${usd(q.cheapestLiveUsdPerHour, '/hr')} reference: ${usd(q.referenceUsdPerHour, '/hr')}`);\n } else if (q.rate) {\n console.log(` rate: $${q.rate.usd}/${q.rate.per}`);\n }\n const timeout = timeoutMs !== undefined ? ` for ${timeoutMs}ms` : '';\n console.log(` est. cost${timeout}: ${usd(q.estimatedCostUsd)} required hold: ${usd(q.requiredHoldUsd)}`);\n console.log(\n ` cap: ${q.maxPrice ? `$${q.maxPrice.usd}/${q.maxPrice.per}` : usd(q.marketCapUsdPerHour, '/hr')}` +\n ` protection limit: ${usd(q.protectionLimitUsdPerHour, '/hr')} balance: ${usd(q.creditBalanceUsd)}`,\n );\n if (!q.ok && q.topUpPath) console.log(` ${pc.dim(`→ ${q.topUpPath}`)}`);\n if (q.liveAskDepth !== undefined) console.log(` ${pc.dim(`live asks: ${q.liveAskDepth}`)}`);\n}\n\nfunction printProcess(p: SandboxProcess | SandboxProcessStatus): void {\n const exit = p.status === 'exited' ? `exit=${p.exitCode ?? '?'}${p.signal ? ` (${p.signal})` : ''}` : '';\n const stdin = p.stdin && p.status === 'running' ? ' [stdin open]' : '';\n console.log(`${pc.cyan(p.jobId)} ${p.status}${exit ? ' ' + exit : ''}${stdin} ${p.command}`);\n}\n\nfunction printSnapshot(s: SandboxSnapshot): void {\n const state = s.deletedAt !== null ? ` ${pc.dim(`(deleted ${s.deletedAt})`)}` : '';\n console.log(`${pc.cyan(s.id)} ${s.providerSnapshotId}${state}`);\n console.log(\n ` provider: ${s.provider}${s.region ? ` (${s.region})` : ''} label: ${s.label ?? '—'} created: ${s.createdAt}${s.expiresAt ? ` expires: ${s.expiresAt}` : ''}`,\n );\n}\n\n// ─── Commands ────────────────────────────────────────────────────────────────\n\ninterface LeadOptSpec {\n /** Accepted spellings, e.g. ['-e', '--env']. */\n aliases: string[];\n /** Commander-style camelCase key merged into the parsed options. */\n key: string;\n /** 'bool' takes no value; 'value' takes one; 'repeat' collects repeated values. */\n flag: 'bool' | 'value' | 'repeat';\n}\n\nconst AUTH_LEAD_OPTS: LeadOptSpec[] = [\n { aliases: ['--api-key'], key: 'apiKey', flag: 'value' },\n { aliases: ['--base-url'], key: 'baseUrl', flag: 'value' },\n { aliases: ['--allow-untrusted-host'], key: 'allowUntrustedHost', flag: 'bool' },\n { aliases: ['--org'], key: 'org', flag: 'value' },\n { aliases: ['--json'], key: 'json', flag: 'bool' },\n];\n\nconst EXEC_LEAD_OPTS: LeadOptSpec[] = [\n ...AUTH_LEAD_OPTS,\n { aliases: ['--timeout-ms'], key: 'timeoutMs', flag: 'value' },\n];\n\nconst SPAWN_LEAD_OPTS: LeadOptSpec[] = [\n ...AUTH_LEAD_OPTS,\n { aliases: ['--cwd'], key: 'cwd', flag: 'value' },\n { aliases: ['-e', '--env'], key: 'env', flag: 'repeat' },\n { aliases: ['--stdin'], key: 'stdin', flag: 'bool' },\n];\n\n/**\n * `exec`/`spawn` run under `.passThroughOptions()`: everything after\n * `<sandboxId>` arrives in the variadic `<command...>` untouched, so a flag\n * like `uname -a` or `node -e …` reaches the sandbox instead of being eaten\n * as a CLI option. CLI options still parse when placed *before* the sandbox\n * id; this helper additionally accepts them between the id and the command —\n * parse leading known options, stop at the first non-option word or `--`.\n */\nexport function takeLeadingOptions(\n argv: string[],\n specs: LeadOptSpec[],\n): { command: string[]; inline: Record<string, string | string[] | true> } {\n const byAlias = new Map<string, LeadOptSpec>();\n for (const spec of specs) for (const alias of spec.aliases) byAlias.set(alias, spec);\n const inline: Record<string, string | string[] | true> = {};\n let i = 0;\n for (; i < argv.length; i++) {\n const token = argv[i];\n if (token === '--') {\n i++;\n break;\n }\n if (!token.startsWith('-') || token === '-') break;\n const eq = token.indexOf('=');\n const flag = eq === -1 ? token : token.slice(0, eq);\n let spec = byAlias.get(flag);\n // Attached short-option value, e.g. `-eFOO=bar` (commander accepts the\n // same form before the sandbox id).\n let attached: string | undefined;\n if (!spec && !flag.startsWith('--') && flag.length > 2) {\n const shortSpec = byAlias.get(flag.slice(0, 2));\n if (shortSpec && shortSpec.flag !== 'bool') {\n spec = shortSpec;\n attached = flag.slice(2);\n if (attached.startsWith('=')) attached = attached.slice(1);\n if (eq !== -1) attached += token.slice(eq);\n }\n }\n if (!spec) {\n throw new Error(\n `unknown option '${flag}' — pass CLI options before the command, or use -- to separate them`,\n );\n }\n if (spec.flag === 'bool') {\n if (eq !== -1) throw new Error(`option '${flag}' takes no value`);\n inline[spec.key] = true;\n } else {\n const value = attached ?? (eq !== -1 ? token.slice(eq + 1) : argv[++i]);\n if (value === undefined) throw new Error(`option '${flag}' requires a value`);\n if (spec.flag === 'repeat') {\n ((inline[spec.key] ??= []) as string[]).push(value);\n } else {\n inline[spec.key] = value;\n }\n }\n }\n return { command: argv.slice(i), inline };\n}\n\nfunction mergeLeadOpts<T>(opts: T, inline: Record<string, string | string[] | true>): T {\n const merged = { ...opts } as Record<string, unknown>;\n for (const [key, value] of Object.entries(inline)) {\n if (Array.isArray(value)) {\n merged[key] = [...((merged[key] as string[] | undefined) ?? []), ...value];\n } else {\n merged[key] = value;\n }\n }\n return merged as T;\n}\n\nexport function registerSandboxesCommands(program: Command): void {\n const cmd = program\n .command('sandboxes')\n .alias('sbx')\n .description('Create and drive sandboxes through the platform')\n .enablePositionalOptions()\n .configureOutput({ outputError: usageErrorOutput });\n\n cmd\n .command('create')\n .description('Place a sandbox (provider order walks 1,2,3; \"market\" bids first)')\n .option('--order <providers>', 'provider order, comma-separated (e.g. \"market,blaxel,vercel\")')\n .option('--size <size>', 'platform size: small (1 vCPU/2 GB), medium, large, xlarge (8/16 GB); default medium')\n .option('--label <label>', 'label for the sandbox')\n .option('--image <image>', 'container image to boot')\n .option('--snapshot-id <id>', 'provider snapshot to resume')\n .option('--cpus <n>', 'CPU cores (raw resources — mutually exclusive with --size)')\n .option('--memory-mb <n>', 'memory in MB (raw resources)')\n .option('--disk-mb <n>', 'ephemeral disk in MB (raw resources)')\n .option('--max-price <usd/unit>', 'max price for a market fill (e.g. 0.12/hour); makes the create a limit order')\n .option('--max-price-per <unit>', 'unit for a bare --max-price usd (second, minute, or hour)')\n .option('--market', 'place the create on the compute market (order type \"market\")')\n .option('--order-type <type>', 'explicit market order type: market or limit')\n .option('--timeout-ms <ms>', 'sandbox timeout in ms')\n .option('--secret <name>', 'vault secret name to inject (repeatable)', (v, a: string[]) => a.concat(v), [] as string[])\n .option('--api-key <key>', 'platform API key (or COMPUTE_API_KEY)')\n .option('--base-url <url>', 'platform base URL')\n .option('--allow-untrusted-host', 'allow non-computesdk.com base URLs')\n .option('--json', 'print the raw response')\n .action(async (opts: CommonOpts & {\n order?: string; label?: string; image?: string; snapshotId?: string;\n size?: string; cpus?: string; memoryMb?: string; diskMb?: string; timeoutMs?: string;\n maxPrice?: string; maxPricePer?: string; market?: boolean; orderType?: string;\n secret?: string[];\n }) => {\n try {\n const c = await client(opts);\n const resources: Record<string, number> = {};\n if (opts.cpus) resources.cpus = Number(opts.cpus);\n if (opts.memoryMb) resources.memoryMb = Number(opts.memoryMb);\n if (opts.diskMb) resources.ephemeralDiskMb = Number(opts.diskMb);\n const body: Record<string, unknown> = {};\n if (opts.order) body.providerOrder = opts.order.split(',').map((s) => s.trim());\n if (opts.size) body.size = opts.size;\n if (opts.label) body.label = opts.label;\n if (opts.image) body.image = opts.image;\n if (opts.snapshotId) body.snapshotId = opts.snapshotId;\n if (opts.timeoutMs) body.timeoutMs = Number(opts.timeoutMs);\n if (opts.secret && opts.secret.length > 0) body.secrets = opts.secret;\n if (Object.keys(resources).length > 0) body.resources = resources;\n const maxPrice = parseMaxPrice(opts.maxPrice, opts.maxPricePer);\n if (maxPrice) body.maxPrice = { usd: maxPrice.usd, per: maxPrice.per };\n if (opts.orderType && opts.market) {\n throw new Error('--market and --order-type are mutually exclusive.');\n }\n if (opts.orderType) body.orderType = opts.orderType;\n if (opts.market) body.orderType = 'market';\n const res = await c.post<{ sandbox: SandboxDetail }>('/api/v1/sandboxes', body);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('quote')\n .description('Quote a sandbox create: placement, rate, caps and credits — creates nothing')\n .option('--size <size>', 'platform size (or raw resource flags; default medium)')\n .option('--cpus <n>', 'CPU cores')\n .option('--memory-mb <n>', 'memory in MB')\n .option('--disk-mb <n>', 'ephemeral disk in MB')\n .option('--region <region>', 'pin the placement region')\n .option('--timeout-ms <ms>', 'sandbox timeout in ms')\n .option('--order-type <type>', 'market order type: market or limit')\n .option('--market', 'quote a market order (fills at the live price, protection-bounded)')\n .option('--max-price <usd/unit>', 'max price for a market fill (e.g. 0.12/hour)')\n .option('--max-price-per <unit>', 'unit for a bare --max-price usd (second, minute, or hour)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (opts: CommonOpts & {\n size?: string; cpus?: string; memoryMb?: string; diskMb?: string;\n region?: string; timeoutMs?: string; orderType?: string; market?: boolean;\n maxPrice?: string; maxPricePer?: string;\n }) => {\n try {\n const c = await client(opts);\n const params: Record<string, string | undefined> = {\n size: opts.size,\n cpus: opts.cpus,\n memoryMb: opts.memoryMb,\n ephemeralDiskMb: opts.diskMb,\n region: opts.region,\n timeoutMs: opts.timeoutMs,\n orderType: opts.market ? 'market' : opts.orderType,\n };\n if (opts.orderType && opts.market) {\n throw new Error('--market and --order-type are mutually exclusive.');\n }\n const maxPrice = parseMaxPrice(opts.maxPrice, opts.maxPricePer);\n if (maxPrice) {\n params.maxPriceUsd = String(maxPrice.usd);\n params.maxPricePer = maxPrice.per;\n }\n const res = await c.get<{ quote: SandboxQuoteWire }>(\n '/api/v1/sandboxes/quote',\n params,\n );\n output(opts, res.quote, (quote) => printQuote(quote, opts.timeoutMs));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('list')\n .description('List sandboxes')\n .option('--status <status>', 'creating | running | destroyed')\n .option('--limit <n>', 'page size')\n .option('--cursor <cursor>', 'page cursor from a previous response')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (opts: CommonOpts & { status?: string; limit?: string; cursor?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ sandboxes: SandboxSummary[]; nextCursor: string | null }>(\n '/api/v1/sandboxes',\n { status: opts.status, limit: opts.limit, cursor: opts.cursor },\n );\n output(opts, res, (page) => {\n page.sandboxes.forEach(printSandbox);\n if (page.nextCursor) console.log(pc.dim(`nextCursor: ${page.nextCursor}`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('get <sandboxId>')\n .description('Show one sandbox (includes the BYOK attach descriptor)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ sandbox: SandboxDetail }>(`/api/v1/sandboxes/${sandboxId}`);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('destroy <sandboxId>')\n .description('Destroy a sandbox (verified teardown + cost settle)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.del<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${sandboxId}`);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('exec <sandboxId> <command...>')\n .description('Run a one-shot command and print its result (options before the command; -- also works)')\n .option('--timeout-ms <ms>', 'command timeout in ms')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .passThroughOptions()\n .action(async (sandboxId: string, rawCommand: string[], rawOpts: CommonOpts & { timeoutMs?: string }) => {\n let opts = rawOpts;\n try {\n const lead = takeLeadingOptions(rawCommand, EXEC_LEAD_OPTS);\n opts = mergeLeadOpts(rawOpts, lead.inline);\n const command = lead.command;\n if (command.length === 0) throw new Error('missing command to run');\n const c = await client(opts);\n const res = await c.post<{ commandId: string } & CommandResult>(\n `/api/v1/sandboxes/${sandboxId}/commands`,\n {\n command: command.map(shellQuote).join(' '),\n ...(opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}),\n },\n );\n output(opts, res, (r) => {\n process.stdout.write(r.stdout);\n if (r.stderr) process.stderr.write(r.stderr);\n if (!r.stdout) console.log(`exit ${r.exitCode} (${r.durationMs}ms)`);\n });\n // exitCode, not exit(): a piped stdout flushes before the CLI exits.\n if (res.exitCode !== 0) process.exitCode = res.exitCode;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('spawn <sandboxId> <command...>')\n .description('Start a detached process that outlives this request (options before the command; -- also works)')\n .option('--cwd <dir>', 'working directory')\n .option('-e, --env <key=value>', 'environment variable (repeatable)', (v, a: string[]) => a.concat(v), [] as string[])\n .option('--stdin', 'keep the process\\'s stdin pipe open for `stdin`/`close-stdin`')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .passThroughOptions()\n .action(async (sandboxId: string, rawCommand: string[], rawOpts: CommonOpts & { cwd?: string; env?: string[]; stdin?: boolean }) => {\n let opts = rawOpts;\n try {\n const lead = takeLeadingOptions(rawCommand, SPAWN_LEAD_OPTS);\n opts = mergeLeadOpts(rawOpts, lead.inline);\n const command = lead.command;\n if (command.length === 0) throw new Error('missing command to spawn');\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${sandboxId}/processes`,\n {\n command: command.map(shellQuote).join(' '),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {}),\n ...(opts.stdin ? { stdin: true } : {}),\n },\n );\n output(opts, res.process, printProcess);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('ps <sandboxId>')\n .description('List the sandbox\\'s tracked processes')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ processes: SandboxProcess[] }>(\n `/api/v1/sandboxes/${sandboxId}/processes`,\n );\n output(opts, res.processes, (list) => list.forEach(printProcess));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('logs <sandboxId> <jobId>')\n .description('Show a process\\'s buffered output (--follow streams until exit)')\n .option('-f, --follow', 'stream output until the process exits')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { follow?: boolean }) => {\n try {\n const c = await client(opts);\n if (opts.follow) {\n await followProcess(c, sandboxId, jobId);\n return;\n }\n const res = await c.get<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`,\n );\n output(opts, res.process, (p) => {\n if (p.stdout) process.stdout.write(p.stdout);\n if (p.stderr) process.stderr.write(p.stderr);\n if (!p.stdout && !p.stderr) printProcess(p);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('wait <sandboxId> <jobId>')\n .description('Block until a process exits')\n .option('--timeout-ms <ms>', 'bound the wait (job keeps running on timeout)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { timeoutMs?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/wait`,\n opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {},\n );\n output(opts, res.process, printProcess);\n if (res.process.status === 'exited') {\n // A null exit code (signal-terminated) is still a failure, not 0.\n process.exitCode = res.process.exitCode ?? 128;\n }\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('kill <sandboxId> <jobId>')\n .description('Signal a process (default SIGTERM)')\n .option('--signal <signal>', 'signal name or number, e.g. SIGKILL or 9')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { signal?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/kill`,\n opts.signal ? { signal: opts.signal } : {},\n );\n output(opts, res.process, printProcess);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('stdin <sandboxId> <jobId>')\n .description('Write to a process\\'s stdin pipe (spawn with --stdin; --data, --file, or piped)')\n .option('--data <text>', 'data to write')\n .option('--file <local>', 'read data from a local file')\n .option('--base64', 'base64-encode the input before sending (binary-safe)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { data?: string; file?: string; base64?: boolean }) => {\n try {\n let data = opts.data;\n if (data === undefined && opts.file) {\n const { readFile } = await import('node:fs/promises');\n data = opts.base64\n ? (await readFile(opts.file)).toString('base64')\n : await readFile(opts.file, 'utf8');\n }\n if (data === undefined && !process.stdin.isTTY) {\n // Buffer raw bytes — decoding as utf8 first would corrupt binary\n // input before --base64 could encode it.\n const piped = await new Promise<Buffer>((resolve) => {\n const chunks: Buffer[] = [];\n process.stdin.on('data', (chunk) => chunks.push(chunk));\n process.stdin.on('end', () => resolve(Buffer.concat(chunks)));\n });\n data = opts.base64 ? piped.toString('base64') : piped.toString('utf8');\n }\n if (data === undefined || data === '') {\n console.error(pc.red('Pass --data, --file, or pipe stdin'));\n process.exit(1);\n }\n if (opts.base64 && opts.data !== undefined) {\n data = Buffer.from(data).toString('base64');\n }\n const c = await client(opts);\n const res = await c.post<{ ok: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/stdin`,\n { data, ...(opts.base64 ? { encoding: 'base64' } : {}) },\n );\n output(opts, res, () => console.log(`wrote ${data.length} chars to ${jobId}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('close-stdin <sandboxId> <jobId>')\n .description('Close a process\\'s stdin pipe')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ ok: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/close-stdin`,\n {},\n );\n output(opts, res, () => console.log(`closed stdin on ${jobId}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('ls <sandboxId> [path]')\n .description('List a directory (or stat a path) inside the sandbox')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string | undefined, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${sandboxId}/files`, {\n path: path ?? '/',\n });\n output(opts, res, (view) => {\n if (view.type === 'directory') {\n for (const e of view.entries) {\n console.log(`${e.type === 'directory' ? pc.blue('d') : ' '} ${e.name}${e.size !== undefined ? ` ${pc.dim(String(e.size))}` : ''}`);\n }\n } else {\n console.log(`${view.path} file ${view.content.length} chars`);\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('cat <sandboxId> <path>')\n .description('Print a file\\'s contents')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${sandboxId}/files`, { path });\n output(opts, res, (view) => {\n if (view.type !== 'file') {\n console.error(pc.red(`${view.path} is a directory`));\n process.exit(1);\n }\n process.stdout.write(view.content);\n if (!view.content.endsWith('\\n')) process.stdout.write('\\n');\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('write <sandboxId> <path>')\n .description('Write a file inside the sandbox (--content or --file <local>, else stdin)')\n .option('--content <text>', 'file contents')\n .option('--file <local>', 'read contents from a local file')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts & { content?: string; file?: string }) => {\n try {\n let content = opts.content;\n if (content === undefined && opts.file) {\n const { readFile } = await import('node:fs/promises');\n content = await readFile(opts.file, 'utf8');\n }\n if (content === undefined && !process.stdin.isTTY) {\n content = await new Promise<string>((resolve) => {\n let data = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk) => (data += chunk));\n process.stdin.on('end', () => resolve(data));\n });\n }\n if (content === undefined) {\n console.error(pc.red('Pass --content, --file, or pipe stdin'));\n process.exit(1);\n }\n const c = await client(opts);\n const res = await c.post<{ path: string; type: string }>(\n `/api/v1/sandboxes/${sandboxId}/files`,\n { path, content },\n );\n output(opts, res, (r) => console.log(`wrote ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('mkdir <sandboxId> <path>')\n .description('Create a directory (parents included)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ path: string }>(`/api/v1/sandboxes/${sandboxId}/files`, {\n path,\n mkdir: true,\n });\n output(opts, res, (r) => console.log(`created ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('rm <sandboxId> <path>')\n .description('Remove a file or directory inside the sandbox')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.del<{ path: string; removed: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/files?path=${encodeURIComponent(path)}`,\n );\n output(opts, res, (r) => console.log(`removed ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('url <sandboxId>')\n .description('Resolve the provider\\'s public URL for a port')\n .requiredOption('--port <n>', 'port the service listens on')\n .option('--protocol <protocol>', 'protocol (default provider-chosen)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts & { port: string; protocol?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ url: string }>(`/api/v1/sandboxes/${sandboxId}/urls`, {\n port: opts.port,\n protocol: opts.protocol,\n });\n output(opts, res, (r) => console.log(safeTerm(r.url)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('snapshots <sandboxId>')\n .description('List the sandbox\\'s snapshots')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ snapshots: SandboxSnapshot[] }>(\n `/api/v1/sandboxes/${sandboxId}/snapshots`,\n );\n output(opts, res.snapshots, (list) => list.forEach(printSnapshot));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('snapshot <sandboxId>')\n .description('Snapshot a running sandbox through its provider')\n .option('--label <label>', 'label for the snapshot')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts & { label?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ snapshot: SandboxSnapshot }>(\n `/api/v1/sandboxes/${sandboxId}/snapshots`,\n opts.label ? { label: opts.label } : {},\n );\n output(opts, res.snapshot, printSnapshot);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('snapshot-delete <sandboxId> <snapshotId>')\n .description('Delete a snapshot\\'s provider artifact')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, snapshotId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.del<{ ok: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/snapshots/${snapshotId}`,\n );\n output(opts, res, () => console.log(`deleted snapshot ${snapshotId}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n // One-off org override on every subcommand — sent as X-Org-Slug.\n for (const sub of cmd.commands) {\n sub.option('--org <slug>', 'organization slug for this command (or $COMPUTE_ORG)');\n }\n}\n\n/** Streams a process's daemon-buffered output to the console until `exit`. */\nasync function followProcess(\n c: ActionsClient,\n sandboxId: string,\n jobId: string,\n): Promise<void> {\n let exitCode = 0;\n for await (const { event, data } of c.sseNamed(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`,\n )) {\n const payload = data as Record<string, unknown>;\n if (event === 'stdout') process.stdout.write(String(payload.chunk ?? ''));\n else if (event === 'stderr') process.stderr.write(String(payload.chunk ?? ''));\n else if (event === 'exit') {\n // A null exit code means a signal killed the process — still a failure.\n exitCode = typeof payload.exitCode === 'number' ? payload.exitCode : 128;\n return finish();\n } else if (event === 'error') {\n console.error(pc.red(`Error: ${String(payload.error ?? 'stream error')}`));\n return finish(1);\n }\n }\n // The stream ended without an `exit` event — the process may still be\n // running; reporting success would be wrong either way.\n console.error(pc.yellow('stream ended before the process exited'));\n return finish(2);\n\n function finish(code?: number): void {\n if (code !== undefined) exitCode = code;\n if (exitCode !== 0) process.exitCode = exitCode;\n }\n}\n"],"mappings":";;;AAeA,OAAO;AACP,SAAS,eAAe;AACxB,YAAY,OAAO;AACnB,OAAOA,SAAQ;AACf,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,QAAAC,aAAY;;;ACE9B,IAAM,eAAgD;AAAA,EACpD,KAAK,EAAE,aAAa,CAAC,CAAC,aAAa,CAAC,GAAG,YAAY,EAAE,aAAa,SAAS,EAAE;AAAA,EAC7E,SAAS,EAAE,aAAa,CAAC,CAAC,mBAAmB,CAAC,GAAG,YAAY,EAAE,mBAAmB,QAAQ,EAAE;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7B,CAAC;AACD,UAAQ,IAAI,8BAA8B,OAAO,aAAa,IAAI,KAAK,OAAO,aAAa,EAAE,GAAG;AAClG,CAAC;AAEH,IACG,QAAQ,SAAS,EACjB,YAAY,+CAA+C,EAC3D,OAAO,oBAAoB,uBAAuB,EAClD,OAAO,UAAU,6BAA6B,EAC9C,OAAO,CAAC,SAAS,YAAY,IAAI,CAAC;AAErC,QACG,QAAQ,QAAQ,EAChB,YAAY,+CAA+C,EAC3D,OAAO,oBAAoB,uBAAuB,EAClD,OAAO,UAAU,6BAA6B,EAC9C,OAAO,CAAC,SAAS,YAAY,IAAI,CAAC;AAIrC,wBAAwB,OAAO;AAM/B,uBAAuB,OAAO;AAM9B,0BAA0B,OAAO;AAOjC,QACG,QAAQ,OAAO,EACf,YAAY,6FAA6F,EACzG,mBAAmB,EACnB,WAAW,KAAK,EAChB,OAAO,MAAM;AAEd,CAAC;AAOH,eAAe,OAAO;AACpB,MAAI,QAAQ,KAAK,CAAC,MAAM,WAAW,QAAQ,KAAK,CAAC,MAAM,aAAa;AAClE,UAAM,EAAE,KAAK,SAAS,IAAI,MAAM,OAAO,kBAAkB;AACzD,UAAM,SAAS,QAAQ,KAAK,MAAM,CAAC,CAAC;AACpC;AAAA,EACF;AACA,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAMA,IAAG,IAAI;AAAA,SAAY,MAAM,OAAO,EAAE,CAAC;AACjD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["pc","readFileSync","join","client","p","usd","program","org","pc","usd","pc","p","program","pc","usd","pc","p","program","__filename","__dirname","readFileSync","join","pc","org"]}