@computesdk/cli 2.6.18 → 2.6.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -3
- package/cli-manifest.json +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +7 -6
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/.pnpm/tsup@8.5.0_jiti@2.7.0_postcss@8.5.6_tsx@4.20.3_typescript@5.8.3_yaml@2.9.1/node_modules/tsup/assets/esm_shims.js","../src/actions-client.ts","../src/term.ts","../src/settings.ts","../src/confirm.ts","../src/actions-runs.ts","../src/actions-workflows.ts","../src/actions-repos.ts","../src/actions-integrations.ts","../src/actions.ts","../src/exec.ts","../src/sync-fs.ts","../src/snapshot-engine.ts","../src/index.ts","../src/providers.ts","../src/byok.ts","../src/rate-display.ts","../src/market.ts","../src/credits.ts","../src/option-inheritance.ts","../src/sandboxes.ts","../src/current-instance.ts","../src/sandbox-billing.ts","../src/sync.ts","../src/sync-retention.ts","../src/onboarding.ts","../src/login.ts","../src/session.ts","../src/net.ts","../src/agents.ts","../src/status.ts","../src/bench.ts","../src/manifest.ts","../src/org-members.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * The platform transport moved to `@computesdk/platform` in cli 2.x — this\n * file re-exports the moved names under their old `Actions*` names for one\n * release, keeps the Actions wire types, and defines `ActionsClient` as the\n * `PlatformClient` subclass with the Actions `org()` endpoint.\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 */\nimport {\n DEFAULT_BASE_URL,\n PlatformApiError,\n PlatformClient,\n PlatformClientError,\n codeForStatus,\n errorDetails,\n isSecurePlatformTransport,\n isTrustedPlatformHost,\n readSseEvents,\n readSseNamedEvents,\n resolvePlatformAuth,\n toErrorEnvelope,\n} from '@computesdk/platform';\nimport type {\n PlatformAuth,\n PlatformClientErrorCode,\n PlatformErrorEnvelope,\n StoredPlatformAuth,\n StoredPlatformAuthResolver,\n} from '@computesdk/platform';\n\nexport {\n DEFAULT_BASE_URL,\n PlatformApiError as ActionsApiError,\n PlatformClientError as ActionsCliError,\n codeForStatus,\n errorDetails,\n isSecurePlatformTransport as isSecureActionsTransport,\n isTrustedPlatformHost as isTrustedActionsHost,\n readSseEvents,\n readSseNamedEvents,\n toErrorEnvelope,\n};\n\nconst CLI_CREDENTIALS_HINT =\n 'Set COMPUTE_API_KEY, pass --api-key, or run `compute login`.';\n\n/** `resolvePlatformAuth` with the CLI's flag-style credentials hint. */\nexport function resolveActionsAuth(\n opts: Parameters<typeof resolvePlatformAuth>[0],\n resolveStored?: StoredPlatformAuthResolver,\n): Promise<PlatformAuth> {\n return resolvePlatformAuth(opts, resolveStored, CLI_CREDENTIALS_HINT);\n}\nexport type {\n PlatformAuth as ActionsAuth,\n PlatformClientErrorCode as ActionsCliErrorCode,\n PlatformErrorEnvelope as ActionsErrorEnvelope,\n StoredPlatformAuth,\n StoredPlatformAuthResolver,\n};\n\nexport interface ActionsOrg {\n organizationId: string;\n name: string;\n slug: string;\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\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\n/** A row of `GET /api/v1/actions/workflows`: the dispatch picker row plus its controls and latest run. */\nexport interface CiWorkflowListItem extends CiWorkflow {\n /** Runs at all: the repo is enabled and the workflow is not user-disabled. */\n enabled: boolean;\n repoEnabled: boolean;\n userDisabledAt: string | null;\n /** Per-workflow placement order; null inherits the org order. */\n providerOrder: string[] | null;\n /** Per-workflow snapshot cap; null is the dynamic pool, 0 is off. */\n snapshotCap: number | null;\n lastRun: { id: string; conclusion: CiConclusion; queuedAt: string } | null;\n}\n\n/** A workflow file only the listed ref has: dispatched by repo and path on that ref. */\nexport interface CiRefOnlyWorkflow {\n name: string;\n path: string;\n inputs: CiWorkflowInput[];\n dispatchable: boolean;\n}\n\nexport interface CiWorkflowsResponse {\n workflows: CiWorkflowListItem[];\n /** Present when the list was asked for with `ref`. */\n refOnly?: CiRefOnlyWorkflow[];\n}\n\n/** `PATCH /api/v1/actions/workflows`: a workflow's user-owned controls after the change. */\nexport interface CiWorkflowControls {\n repoFullName: string;\n path: string;\n enabled: boolean;\n userDisabledAt: string | null;\n providerOrder: string[] | null;\n snapshotCap: number | null;\n}\n\nexport type CiConclusion = 'passed' | 'failed' | 'running' | 'cancelled' | 'none';\n\nexport interface CiScheduleWorkflow {\n repoFullName: string;\n workflowName: string;\n workflowPath: string;\n}\n\nexport interface CiScheduleRun extends CiScheduleWorkflow {\n id: string;\n event: string;\n ref: string;\n status: 'queued' | 'running' | 'completed';\n conclusion: string;\n startedAt: string | null;\n createdAt: string;\n}\n\n/** `GET /api/v1/actions/schedule`: daily totals, paginated runs and capped fires. */\nexport interface CiSchedule {\n from: string;\n to: string;\n timeZone: string;\n countsTruncated: boolean;\n days: (CiScheduleWorkflow & {\n date: string;\n runs: { total: number; byConclusion: Record<string, number>; items: CiScheduleRun[] };\n upcoming: { total: number; items: string[] };\n })[];\n runs: CiScheduleRun[];\n nextCursor: string | null;\n upcoming: (CiScheduleWorkflow & {\n scheduleId: string;\n cron: string;\n description: string;\n occurrences: string[];\n occurrenceCount: number;\n truncated: boolean;\n countTruncated: boolean;\n })[];\n}\n\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 /** When the run was archived (hidden from the default lists), else null. */\n archivedAt?: string | null;\n jobs: CiJob[];\n logTail: string[];\n /**\n * Benchmark runs this run produced (linked by `benchmark_run_executions.ci_run_id`).\n * `[]` when the workflow ran no benchmark; a benchmark still running is listed\n * with `providers: []` until its summary is uploaded.\n */\n benchmarks?: CiRunBenchmarkResult[];\n}\n\n/** The `(startedAt, id)` position after a day page's last row. */\nexport interface CiRunsCursor {\n startedAt: string;\n id: string;\n}\n\n/** `GET /api/v1/actions/runs/day/{day}`: one page; `nextCursor` is null on the last. */\nexport interface CiRunsPage {\n runs: CiRun[];\n nextCursor?: CiRunsCursor | null;\n}\n\n/** One row of `GET /api/v1/actions/run-days`. */\nexport interface CiRunDay {\n day: string;\n count: number;\n}\n\n/** `POST /api/v1/actions/runs/archive`: how many runs changed, and the stamp (null when unarchiving). */\nexport interface CiRunArchiveResponse {\n archived: number;\n archivedAt: string | null;\n}\n\n/** One benchmark run linked to an Actions run, from `GET /api/v1/actions/runs/{id}`. */\nexport interface CiRunBenchmarkResult {\n benchmarkSlug: string;\n benchmarkName: string;\n benchmarkRunId: string;\n status: string;\n dashboardUrl: string;\n startedAt: string | null;\n endedAt: string | null;\n providers: CiRunBenchmarkProvider[];\n}\n\n/** One provider row of a benchmark result; `dimensions: {}` is the provider's overall row. */\nexport interface CiRunBenchmarkProvider {\n provider: string;\n dimensions: Record<string, unknown>;\n compositeScore: number | null;\n scoringVersion: string | null;\n successRate: number | null;\n skipped: boolean;\n skipReason: string | null;\n metrics: Record<string, { median: number; p95: number; p99: number; unit: string }>;\n scalars: Record<string, number>;\n scalarUnits: Record<string, 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 /** The stored key's last verification; absent from servers that predate it. */\n status?: 'connected' | 'error' | 'unconfigured';\n statusDetail?: string | null;\n /** The stored key's masked hint — never the key. */\n keyHint?: string | null;\n lastCheckedAt?: string | null;\n}\n\n/** A GitHub App installation on `GET /api/v1/actions/installations` — never a token. */\nexport interface CiInstallation {\n githubInstallationId: number;\n account: string;\n accountType: string | null;\n accountAvatarUrl: string | null;\n appSlug: string;\n repoSelection: 'all' | 'selected';\n suspended: boolean;\n suspendedAt: string | null;\n installedAt: string;\n configureUrl: string | null;\n repos: { granted: number; enabled: number };\n}\n\nexport interface CiInstallationsResponse {\n installations: CiInstallation[];\n}\n\n/**\n * Where a signed-in owner/admin starts an install in their browser. The\n * platform never mints the signed install link for an API credential.\n */\nexport interface CiInstallLink {\n configured: boolean;\n url: string | null;\n /** GitHub only. */\n appSlug?: string | null;\n}\n\n/** The org's Slack connection on `GET /api/v1/actions/slack` — never the bot token. */\nexport interface CiSlackConnection {\n installed: boolean;\n teamName: string | null;\n channelId: string | null;\n channelName: string | null;\n notifyOn: 'all' | 'failure';\n brief: { enabled: boolean; times: string[]; timeZone: string; categories: string[] };\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\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: CiApiRepo[];\n}\n\nexport type CiPollSchedule = 'disabled' | 'never' | 'scheduled';\n\n/**\n * A repo on `GET /api/v1/actions/repos` since the platform added poll state\n * and run counts. Older deployments send only the `CiRepo` fields.\n */\nexport interface CiApiRepo extends CiRepo {\n pollIntervalSeconds: number;\n /** `disabled`: repo off; `never`: enabled but not polled yet; `scheduled`: `nextPollDueAt` is set. */\n pollSchedule: CiPollSchedule;\n nextPollDueAt: string | null;\n lastPollErrorAt: string | null;\n lastPollSucceededAt: string | null;\n lastChangeAt: string | null;\n /** Unarchived runs (reliability runs included), as the repository index counts them. */\n runs: { total: number; lastRunState: CiConclusion | null; lastRunQueuedAt: string | null };\n}\n\n/** `POST /api/v1/actions/repos/poll`: a poll that failed against the remote still answers with `error` set. */\nexport interface CiRepoPollResponse {\n fullName: string;\n repoId: string;\n polled: true;\n error: string | null;\n createdRunIds: string[];\n repo: CiApiRepo;\n}\n\n/** One ref of `GET /api/v1/actions/repos/branches`: a watched cursor, or run history alone. */\nexport interface CiBranch {\n /** Fully qualified: refs/heads/…, refs/pull/<n>/head, refs/tags/… */\n ref: string;\n prNumber: number | null;\n /** True while a live ref cursor polls the ref; false: run history only. */\n watched: boolean;\n runCount: number;\n /** \"\" when the ref has no run in view. */\n latestRunId: string;\n lastRunAt: string;\n}\n\nexport interface CiBranchesResponse {\n repo: string;\n defaultBranch: string;\n branches: CiBranch[];\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\n/** `POST /api/v1/actions/repos/sync`: per-account result plus the refreshed repo list. */\nexport interface CiRepoSyncResponse {\n accounts: Array<{ account: string; error: string | null }>;\n repos: Array<Pick<CiRepo, 'repoId' | 'fullName' | 'enabled' | 'private' | 'authType' | 'githubInstallationId'>>;\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\n/**\n * The CLI's platform client — `PlatformClient` plus the Actions-only\n * `org()` endpoint the dashboard URL builders need.\n */\nexport class ActionsClient extends PlatformClient {\n private orgPromise: Promise<ActionsOrg> | null = null;\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","/** Terminal-safe text and status labels shared by the `compute actions` modules. */\n\nimport pc from 'picocolors';\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\n/**\n * `safeTerm` for multi-line text (error messages, hints): newlines and tabs\n * stay, every other control character is replaced.\n */\nexport function safeTermText(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F]/g, '�');\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 // Anything else is the server's string verbatim.\n default: return safeTerm(conclusion);\n }\n}\n","/**\n * `compute sandboxes settings` / `compute actions settings` — one lane's\n * router. Routing is ComputeSDK's managed accounts: the default routing, or\n * the org's own managed order (`--routing`). BYOK is separate: whether the\n * org's own keys are used (`--byok off|first|fallback|only`) and in what\n * order (`--byok-order`), over `GET/PATCH /api/v1/{lane}/routing`. Sizes\n * and pools stay on `GET/PATCH /api/v1/{lane}/settings`. Keys themselves are\n * `compute byok`.\n *\n * `--cap`/`--general-cap` prices use the same parser as `--max-price` — a\n * unit is required (`0.12/hour`), so a bare dollar amount never silently\n * becomes per-second pricing.\n */\n\nimport { Command, Option } from 'commander';\nimport pc from 'picocolors';\nimport { ActionsApiError, ActionsCliError, type ActionsClient } from './actions-client.js';\n\nimport { safeTerm } from './term.js';\nimport type { CommonOpts } from './actions.js';\n\n/**\n * The helpers these commands need from `actions.js`, injected by the caller —\n * `actions.ts` imports this module, so a runtime import the other way would\n * create a cycle.\n */\nexport interface SettingsDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n usageErrorOutput: (str: string, write: (str: string) => void, argv?: string[]) => void;\n}\n\nexport const PLATFORM_SIZES = ['small', 'medium', 'large', 'xlarge', '2xlarge', '3xlarge'] as const;\n\ntype Rate = { usd: number; per: string };\n\n/** The settings GET/PATCH wire shape — fields shared by both lanes; the\n * `actions*` keys are the sandbox lane's inherit references. */\nexport interface LaneSettings {\n providerOrder: string[];\n actionsProviderOrder?: string[];\n marketCap?: Rate | null;\n actionsMarketCap?: Rate | null;\n marketOrderType?: 'market' | 'limit' | null;\n actionsMarketOrderType?: 'market' | 'limit';\n marketCaps?: Record<string, Rate | null>;\n referencePrices?: Record<string, Rate | null>;\n providerResources?: Record<\n string,\n { cpus?: number; memoryMb?: number; ephemeralDiskMb?: number }\n >;\n /** Preset name matching each providerResources entry, when one does. */\n providerResourcePresets?: Record<string, string | null>;\n warmPool?: Record<string, number>;\n snapshotPool?: Record<string, number>;\n /** Actions lane: the order an org with no providerOrder stored places on. */\n defaultProviderOrder?: string[];\n /** Actions lane: each provider's size presets, the names --resources takes. */\n sizePresets?: Record<string, { name: string; label: string }[]>;\n /** Actions lane: which workflows cap snapshots and which hold live ones. */\n snapshotSummary?: {\n workflows: { repoFullName: string; path: string; name: string; snapshotCap: number | null }[];\n live: { repoFullName: string; workflowPath: string | null; count: number }[];\n };\n}\n\n/**\n * `--max-price <usd>/<unit>` (and the `--cap`/`--general-cap` rates): the\n * unit is required — inline (`0.12/hour`) or via the `per` argument — so a\n * bare `--max-price 0.12` never silently defaults to per-second pricing.\n */\nexport function 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 'a unit is required — write it as <usd>/<unit> (e.g. 0.12/hour)',\n );\n }\n return { usd, per: unit };\n}\n\n/** One `<size>=<usd>/<unit>` or `<size>=none` `--cap` flag value. */\nfunction parseSizeCap(entry: string): { size: string; cap: Rate | null } {\n const eq = entry.indexOf('=');\n const size = eq === -1 ? entry : entry.slice(0, eq);\n if (!(PLATFORM_SIZES as readonly string[]).includes(size)) {\n throw new Error(\n `Invalid --cap \"${entry}\" — size must be one of ${PLATFORM_SIZES.join(', ')}.`,\n );\n }\n const value = eq === -1 ? '' : entry.slice(eq + 1);\n if (value === 'none') return { size, cap: null };\n const cap = parseMaxPrice(value, undefined);\n if (!cap) {\n throw new Error(\n `Invalid --cap \"${entry}\" — expected <size>=<usd>/<unit> (e.g. small=0.11/hour) or <size>=none.`,\n );\n }\n return { size, cap };\n}\n\n/** Mirrors MAX_WARM_POOL_SIZE in benchmarks-platform lib/providers/org-settings.ts. */\nexport const MAX_WARM_POOL_SIZE = 16;\n\n/** Mirrors MAX_SNAPSHOT_POOL_SIZE in benchmarks-platform lib/providers/org-settings.ts. */\nexport const MAX_SNAPSHOT_POOL_SIZE = 32;\n\n/** One `<provider>=<preset>` or `<provider>=none` `--resources` value; the server checks the names. */\nexport function parseResourcesFlag(entry: string): { provider: string; preset: string | null } {\n const eq = entry.indexOf('=');\n const provider = eq === -1 ? '' : entry.slice(0, eq).trim();\n const preset = eq === -1 ? '' : entry.slice(eq + 1).trim();\n if (provider === '' || preset === '') {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --resources \"${entry}\" — expected <provider>=<preset> (e.g. blaxel=large) or <provider>=none.`,\n );\n }\n return { provider, preset: preset === 'none' ? null : preset };\n}\n\n/** One `<provider[:region]>=<n>` pool-flag value, n in 0..max (0 clears the entry). */\nfunction parsePoolFlag(flag: string, entry: string, max: number): { key: string; size: number } {\n const eq = entry.indexOf('=');\n const key = eq === -1 ? '' : entry.slice(0, eq).trim();\n const value = eq === -1 ? '' : entry.slice(eq + 1).trim();\n const size = Number(value);\n if (key === '' || !/^\\d+$/.test(value) || size > max) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid ${flag} \"${entry}\" — expected <provider>[:<region>]=<n> with n in 0..${max} (0 clears it).`,\n );\n }\n return { key, size };\n}\n\n/** One `<provider[:region]>=<n>` `--warm-pool` value, n in 0..16 (0 clears the entry). */\nexport function parseWarmPoolFlag(entry: string): { key: string; size: number } {\n return parsePoolFlag('--warm-pool', entry, MAX_WARM_POOL_SIZE);\n}\n\n/** One `<provider[:region]>=<n>` `--snapshot-pool` value, n in 0..32 (0 clears the entry). */\nexport function parseSnapshotPoolFlag(entry: string): { key: string; size: number } {\n return parsePoolFlag('--snapshot-pool', entry, MAX_SNAPSHOT_POOL_SIZE);\n}\n\n/** Repeated pool flags as the settings patch: entry → size. */\nfunction poolPatch(entries: string[], parse: (entry: string) => { key: string; size: number }): Record<string, number> {\n const pool: Record<string, number> = {};\n for (const entry of entries) {\n const { key, size } = parse(entry);\n pool[key] = size;\n }\n return pool;\n}\n\nfunction formatResources(r: { cpus?: number; memoryMb?: number; ephemeralDiskMb?: number }): string {\n const parts: string[] = [];\n if (r.cpus !== undefined) parts.push(`${r.cpus} vCPU`);\n if (r.memoryMb !== undefined) parts.push(`${r.memoryMb} MB`);\n if (r.ephemeralDiskMb) parts.push(`${r.ephemeralDiskMb} MB disk`);\n return parts.join(' / ') || '—';\n}\n\nexport const BYOK_MODES = ['off', 'first', 'fallback', 'only'] as const;\nexport type ByokMode = (typeof BYOK_MODES)[number];\n\nconst BYOK_MODE_HELP: Record<ByokMode, string> = {\n off: \"not used: managed accounts only\",\n first: 'your keys first, then managed accounts',\n fallback: 'managed accounts first, then your keys',\n only: 'your keys only, never managed accounts',\n};\n\n/** How a router orders its managed accounts. */\nexport const MANAGED_STRATEGIES = ['computesdk', 'cheapest'] as const;\nexport type ManagedStrategy = (typeof MANAGED_STRATEGIES)[number] | 'custom';\n\nconst STRATEGY_LABEL: Record<ManagedStrategy, string> = {\n computesdk: 'ComputeSDK (recommended)',\n cheapest: 'Cheapest',\n custom: 'Custom',\n};\n\n/** `GET/PATCH /api/v1/{lane}/routing`. */\nexport interface LaneRouting {\n /** `computesdk` (the default), `cheapest` or `custom`; absent from older servers. */\n strategy?: ManagedStrategy;\n /** The org's own managed order when custom, else \"default\" (older servers: the only field). */\n routing: 'default' | string[];\n /** The managed accounts the router walks now, in order. */\n managed: string[];\n /** The size `managed` is ordered for (cheapest ranks by price at a size). */\n size?: string;\n /** Every live managed account a custom order may name. */\n available: string[];\n /** `order` is what placement uses; `inherits` (Sandboxes) says it comes from the Actions router. */\n byok: { mode: ByokMode; order: string[]; inherits?: boolean };\n}\n\nconst arrow = (list: string[]): string => list.join(' → ');\n\n/** The router: managed routing first (the default path), then BYOK. */\nexport function printLaneRouting(r: LaneRouting, lane: 'actions' | 'sandboxes'): void {\n const label = (text: string) => text.padEnd(12);\n const managed = r.managed.length > 0 ? arrow(r.managed) : pc.dim('no managed account is live');\n const strategy = r.strategy ?? (r.routing === 'default' ? 'computesdk' : 'custom');\n const size = r.size !== undefined && strategy === 'cheapest' ? pc.dim(` (priced at ${r.size})`) : '';\n console.log(`${label('Routing')}${STRATEGY_LABEL[strategy]}`);\n console.log(`${label('Order')}${managed}${size}`);\n console.log(`${label('BYOK')}${r.byok.mode} ${pc.dim(`(${BYOK_MODE_HELP[r.byok.mode]})`)}`);\n if (r.byok.mode !== 'off') {\n const list = r.byok.order.length > 0 ? arrow(r.byok.order) : '—';\n const order =\n lane === 'sandboxes' && r.byok.inherits === true\n ? `${list} ${pc.dim('(inherited from the Actions router)')}`\n : r.byok.order.length > 0\n ? list\n : pc.dim('none set — add keys with `compute byok configure`');\n console.log(`${label('BYOK order')}${order}`);\n }\n}\n\n/** Sizes and pools (the BYOK side's per-provider knobs). */\nexport function printLaneSettings(s: LaneSettings): void {\n const resources = Object.entries(s.providerResources ?? {});\n console.log('resources:');\n if (resources.length === 0) console.log(' —');\n for (const [provider, r] of resources) {\n const preset = s.providerResourcePresets?.[provider];\n console.log(preset ? ` ${provider} ${preset} (${formatResources(r)})` : ` ${provider} ${formatResources(r)}`);\n }\n const pool = Object.entries(s.warmPool ?? {});\n console.log('warm pool:');\n if (pool.length === 0) console.log(' —');\n for (const [entry, floor] of pool) console.log(` ${entry} ${floor}`);\n if (s.snapshotPool !== undefined) {\n const snap = Object.entries(s.snapshotPool);\n console.log('snapshot pool:');\n if (snap.length === 0) console.log(' —');\n for (const [entry, cap] of snap) console.log(` ${safeTerm(entry)} ${cap}`);\n }\n if (s.snapshotSummary !== undefined) printSnapshotSummary(s.snapshotSummary);\n}\n\n/** Workflows carrying their own snapshot cap, then the workflows holding live snapshots. */\nfunction printSnapshotSummary(summary: NonNullable<LaneSettings['snapshotSummary']>): void {\n const capped = summary.workflows.filter((w) => w.snapshotCap !== null);\n console.log('workflow snapshot caps:');\n if (capped.length === 0) console.log(` ${pc.dim('— (every workflow uses the dynamic pool)')}`);\n for (const w of capped) {\n const cap = w.snapshotCap === 0 ? 'off' : String(w.snapshotCap);\n console.log(` ${safeTerm(w.repoFullName)} ${safeTerm(w.path)} ${cap}`);\n }\n console.log('live snapshots:');\n if (summary.live.length === 0) console.log(' —');\n for (const row of summary.live) {\n console.log(` ${safeTerm(row.repoFullName)} ${row.workflowPath === null ? pc.dim('(no workflow)') : safeTerm(row.workflowPath)} ${row.count}`);\n }\n}\n\nfunction settingsFail(\n e: unknown,\n opts: CommonOpts,\n lane: string,\n verb: 'view' | 'change',\n deps: SettingsDeps,\n): never {\n if (e instanceof ActionsApiError && e.status === 403) {\n return deps.fail(\n new ActionsApiError(\n 403,\n `Only org owners/admins can ${verb} ${lane} settings`,\n e.body,\n ),\n opts,\n );\n }\n return deps.fail(e, opts);\n}\n\n/** A comma-separated provider list flag; empty is a usage error. */\nfunction providerList(flag: string, value: string): string[] {\n const list = value.split(',').map((entry) => entry.trim()).filter(Boolean);\n if (list.length === 0) throw new Error(`${flag} \"${value}\" names no providers — pass a comma-separated list.`);\n return list;\n}\n\n/**\n * Register `settings` / `settings set` on a lane's command group\n * (`compute sandboxes` or `compute actions`).\n */\nexport function registerSettingsCommands(\n group: Command,\n lane: 'actions' | 'sandboxes',\n common: (cmd: Command) => Command,\n deps: SettingsDeps,\n): void {\n const routerName = lane === 'sandboxes' ? 'Sandboxes' : 'Actions';\n const show = async (c: ActionsClient) => {\n const [routing, settings] = await Promise.all([\n c.get<LaneRouting>(`/api/v1/${lane}/routing`),\n c.get<LaneSettings>(`/api/v1/${lane}/settings`),\n ]);\n return { routing, settings };\n };\n const print = ({ routing, settings }: { routing: LaneRouting; settings: LaneSettings }) => {\n printLaneRouting(routing, lane);\n printLaneSettings(settings);\n };\n\n const settings = common(\n group\n .command('settings')\n .description(`Show the ${routerName} router: managed routing, BYOK use, sizes and pools`)\n .configureOutput({\n outputError: (str, write) => deps.usageErrorOutput(str, write),\n }),\n ).action(async (opts: CommonOpts) => {\n try {\n deps.output(opts, await show(await deps.client(opts)), print);\n } catch (e) {\n settingsFail(e, opts, lane, 'view', deps);\n }\n });\n\n const set = common(\n settings\n .command('set')\n .description(`Change the ${routerName} router (owner/admin)`)\n .option(\n '--routing <strategy|providers>',\n 'managed routing: computesdk (default) | cheapest | your own managed-account order (e.g. daytona,e2b)',\n )\n .option('--byok <mode>', `use your own keys: ${BYOK_MODES.join(' | ')}`)\n .option(\n '--byok-order <providers>',\n lane === 'sandboxes'\n ? 'your own providers in order (e.g. tensorlake,blaxel); \"inherit\" uses the Actions BYOK order'\n : 'your own providers in order (e.g. tensorlake,blaxel)',\n )\n // Pre-router spelling of --byok-order, kept for existing scripts.\n .addOption(new Option('--order <providers>').hideHelp()),\n );\n set\n .option(\n '--resources <provider=preset>',\n 'per-provider size preset (e.g. blaxel=large); <provider>=none clears it (repeatable)',\n (v, a: string[]) => a.concat(v),\n [] as string[],\n )\n .option(\n '--warm-pool <provider[:region]=n>',\n `warm pool size per BYOK entry, 0..${MAX_WARM_POOL_SIZE}; 0 clears it (repeatable)`,\n (v, a: string[]) => a.concat(v),\n [] as string[],\n );\n if (lane === 'actions') {\n set.option(\n '--snapshot-pool <provider[:region]=n>',\n `snapshot cap per BYOK entry, 0..${MAX_SNAPSHOT_POOL_SIZE}; 0 clears it (repeatable)`,\n (v, a: string[]) => a.concat(v),\n [] as string[],\n );\n }\n // Caps and order types price the compute market, which is not generally\n // available; accepted, but kept out of help.\n set\n .addOption(new Option('--cap <size=rate>').hideHelp().argParser((v, a: string[] = []) => a.concat(v)).default([]))\n .addOption(new Option('--general-cap <rate|none>').hideHelp())\n .addOption(new Option('--order-type <type>').hideHelp());\n\n set.action(async (opts: CommonOpts & {\n routing?: string;\n byok?: string;\n byokOrder?: string;\n order?: string;\n cap: string[];\n generalCap?: string;\n orderType?: string;\n resources?: string[];\n warmPool?: string[];\n snapshotPool?: string[];\n }) => {\n try {\n const routing: Record<string, unknown> = {};\n if (opts.routing !== undefined) {\n // \"default\" is the old name of computesdk; older servers only know it.\n routing.routing =\n opts.routing === 'default' || (MANAGED_STRATEGIES as readonly string[]).includes(opts.routing)\n ? opts.routing\n : providerList('--routing', opts.routing);\n }\n if (opts.byok !== undefined) {\n if (!(BYOK_MODES as readonly string[]).includes(opts.byok)) {\n throw new Error(`--byok must be one of ${BYOK_MODES.join(', ')}.`);\n }\n routing.byok = opts.byok;\n }\n if (opts.byokOrder !== undefined && opts.order !== undefined) {\n throw new Error('--order is the old name of --byok-order; pass one.');\n }\n const byokOrder = opts.byokOrder ?? opts.order;\n if (byokOrder !== undefined) {\n const flag = opts.byokOrder !== undefined ? '--byok-order' : '--order';\n routing.byokOrder =\n (byokOrder === 'inherit' && lane === 'sandboxes') || (byokOrder === 'default' && lane === 'actions')\n ? []\n : providerList(flag, byokOrder);\n }\n\n const settingsBody: Record<string, unknown> = {};\n if (opts.cap.length > 0) {\n const caps: Record<string, Rate | null> = {};\n for (const entry of opts.cap) {\n const { size, cap } = parseSizeCap(entry);\n caps[size] = cap;\n }\n settingsBody.marketCaps = caps;\n }\n if (opts.generalCap !== undefined) {\n settingsBody.marketCap = opts.generalCap === 'none' ? null : parseMaxPrice(opts.generalCap, undefined);\n }\n if (opts.orderType !== undefined) {\n if (lane === 'sandboxes' && opts.orderType === 'inherit') {\n settingsBody.marketOrderType = null;\n } else if (opts.orderType === 'limit' || opts.orderType === 'market') {\n settingsBody.marketOrderType = opts.orderType;\n } else {\n throw new Error('--order-type must be limit or market.');\n }\n }\n if (opts.resources && opts.resources.length > 0) {\n const resources: Record<string, string | null> = {};\n for (const entry of opts.resources) {\n const { provider, preset } = parseResourcesFlag(entry);\n resources[provider] = preset;\n }\n settingsBody.providerResources = resources;\n }\n if (opts.warmPool && opts.warmPool.length > 0) {\n settingsBody.warmPool = poolPatch(opts.warmPool, parseWarmPoolFlag);\n }\n if (opts.snapshotPool && opts.snapshotPool.length > 0) {\n settingsBody.snapshotPool = poolPatch(opts.snapshotPool, parseSnapshotPoolFlag);\n }\n // The router and the sizes/pools are two endpoints; one command never\n // half-applies, so it changes one or the other.\n if (Object.keys(routing).length > 0 && Object.keys(settingsBody).length > 0) {\n throw new Error(\n 'Change routing (--routing, --byok, --byok-order) and sizes or pools in separate commands.',\n );\n }\n if (Object.keys(routing).length === 0 && Object.keys(settingsBody).length === 0) {\n throw new Error(\n lane === 'sandboxes'\n ? 'Nothing to change — pass --routing, --byok, --byok-order, --resources, or --warm-pool.'\n : 'Nothing to change — pass --routing, --byok, --byok-order, --resources, --warm-pool, or --snapshot-pool.',\n );\n }\n const c = await deps.client(opts);\n if (Object.keys(routing).length > 0) await c.patch<LaneRouting>(`/api/v1/${lane}/routing`, routing);\n if (Object.keys(settingsBody).length > 0) await c.patch<LaneSettings>(`/api/v1/${lane}/settings`, settingsBody);\n deps.output(opts, await show(c), print);\n } catch (e) {\n settingsFail(e, opts, lane, 'change', deps);\n }\n });\n}\n","/**\n * Confirmation for CLI writes that hide, remove or change shared state.\n * `-y/--yes` skips it; an interactive terminal is asked; anything else\n * (scripts, agents, CI) is refused with a hint, so a write never happens\n * because nobody was there to say no.\n */\n\nimport { createInterface } from 'node:readline/promises';\nimport { ActionsCliError } from './actions-client.js';\n\n/**\n * Resolve when the write may go ahead. Throws `confirmation_required` when\n * stdin is not a TTY and `--yes` was not passed, and `cancelled` when the\n * prompt is answered with anything but y/yes.\n */\nexport async function confirmWrite(question: string, opts: { yes?: boolean }): Promise<void> {\n if (opts.yes) return;\n if (!process.stdin.isTTY) {\n throw new ActionsCliError('confirmation_required', `${question} Pass -y to confirm.`);\n }\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n let answer: string;\n try {\n answer = await rl.question(`${question} [y/N] `);\n } finally {\n rl.close();\n }\n if (!/^y(es)?$/i.test(answer.trim())) {\n throw new ActionsCliError('cancelled', 'Cancelled; nothing was changed.');\n }\n}\n","/**\n * `compute actions runs …` — the run list and its views over the v1 run\n * routes: the newest-100 window (`GET /api/v1/actions/runs`), one day's runs\n * page by page (`/runs/day/{day}`), the per-day index (`/run-days`), and\n * archive/unarchive (`POST /runs/archive`). Every view takes the same\n * filters, which map one-to-one onto the v1 query.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport {\n ActionsApiError,\n ActionsCliError,\n type ActionsClient,\n type CiRun,\n type CiRunArchiveResponse,\n type CiRunDay,\n type CiRunsCursor,\n type CiRunsPage,\n type CiWorkflow,\n} from './actions-client.js';\nimport type { CommonOpts } from './actions.js';\nimport { confirmWrite } from './confirm.js';\nimport { safeTerm } from './term.js';\n\n/** Injected by `actions.ts`, which imports this module (a runtime import back would be a cycle). */\nexport interface RunsDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n formatRunRow: (run: CiRun) => string;\n}\n\nexport interface RunFilterOpts {\n status?: string[];\n branch?: string[];\n event?: string[];\n workflow?: string[];\n search?: string;\n archived?: boolean;\n reliability?: boolean;\n}\n\ntype RunsOpts = CommonOpts & RunFilterOpts & { day?: string; timeZone?: string; cursor?: string; all?: boolean };\ntype Query = Record<string, string | string[] | undefined>;\n\n/** Selectors starting here are workflow file paths and go to the API as is. */\nconst WORKFLOW_PATH_PREFIX = '.github/';\n\nfunction plural(n: number, noun: string): string {\n return `${n} ${noun}${n === 1 ? '' : 's'}`;\n}\n\n/**\n * `--workflow` selectors → workflow file paths, matched against the catalog\n * by path, then name, then file name (`ci.yml`), then id. A name can match\n * workflows in several repos; each distinct path is kept once.\n */\nexport function resolveWorkflowPaths(workflows: CiWorkflow[], selectors: string[]): string[] {\n const paths: string[] = [];\n for (const selector of selectors) {\n const matchers: ((w: CiWorkflow) => boolean)[] = [\n (w) => w.path === selector,\n (w) => w.name === selector,\n (w) => w.path.split('/').pop() === selector,\n (w) => w.id === selector,\n ];\n let found: CiWorkflow[] = [];\n for (const matches of matchers) {\n found = workflows.filter(matches);\n if (found.length > 0) break;\n }\n if (found.length === 0) {\n const choices = [...new Set(workflows.map((w) => `${w.path} (${w.name})`))].join(', ') || 'none';\n throw new ActionsCliError('workflow_not_found', `No workflow \"${selector}\". Available: ${choices}`);\n }\n for (const w of found) if (!paths.includes(w.path)) paths.push(w.path);\n }\n return paths;\n}\n\n/** The v1 run-filter query for the flags; reads the workflow catalog only to resolve names. */\nasync function runFilterQuery(c: ActionsClient, repo: string | undefined, opts: RunFilterOpts): Promise<Query> {\n let workflow: string[] | undefined;\n if (opts.workflow && opts.workflow.length > 0) {\n const lookups = opts.workflow.filter((s) => !s.startsWith(WORKFLOW_PATH_PREFIX));\n const catalog =\n lookups.length === 0\n ? []\n : (await c.get<{ workflows: CiWorkflow[] }>('/api/v1/actions/workflows', { repo, include: 'all' })).workflows;\n workflow = [];\n for (const selector of opts.workflow) {\n const paths = selector.startsWith(WORKFLOW_PATH_PREFIX) ? [selector] : resolveWorkflowPaths(catalog, [selector]);\n for (const path of paths) if (!workflow.includes(path)) workflow.push(path);\n }\n }\n return {\n repo,\n status: opts.status,\n branch: opts.branch,\n event: opts.event,\n workflow,\n q: opts.search,\n archived: opts.archived ? 'only' : undefined,\n reliability: opts.reliability ? '1' : undefined,\n };\n}\n\n/** `--cursor <startedAt>,<id>`, the form printed after a day page. */\nexport function parseDayCursor(value: string): CiRunsCursor {\n const comma = value.lastIndexOf(',');\n if (comma <= 0 || comma === value.length - 1) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --cursor \"${value}\". Expected <startedAt>,<id>, as printed after a page.`,\n );\n }\n return { startedAt: value.slice(0, comma), id: value.slice(comma + 1) };\n}\n\n/** One page of a day's runs, or with `all` every page from `cursor` on, merged. */\nasync function listDayRuns(\n c: ActionsClient,\n day: string,\n query: Query,\n { all, cursor }: { all: boolean; cursor?: CiRunsCursor },\n): Promise<CiRunsPage & { nextCursor: CiRunsCursor | null }> {\n const runs: CiRun[] = [];\n const seen = new Set<string>();\n let next: CiRunsCursor | null = cursor ?? null;\n for (;;) {\n const page: CiRunsPage = await c.get<CiRunsPage>(`/api/v1/actions/runs/day/${encodeURIComponent(day)}`, {\n ...query,\n cursorStartedAt: next?.startedAt,\n cursorId: next?.id,\n });\n runs.push(...page.runs);\n next = page.nextCursor ?? null;\n if (!all || next === null) return { runs, nextCursor: next };\n const key = `${next.startedAt},${next.id}`;\n if (seen.has(key)) throw new ActionsCliError('invalid_argument', `The platform repeated cursor ${key}; stopping.`);\n seen.add(key);\n }\n}\n\nexport function formatRunDays(days: CiRunDay[]): string {\n if (days.length === 0) return 'No runs found.';\n return days.map((d) => `${safeTerm(d.day)} ${plural(d.count, 'run')}`).join('\\n');\n}\n\n/** The hint after a day page: the `--cursor` that continues it. */\nexport function formatDayCursor(cursor: { startedAt: string; id: string }): string {\n return `more: --cursor ${safeTerm(cursor.startedAt)},${safeTerm(cursor.id)}`;\n}\n\nfunction archiveQuestion(count: number, archived: boolean): string {\n return archived\n ? `Archive ${plural(count, 'run')}? Archived runs leave the run lists and counts; \\`compute actions runs unarchive\\` restores them.`\n : `Unarchive ${plural(count, 'run')}? They return to the run lists and counts.`;\n}\n\n/** The ids a 400 from `POST /runs/archive` reported as unknown or another org's. */\nfunction notFoundIds(error: unknown): string[] {\n if (!(error instanceof ActionsApiError)) return [];\n const ids = error.details?.notFound;\n return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === 'string') : [];\n}\n\nexport function registerRunsCommands(\n actions: Command,\n common: (cmd: Command) => Command,\n deps: RunsDeps,\n): void {\n const withFilters = (cmd: Command) =>\n cmd\n .option('--status <status...>', 'filter by conclusion: passed, failed, running, cancelled, none')\n .option('--branch <branch...>', 'filter by branch/ref')\n .option('--event <event...>', 'filter by trigger: push, pull_request, schedule, workflow_dispatch')\n .option('--workflow <path|name...>', 'filter by workflow path, name or file name (e.g. ci.yml)')\n .option('--search <text>', 'search title, ref, SHA prefix, workflow, #run or #PR number')\n .option('--archived', 'archived runs only (hidden by default)')\n .option('--reliability', 'reliability runs only (hidden by default)');\n\n const printRuns = (runs: CiRun[]) => {\n if (runs.length === 0) {\n console.log('No runs found.');\n return;\n }\n for (const run of runs) console.log(deps.formatRunRow(run));\n };\n\n const runs = actions\n .command('runs')\n .description('List recent runs (every repo, or one), or one day\\'s runs with --day');\n common(\n withFilters(runs.argument('[repo]', 'repository in owner/repo format (default: every repo)'))\n .option('--day <YYYY-MM-DD>', 'list one day\\'s runs, page by page, instead of the newest 100')\n .option('--time-zone <iana>', 'with --day: the time zone the day is read in (default: UTC)')\n .option('--cursor <startedAt,id>', 'with --day: continue after this cursor (printed after a page)')\n .option('--all', 'with --day: follow every page'),\n ).action(async (repo: string | undefined, opts: RunsOpts) => {\n try {\n if (opts.day === undefined && (opts.all || opts.timeZone !== undefined || opts.cursor !== undefined)) {\n throw new ActionsCliError('invalid_argument', '--all, --time-zone and --cursor page one day\\'s runs: pass --day <YYYY-MM-DD>.');\n }\n const cursor = opts.cursor === undefined ? undefined : parseDayCursor(opts.cursor);\n const c = await deps.client(opts);\n const query = await runFilterQuery(c, repo, opts);\n if (opts.day !== undefined) {\n const page = await listDayRuns(c, opts.day, { ...query, timeZone: opts.timeZone }, { all: opts.all === true, cursor });\n deps.output(opts, page, (p) => {\n printRuns(p.runs);\n if (p.nextCursor) console.log(pc.dim(formatDayCursor(p.nextCursor)));\n });\n return;\n }\n const { runs: list } = await c.get<{ runs: CiRun[] }>('/api/v1/actions/runs', query);\n deps.output(opts, list, printRuns);\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n\n common(\n withFilters(\n runs\n .command('days')\n .description('How many runs each day holds, newest first (same filters as runs)')\n .argument('[repo]', 'repository in owner/repo format (default: every repo)'),\n ).option('--time-zone <iana>', 'the time zone days are read in (default: UTC)'),\n ).action(async (repo: string | undefined, opts: CommonOpts & RunFilterOpts & { timeZone?: string }) => {\n try {\n const c = await deps.client(opts);\n const query = await runFilterQuery(c, repo, opts);\n const data = await c.get<{ days: CiRunDay[] }>('/api/v1/actions/run-days', { ...query, timeZone: opts.timeZone });\n deps.output(opts, data, (d) => console.log(formatRunDays(d.days)));\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n\n for (const archived of [true, false]) {\n const verb = archived ? 'archive' : 'unarchive';\n common(\n runs\n .command(verb)\n .description(\n archived\n ? 'Archive runs: hide them from run lists and counts, still reachable by id (owner/admin)'\n : 'Restore archived runs to the run lists (owner/admin)',\n )\n .argument('<run-id...>', 'run IDs')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (runIds: string[], opts: CommonOpts & { yes?: boolean }) => {\n try {\n await confirmWrite(archiveQuestion(runIds.length, archived), opts);\n const result = await (await deps.client(opts)).post<CiRunArchiveResponse>('/api/v1/actions/runs/archive', {\n runIds,\n archived,\n });\n deps.output(opts, result, (r) => console.log(`${verb}d ${plural(r.archived, 'run')}`));\n } catch (e) {\n const missing = notFoundIds(e);\n if (!opts.json && missing.length > 0 && e instanceof ActionsApiError) {\n deps.fail(new ActionsApiError(e.status, `${e.message} — not found: ${missing.join(', ')}`, e.body), opts);\n }\n deps.fail(e, opts);\n }\n });\n }\n}\n","/**\n * `compute actions workflows …` — the workflow catalog and its per-workflow\n * controls over `GET`/`PATCH /api/v1/actions/workflows`: the runnable list,\n * every workflow with `--all` (user-disabled ones and those on disabled\n * repos), the files only a branch or tag has with `--ref`, and\n * enable/disable/set for the on/off switch, placement order and snapshot cap.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport {\n ActionsCliError,\n type ActionsClient,\n type CiRefOnlyWorkflow,\n type CiWorkflowControls,\n type CiWorkflowInput,\n type CiWorkflowListItem,\n type CiWorkflowsResponse,\n} from './actions-client.js';\nimport type { CommonOpts } from './actions.js';\nimport { resolveWorkflowPaths } from './actions-runs.js';\nimport { confirmWrite } from './confirm.js';\nimport { conclusionLabel, safeTerm } from './term.js';\n\n/** Injected by `actions.ts`, which imports this module (a runtime import back would be a cycle). */\nexport interface WorkflowsDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n}\n\ntype ListOpts = CommonOpts & { all?: boolean; ref?: string };\ntype WriteOpts = CommonOpts & { yes?: boolean };\ntype SetOpts = WriteOpts & {\n order?: string;\n inheritOrder?: boolean;\n snapshotCap?: string;\n dynamicSnapshots?: boolean;\n};\ntype Controls = { enabled?: boolean; providerOrder?: string[] | null; snapshotCap?: number | null };\n\nexport function formatAgo(iso: string, now: number = Date.now()): string {\n const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000));\n if (s < 60) return `${s}s ago`;\n const m = Math.floor(s / 60);\n if (m < 60) return `${m}m ago`;\n const h = Math.floor(m / 60);\n if (h < 48) return `${h}h ago`;\n return `${Math.floor(h / 24)}d ago`;\n}\n\nfunction orderText(order: string[] | null | undefined): string {\n return order && order.length > 0 ? order.map(safeTerm).join(',') : 'inherits';\n}\n\nfunction snapshotText(cap: number | null | undefined): string {\n if (cap === null || cap === undefined) return 'dynamic';\n return cap === 0 ? 'off' : String(cap);\n}\n\n/** `target* (required), suite default=dax` — dispatch inputs as `--inputs` needs them. */\nexport function formatWorkflowInputs(inputs: CiWorkflowInput[]): string {\n return inputs\n .map((i) => {\n const name = safeTerm(i.name);\n if (i.required) return `${name}* (required)`;\n return i.default !== '' ? `${name} default=${safeTerm(i.default)}` : name;\n })\n .join(', ');\n}\n\nfunction stateLabel(w: CiWorkflowListItem): string {\n if (w.repoEnabled === false) return pc.gray('○ repo disabled');\n if (w.enabled === false || w.userDisabledAt) return pc.gray('○ disabled (user)');\n return pc.green('● enabled');\n}\n\nexport function formatWorkflowRow(w: CiWorkflowListItem, now: number = Date.now()): string {\n const last = w.lastRun ? `${conclusionLabel(w.lastRun.conclusion)} ${formatAgo(w.lastRun.queuedAt, now)}` : 'never';\n const inputs = formatWorkflowInputs(w.inputs ?? []);\n return [\n stateLabel(w),\n pc.dim(safeTerm(w.repoFullName)),\n `${safeTerm(w.path)} (${safeTerm(w.name)})`,\n `order: ${orderText(w.providerOrder)}`,\n `snapshots: ${snapshotText(w.snapshotCap)}`,\n `last: ${last}`,\n ...(inputs ? [pc.dim(`inputs: ${inputs}`)] : []),\n ].join(' ');\n}\n\nexport function formatRefOnlyRow(w: CiRefOnlyWorkflow): string {\n const inputs = formatWorkflowInputs(w.inputs);\n return [\n pc.cyan('◇ ref-only'),\n `${safeTerm(w.path)} (${safeTerm(w.name)})`,\n w.dispatchable\n ? inputs\n ? `inputs: ${inputs}`\n : pc.dim('no inputs')\n : pc.dim('push-only: dispatch with --manual'),\n ].join(' ');\n}\n\n/**\n * Match a dispatch `--workflow` against the files only the ref has: an exact\n * path first, then the name. A name two files share is refused with their\n * paths rather than guessed, as the control commands do.\n */\nexport function matchRefOnly(refOnly: CiRefOnlyWorkflow[], selector: string): CiRefOnlyWorkflow | undefined {\n const byPath = refOnly.find((w) => w.path === selector);\n if (byPath) return byPath;\n const byName = refOnly.filter((w) => w.name === selector);\n if (byName.length > 1) {\n throw new ActionsCliError(\n 'invalid_argument',\n `\"${selector}\" matches ${byName.length} workflows only on this ref: ${byName.map((w) => safeTerm(w.path)).join(', ')}. Pass the path.`,\n );\n }\n return byName[0];\n}\n\n/** `path (name)` choices for a not-found message. */\nexport function workflowChoices(workflows: { path: string; name: string }[]): string {\n return [...new Set(workflows.map((w) => `${w.path} (${w.name})`))].join(', ') || 'none';\n}\n\n/**\n * The path a control command's `<workflow>` names in `repo`, matched against\n * the full catalog (disabled workflows included) by path, name, file name or\n * id. A name shared by two files is refused rather than guessed.\n */\nexport function resolveControlTarget(catalog: CiWorkflowListItem[], repo: string, selector: string): string {\n const inRepo = catalog.filter((w) => w.repoFullName === repo);\n let paths: string[];\n try {\n paths = resolveWorkflowPaths(inRepo, [selector]);\n } catch (e) {\n if (e instanceof ActionsCliError && e.code === 'workflow_not_found') {\n throw new ActionsCliError('workflow_not_found', `No workflow \"${selector}\" in ${repo}. Available: ${workflowChoices(inRepo)}`);\n }\n throw e;\n }\n if (paths.length > 1) {\n throw new ActionsCliError(\n 'invalid_argument',\n `\"${selector}\" matches ${paths.length} workflows in ${repo}: ${paths.join(', ')}. Pass the path.`,\n );\n }\n return paths[0];\n}\n\n/** `set`'s flags → the PATCH controls; refuses conflicting, malformed or empty input. */\nexport function setControls(opts: SetOpts): Controls {\n const controls: Controls = {};\n if (opts.order !== undefined && opts.inheritOrder) {\n throw new ActionsCliError('invalid_argument', 'Pass --order or --inherit-order, not both.');\n }\n if (opts.snapshotCap !== undefined && opts.dynamicSnapshots) {\n throw new ActionsCliError('invalid_argument', 'Pass --snapshot-cap or --dynamic-snapshots, not both.');\n }\n if (opts.inheritOrder) controls.providerOrder = null;\n if (opts.order !== undefined) {\n const order = opts.order.split(',').map((s) => s.trim()).filter(Boolean);\n if (order.length === 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--order \"${opts.order}\" names no providers — pass a comma-separated list, or --inherit-order.`,\n );\n }\n controls.providerOrder = order;\n }\n if (opts.dynamicSnapshots) controls.snapshotCap = null;\n if (opts.snapshotCap !== undefined) {\n if (!/^\\d+$/.test(opts.snapshotCap.trim())) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --snapshot-cap \"${opts.snapshotCap}\". Expected a whole number (0 turns snapshots off), or --dynamic-snapshots.`,\n );\n }\n controls.snapshotCap = Number(opts.snapshotCap.trim());\n }\n if (Object.keys(controls).length === 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Nothing to change — pass --order, --inherit-order, --snapshot-cap or --dynamic-snapshots.',\n );\n }\n return controls;\n}\n\nfunction describeControls(c: Controls): string {\n const parts: string[] = [];\n if (c.providerOrder !== undefined) parts.push(`order: ${orderText(c.providerOrder)}`);\n if (c.snapshotCap !== undefined) parts.push(`snapshots: ${snapshotText(c.snapshotCap)}`);\n return parts.join(', ');\n}\n\nfunction formatControlsResult(verb: string, r: CiWorkflowControls): string {\n const detail =\n verb === 'set'\n ? ` order: ${orderText(r.providerOrder)} snapshots: ${snapshotText(r.snapshotCap)}`\n : '';\n return `${verb} ${pc.cyan(safeTerm(r.repoFullName))} ${safeTerm(r.path)}${detail}`;\n}\n\nexport function registerWorkflowsCommands(\n actions: Command,\n common: (cmd: Command) => Command,\n deps: WorkflowsDeps,\n): void {\n const workflows = actions\n .command('workflows')\n .description('List workflows with their controls (every repo, or one); --all adds disabled ones, --ref the files only a branch has');\n common(\n workflows\n .argument('[repo]', 'repository in owner/repo format (default: every repo)')\n .option('--all', 'include user-disabled workflows and workflows on disabled repos')\n .option('--ref <ref>', 'with a repo: also list the workflow files only this branch or tag has (dispatchable by path)'),\n ).action(async (repo: string | undefined, opts: ListOpts) => {\n try {\n if (opts.ref !== undefined && repo === undefined) {\n throw new ActionsCliError('invalid_argument', '--ref needs a repo: compute actions workflows <owner/repo> --ref <ref>.');\n }\n const c = await deps.client(opts);\n const data = await c.get<CiWorkflowsResponse>('/api/v1/actions/workflows', {\n repo,\n include: opts.all ? 'all' : undefined,\n ref: opts.ref,\n });\n deps.output(opts, data, (d) => {\n if (d.workflows.length === 0 && (d.refOnly ?? []).length === 0) {\n console.log('No workflows found.');\n return;\n }\n for (const w of d.workflows) console.log(formatWorkflowRow(w));\n if (opts.ref !== undefined) {\n const refOnly = d.refOnly ?? [];\n console.log(pc.dim(refOnly.length === 0 ? `only on ${safeTerm(opts.ref)}: none` : `only on ${safeTerm(opts.ref)}:`));\n for (const w of refOnly) console.log(formatRefOnlyRow(w));\n }\n });\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n\n /** Confirm, resolve `<workflow>` against `?include=all`, then PATCH repo + path with `controls`. */\n async function writeControls(\n repo: string,\n selector: string,\n controls: Controls,\n question: string,\n verb: string,\n opts: WriteOpts,\n ): Promise<void> {\n await confirmWrite(question, opts);\n const c = await deps.client(opts);\n const { workflows: catalog } = await c.get<CiWorkflowsResponse>('/api/v1/actions/workflows', {\n repo,\n include: 'all',\n });\n const path = resolveControlTarget(catalog, repo, selector);\n const result = await c.patch<CiWorkflowControls>('/api/v1/actions/workflows', {\n repoFullName: repo,\n path,\n ...controls,\n });\n deps.output(opts, result, (r) => console.log(formatControlsResult(verb, r)));\n }\n\n for (const enabled of [true, false]) {\n const verb = enabled ? 'enable' : 'disable';\n common(\n workflows\n .command(verb)\n .description(\n enabled\n ? 'Turn a workflow back on (owner/admin)'\n : 'Turn a workflow off: no pushes, schedules or dispatches run it until enabled (owner/admin)',\n )\n .argument('<repo>', 'repository in owner/repo format')\n .argument('<workflow>', 'workflow path, name, file name (ci.yml) or id')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (repo: string, selector: string, opts: WriteOpts) => {\n try {\n const question = enabled\n ? `Enable workflow \"${selector}\" in ${repo}? It runs again on its triggers.`\n : `Disable workflow \"${selector}\" in ${repo}? Pushes, schedules and dispatches stop running it until it is enabled.`;\n await writeControls(repo, selector, { enabled }, question, `${verb}d`, opts);\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n }\n\n common(\n workflows\n .command('set')\n .description('Set a workflow\\'s provider order and snapshot cap (owner/admin)')\n .argument('<repo>', 'repository in owner/repo format')\n .argument('<workflow>', 'workflow path, name, file name (ci.yml) or id')\n .option('--order <providers>', 'this workflow walks exactly these BYOK providers instead of the Actions router (e.g. e2b,blaxel)')\n .option('--inherit-order', 'drop the workflow\\'s order: it follows the Actions router')\n .option('--snapshot-cap <n>', 'most snapshots this workflow keeps (0 turns them off)')\n .option('--dynamic-snapshots', 'drop the cap: the workflow uses the dynamic snapshot pool')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (repo: string, selector: string, opts: SetOpts) => {\n try {\n const controls = setControls(opts);\n await writeControls(\n repo,\n selector,\n controls,\n `Change workflow \"${selector}\" in ${repo} (${describeControls(controls)})?`,\n 'set',\n opts,\n );\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n}\n","/**\n * `compute actions repos …` and `compute actions branches` — the org's\n * repositories over `/api/v1/actions/repos*`: the list with run counts and\n * poll state, connect/sync/enable/disable, poll-now (`/repos/poll`, at most\n * every 30 s, shared with the dashboard), the fork pull request setting, and\n * a repo's refs (`/repos/branches`).\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { readFileSync } from 'fs';\nimport {\n ActionsApiError,\n ActionsCliError,\n type ActionsClient,\n type CiApiRepo,\n type CiBranch,\n type CiBranchesResponse,\n type CiRepoConnectResponse,\n type CiRepoPatchResponse,\n type CiRepoPollResponse,\n type CiRepoSyncResponse,\n type CiReposResponse,\n} from './actions-client.js';\nimport type { CommonOpts } from './actions.js';\nimport { formatAgo } from './actions-workflows.js';\nimport { confirmWrite } from './confirm.js';\nimport { conclusionLabel, safeTerm } from './term.js';\n\n/** Injected by `actions.ts`, which imports this module (a runtime import back would be a cycle). */\nexport interface ReposDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n}\n\ntype RepoIdOpts = CommonOpts & { repoId?: string };\ntype WriteOpts = RepoIdOpts & { yes?: boolean };\n\nconst FORK_PRS: Record<string, boolean> = { allow: true, refuse: false };\n\nfunction plural(n: number, noun: string): string {\n return `${n} ${noun}${n === 1 ? '' : 's'}`;\n}\n\n/** `in 25s` / `in 2m` / `in 3h` / `in 2d` — the countdown twin of `formatAgo`. */\nexport function formatIn(iso: string, now: number = Date.now()): string {\n const s = Math.max(0, Math.round((Date.parse(iso) - now) / 1000));\n if (s < 60) return `in ${s}s`;\n const m = Math.round(s / 60);\n if (m < 60) return `in ${m}m`;\n const h = Math.round(m / 60);\n if (h < 48) return `in ${h}h`;\n return `in ${Math.round(h / 24)}d`;\n}\n\n/** `not polled yet` / `next poll in 2m` / `poll due`; nothing for a disabled repo. */\nfunction pollText(r: Partial<CiApiRepo>, now: number): string | null {\n if (!r.enabled) return null;\n if (r.pollSchedule === 'never') return 'not polled yet';\n if (!r.nextPollDueAt) return null;\n return Date.parse(r.nextPollDueAt) <= now ? 'poll due' : `next poll ${formatIn(r.nextPollDueAt, now)}`;\n}\n\n/**\n * `enabled acme/widgets github-app · main · 2 workflows · 5 runs · last passed 3h ago · next poll in 2m`.\n * The run and poll parts are left out when the platform predates them.\n */\nexport function formatRepoRow(r: CiApiRepo, now: number = Date.now()): 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 parts = [\n safeTerm(via),\n safeTerm(r.defaultBranch),\n r.workflowPaths.length > 0 ? plural(r.workflowPaths.length, 'workflow') : 'no workflows yet',\n ];\n if (r.runs) {\n parts.push(plural(r.runs.total, 'run'));\n if (r.runs.lastRunState && r.runs.lastRunQueuedAt) {\n parts.push(`last ${conclusionLabel(r.runs.lastRunState)} ${formatAgo(r.runs.lastRunQueuedAt, now)}`);\n }\n }\n const poll = pollText(r, now);\n if (poll) parts.push(poll);\n if (r.forkPullRequests) parts.push('fork PRs on');\n const error = r.lastPollError ? pc.red(` poll error: ${safeTerm(r.lastPollError)}`) : '';\n return `${head} ${safeTerm(r.fullName)} ${pc.dim(parts.join(' · '))}${error}`;\n}\n\n/** `refs/pull/482/head PR #482 watched 3 runs last 2h ago <run-id>`. */\nexport function formatBranchRow(b: CiBranch, now: number = Date.now(), defaultBranch?: string): string {\n const isDefault = defaultBranch !== undefined && b.ref === `refs/heads/${defaultBranch}`;\n const at = Number.isNaN(Date.parse(b.lastRunAt)) ? null : formatAgo(b.lastRunAt, now);\n return [\n safeTerm(b.ref) + (isDefault ? pc.dim(' (default)') : ''),\n ...(b.prNumber !== null ? [`PR #${b.prNumber}`] : []),\n b.watched ? pc.green('watched') : pc.dim('history only'),\n plural(b.runCount, 'run'),\n ...(at ? [b.runCount > 0 ? `last ${at}` : pc.dim(`moved ${at}`)] : []),\n ...(b.latestRunId ? [pc.dim(safeTerm(b.latestRunId))] : []),\n ].join(' ');\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/** A 429 from `/repos/poll` with its `nextAllowedAt` folded into the message. */\nfunction withRetryAfter(error: unknown): unknown {\n if (!(error instanceof ActionsApiError) || error.status !== 429) return error;\n const next = error.details?.nextAllowedAt;\n if (typeof next !== 'string') return error;\n const rewritten = new ActionsApiError(error.status, `${error.message}; retry after ${next} (${formatIn(next)})`, error.body);\n rewritten.retryAfterMs = error.retryAfterMs;\n return rewritten;\n}\n\n/** `--fork-prs` → `forkPullRequests`; anything but allow/refuse is refused before any request. */\nexport function parseForkPrs(value: string): boolean {\n if (!Object.prototype.hasOwnProperty.call(FORK_PRS, value)) {\n throw new ActionsCliError('invalid_argument', `Invalid --fork-prs \"${value}\". Expected allow or refuse.`);\n }\n return FORK_PRS[value];\n}\n\nconst repoIdBody = (opts: RepoIdOpts) => (opts.repoId !== undefined ? { repoId: opts.repoId } : {});\nconst REPO_ID_HELP = 'scope to one row when two installations grant the same name';\n\nexport function registerReposCommands(\n actions: Command,\n common: (cmd: Command) => Command,\n deps: ReposDeps,\n): void {\n const { client, output, fail } = deps;\n\n const repos = actions\n .command('repos')\n .description('List the org\\'s connected repositories: run counts, last run and next poll');\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 if (d.repos.length === 0) {\n console.log('No repositories connected.');\n return;\n }\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('sync')\n .description('Re-read the GitHub App installation so repos granted after install show up (owner/admin key)'),\n ).action(async (opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<CiRepoSyncResponse>('/api/v1/actions/repos/sync', {});\n output(opts, result, (r) => {\n for (const a of r.accounts) {\n console.log(a.error === null ? `synced ${pc.cyan(safeTerm(a.account))}` : `failed ${pc.cyan(safeTerm(a.account))} ${pc.red(safeTerm(a.error))}`);\n }\n console.log(pc.dim(`${r.repos.length} repos visible`));\n });\n if (result.accounts.some((a) => a.error !== null)) process.exitCode = 1;\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>', REPO_ID_HELP),\n ).action(async (repo: string, opts: RepoIdOpts) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: true,\n ...repoIdBody(opts),\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>', REPO_ID_HELP),\n ).action(async (repo: string, opts: RepoIdOpts) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: false,\n ...repoIdBody(opts),\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 common(\n repos\n .command('poll')\n .description('Poll a repo now: fetch its refs and start the runs new commits call for (owner/admin; at most every 30 s)')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--repo-id <id>', REPO_ID_HELP)\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (repo: string, opts: WriteOpts) => {\n try {\n await confirmWrite(`Poll ${repo} now? New commits on its watched refs start the runs their workflows call for.`, opts);\n const c = await client(opts);\n let result: CiRepoPollResponse;\n try {\n result = await c.post<CiRepoPollResponse>('/api/v1/actions/repos/poll', { fullName: repo, ...repoIdBody(opts) });\n } catch (e) {\n throw withRetryAfter(e);\n }\n output(opts, result, (r) => {\n console.log(`polled ${pc.cyan(safeTerm(r.fullName))} ${plural(r.createdRunIds.length, 'run')} started`);\n if (r.error) console.log(pc.red(`poll error: ${safeTerm(r.error)}`));\n });\n // The platform answers 200 for a poll the remote refused; the error is the outcome.\n if (result.error) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('set')\n .description('Change a repo\\'s settings: whether pull requests from forks run CI (owner/admin)')\n .argument('<repo>', 'repository in owner/repo format')\n .requiredOption('--fork-prs <allow|refuse>', 'run pull requests from forks (isolated: no org secrets, no GitHub token), or refuse them')\n .option('--repo-id <id>', REPO_ID_HELP)\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (repo: string, opts: WriteOpts & { forkPrs: string }) => {\n try {\n const forkPullRequests = parseForkPrs(opts.forkPrs);\n await confirmWrite(\n forkPullRequests\n ? `Run pull requests from forks on ${repo}? They run isolated: no org secrets, no GitHub token, and the base branch's workflow definition.`\n : `Refuse pull requests from forks on ${repo}? Fork pull requests stop running CI.`,\n opts,\n );\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n forkPullRequests,\n ...repoIdBody(opts),\n });\n output(opts, result, (r) =>\n console.log(`fork PRs ${r.forkPullRequests === false ? 'refused' : 'allowed'} ${pc.cyan(safeTerm(r.fullName))}`),\n );\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('branches')\n .description('List a repo\\'s refs: watched branches and pull requests, then refs with run history only')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--search <text>', 'only refs containing this text (case-insensitive)')\n .option('--archived', 'count archived runs instead of active ones')\n .option('--repo-id <id>', REPO_ID_HELP),\n ).action(async (repo: string, opts: RepoIdOpts & { search?: string; archived?: boolean }) => {\n try {\n const data = await (await client(opts)).get<CiBranchesResponse>('/api/v1/actions/repos/branches', {\n repo,\n repoId: opts.repoId,\n q: opts.search,\n archived: opts.archived ? '1' : undefined,\n });\n output(opts, data, (d) => {\n console.log(`${pc.bold(safeTerm(d.repo))} ${pc.dim(`default: ${safeTerm(d.defaultBranch)}`)}`);\n if (d.branches.length === 0) {\n console.log('No branches found.');\n return;\n }\n const now = Date.now();\n for (const b of d.branches) console.log(formatBranchRow(b, now, d.defaultBranch));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * `compute actions installations …` and `compute actions slack …` — the org's\n * connected integrations over `/api/v1/actions/installations*` and\n * `/api/v1/actions/slack*`: the GitHub App installations (account, repo\n * selection and counts, suspension) and the Slack connection (workspace,\n * channel, notify rule, daily brief), plus where an owner/admin starts a new\n * install. Reads only: installing is a browser step the platform signs for\n * the signed-in user, so `install-url` prints the page to open, never a\n * signed install link.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport type {\n ActionsClient,\n CiInstallation,\n CiInstallationsResponse,\n CiInstallLink,\n CiSlackConnection,\n} from './actions-client.js';\nimport type { CommonOpts } from './actions.js';\nimport { safeTerm } from './term.js';\n\n/** Injected by `actions.ts`, which imports this module (a runtime import back would be a cycle). */\nexport interface IntegrationsDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n}\n\nexport function formatInstallationRow(i: CiInstallation): string {\n const head = i.suspended ? pc.yellow(safeTerm(i.account)) : pc.cyan(safeTerm(i.account));\n const parts = [\n i.accountType ? safeTerm(i.accountType) : 'account',\n i.repoSelection === 'all' ? 'all repos' : 'selected repos',\n `${i.repos.granted} granted, ${i.repos.enabled} enabled`,\n ...(i.suspended ? [pc.yellow(`suspended ${safeTerm(i.suspendedAt ?? '')}`.trim())] : []),\n pc.dim(`installed ${safeTerm(i.installedAt)}`),\n ];\n return `${head} ${parts.join(' ')}`;\n}\n\nexport function formatInstallations(data: CiInstallationsResponse): string[] {\n if (data.installations.length === 0) {\n return ['No GitHub App installations. Run `compute actions installations install-url` for where to install it.'];\n }\n const lines: string[] = [];\n for (const i of data.installations) {\n lines.push(formatInstallationRow(i));\n if (i.configureUrl) lines.push(` ${pc.dim(`configure: ${safeTerm(i.configureUrl)}`)}`);\n }\n return lines;\n}\n\nexport function formatSlack(s: CiSlackConnection): string[] {\n if (!s.installed) {\n return ['Slack is not connected. Run `compute actions slack install-url` for where to connect it.'];\n }\n const channel = s.channelId\n ? `${s.channelName ? `#${safeTerm(s.channelName)} ` : ''}${pc.dim(safeTerm(s.channelId))}`\n : pc.gray('no channel picked');\n const brief = s.brief.enabled\n ? `${s.brief.times.map(safeTerm).join(', ')} ${safeTerm(s.brief.timeZone)}${s.brief.categories.length > 0 ? ` categories: ${s.brief.categories.map(safeTerm).join(', ')}` : ''}`\n : pc.gray('off');\n return [\n `workspace: ${s.teamName ? safeTerm(s.teamName) : pc.gray('(unnamed)')}`,\n `channel: ${channel}`,\n `notify on: ${s.notifyOn === 'failure' ? 'failures and cancels' : 'every conclusion'}`,\n `daily brief: ${brief}`,\n ];\n}\n\nexport function formatInstallLink(link: CiInstallLink, what: 'github' | 'slack'): string[] {\n if (!link.configured || link.url === null) {\n return [what === 'github' ? 'This deployment has no GitHub App configured.' : 'This deployment has no Slack app configured.'];\n }\n return [\n safeTerm(link.url),\n pc.dim(\n what === 'github'\n ? 'Open it signed in as an org owner/admin and press Install GitHub App.'\n : 'Open it in a browser signed in as an org owner/admin; it continues to Slack.',\n ),\n ];\n}\n\nexport function registerIntegrationsCommands(\n actions: Command,\n common: (cmd: Command) => Command,\n deps: IntegrationsDeps,\n): void {\n const { client, output, fail } = deps;\n const print = (lines: string[]) => {\n for (const line of lines) console.log(line);\n };\n\n const installations = common(\n actions\n .command('installations')\n .description('List the org\\'s GitHub App installations (account, repo selection and counts, suspension)'),\n ).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiInstallationsResponse>('/api/v1/actions/installations');\n output(opts, data, (d) => print(formatInstallations(d)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n installations\n .command('install-url')\n .description('Print where an owner/admin installs the GitHub App into another account'),\n ).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiInstallLink>('/api/v1/actions/installations/install-url');\n output(opts, data, (d) => print(formatInstallLink(d, 'github')));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const slack = common(\n actions\n .command('slack')\n .description('Show the org\\'s Slack connection (workspace, channel, notify rule, daily brief; owner/admin)'),\n ).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiSlackConnection>('/api/v1/actions/slack');\n output(opts, data, (d) => print(formatSlack(d)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n slack\n .command('install-url')\n .description('Print where an owner/admin connects a Slack workspace'),\n ).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiInstallLink>('/api/v1/actions/slack/install-url');\n output(opts, data, (d) => print(formatInstallLink(d, 'slack')));\n } catch (e) {\n fail(e, opts);\n }\n });\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, Option } from 'commander';\nimport pc from 'picocolors';\nimport { mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { spawnSync } from 'child_process';\nimport { registerSettingsCommands } from './settings.js';\nimport { registerReposCommands } from './actions-repos.js';\nimport { registerIntegrationsCommands } from './actions-integrations.js';\nimport { registerRunsCommands } from './actions-runs.js';\nimport { matchRefOnly, registerWorkflowsCommands, workflowChoices } from './actions-workflows.js';\nimport { conclusionLabel, safeTerm, safeTermText } from './term.js';\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 CiRun,\n type CiRunBenchmarkProvider,\n type CiRunBenchmarkResult,\n type CiRunHistory,\n type CiRunInspection,\n type CiRunSummary,\n type CiSchedule,\n type CiVaultDeleteResponse,\n type CiVaultItem,\n type CiVaultKind,\n type CiVaultListResponse,\n type CiVaultRevealResponse,\n type CiVaultSaveResponse,\n type CiRefOnlyWorkflow,\n type CiWorkflow,\n type CiWorkflowsResponse,\n} from './actions-client.js';\n\nexport { conclusionLabel, safeTerm };\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\ninterface ScheduleOpts extends CommonOpts {\n reliability?: boolean;\n from?: string;\n to?: string;\n repo?: string;\n workflow?: string[];\n event?: string[];\n status?: string[];\n tz?: string;\n limit?: string;\n cursor?: string;\n}\n\nfunction scheduleQuery(opts: ScheduleOpts): Record<string, string | string[] | undefined> {\n const from = opts.from === undefined ? new Date() : new Date(opts.from);\n const to = opts.to === undefined ? new Date(from.getTime() + 7 * 86_400_000) : new Date(opts.to);\n if (!Number.isFinite(from.getTime()) || !Number.isFinite(to.getTime())) {\n throw new ActionsCliError('invalid_argument', '--from and --to must be valid timestamps.');\n }\n return {\n from: from.toISOString(), to: to.toISOString(),\n repo: opts.repo, workflow: opts.workflow, event: opts.event, status: opts.status,\n reliability: opts.reliability ? '1' : undefined,\n timeZone: opts.tz ?? Intl.DateTimeFormat().resolvedOptions().timeZone,\n limit: opts.limit, cursor: opts.cursor,\n };\n}\n\nfunction nextScheduleCommand(data: CiSchedule, opts: ScheduleOpts): string {\n const args = ['compute', 'actions', 'schedule', '--from', data.from, '--to', data.to, '--tz', data.timeZone];\n for (const key of ['repo', 'workflow', 'event', 'status', 'limit', 'org', 'baseUrl'] as const) {\n const value = opts[key];\n if (value === undefined) continue;\n for (const item of Array.isArray(value) ? value : [value]) args.push(`--${key === 'baseUrl' ? 'base-url' : key}`, item);\n }\n if (opts.reliability) args.push('--reliability');\n if (opts.allowUntrustedHost) args.push('--allow-untrusted-host');\n args.push('--cursor', data.nextCursor!);\n return args.map((value) => /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replace(/'/g, \"'\\\\''\")}'`).join(' ');\n}\n\nexport function formatSchedule(data: CiSchedule, nextCommand?: string): string {\n const time = new Intl.DateTimeFormat('en-CA', {\n timeZone: data.timeZone, year: 'numeric', month: '2-digit', day: '2-digit',\n hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23', timeZoneName: 'short',\n });\n const lines = [pc.bold(`Upcoming fires (${safeTerm(data.timeZone)})`)];\n const fires = data.upcoming.flatMap((schedule) => schedule.occurrences.map((at) => ({ at, schedule })))\n .sort((a, b) => a.at.localeCompare(b.at));\n if (fires.length === 0) lines.push('No upcoming fires.');\n for (const { at, schedule } of fires) {\n lines.push([time.format(new Date(at)), safeTerm(schedule.workflowName || schedule.workflowPath), safeTerm(schedule.repoFullName), safeTerm(schedule.description)].join(' '));\n }\n for (const schedule of data.upcoming) {\n const remaining = schedule.occurrenceCount - schedule.occurrences.length;\n if (remaining > 0) lines.push(`+${remaining.toLocaleString('en-US')} more scheduled for ${safeTerm(schedule.workflowName || schedule.workflowPath)} ${safeTerm(schedule.repoFullName)} ${safeTerm(schedule.description)}`);\n }\n lines.push('', pc.bold(`Past runs (${safeTerm(data.timeZone)})`));\n if (data.runs.length === 0) lines.push('No past runs found.');\n for (const run of data.runs) {\n lines.push([\n time.format(new Date(run.startedAt ?? run.createdAt)), safeTerm(run.workflowName || run.workflowPath),\n safeTerm(run.repoFullName), safeTerm(run.event), conclusionLabel(safeTerm(run.status === 'completed' ? run.conclusion : run.status)),\n ].join(' '));\n }\n if (data.countsTruncated) lines.push('Warning: some schedule totals reached the safety limit; use a smaller window for exact counts.');\n if (nextCommand) lines.push('', `Next page (reuse the same credentials):\\n${safeTerm(nextCommand)}`);\n return lines.join('\\n');\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 // The message is the server's, or quotes server values: no control sequences.\n console.error(pc.red(`Error (${error.status}): ${safeTermText(error.message)}`));\n } else {\n console.error(pc.red(`Error: ${safeTermText(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 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 ...(run.archivedAt ? [pc.dim('archived')] : []),\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.benchmarks && run.benchmarks.length > 0) lines.push(`benchmarks: ${resultsSummary(run.benchmarks)}`);\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/** One-line digest: `sandbox-cpu · 26 providers · 13 failed`. */\nexport function resultsSummary(results: CiRunBenchmarkResult[]): string {\n return results\n .map((r) => {\n const rows = overallRows(r);\n if (rows.length === 0) return `${safeTerm(r.benchmarkSlug)} (${safeTerm(r.status)}, no results yet)`;\n const failed = rows.filter((p) => !p.skipped && p.successRate !== null && p.successRate < 1).length;\n return `${safeTerm(r.benchmarkSlug)} · ${rows.length} providers${failed > 0 ? ` · ${failed} failed` : ''}`;\n })\n .join('; ');\n}\n\n/**\n * The runner reports one overall row per provider (`dimensions: {}`) plus one\n * per dimension (e.g. phase). The table shows one row per provider — its\n * overall row, or its best dimension row when it has no overall; `--json` has all.\n */\nfunction overallRows(result: CiRunBenchmarkResult): CiRunBenchmarkProvider[] {\n const byProvider = new Map<string, CiRunBenchmarkProvider>();\n for (const p of result.providers) {\n const cur = byProvider.get(p.provider);\n const isOverall = Object.keys(p.dimensions).length === 0;\n const curIsOverall = cur ? Object.keys(cur.dimensions).length === 0 : false;\n if (!cur || (isOverall && !curIsOverall) || (!curIsOverall && (p.compositeScore ?? -1) > (cur.compositeScore ?? -1))) {\n byProvider.set(p.provider, p);\n }\n }\n return Array.from(byProvider.values());\n}\n\nfunction formatScore(n: number | null): string {\n return n === null ? '-' : n.toFixed(2);\n}\n\nfunction formatMetric(n: number): string {\n return Number.isInteger(n) ? String(n) : n.toFixed(Math.abs(n) >= 100 ? 1 : 2);\n}\n\nfunction formatRate(n: number | null): string {\n return n === null ? '-' : `${Math.round(n * 100)}%`;\n}\n\n/** `compute actions benchmarks` — per-provider score table for each linked benchmark run. */\nexport function formatRunResults(results: CiRunBenchmarkResult[]): string {\n if (results.length === 0) return pc.dim('no benchmark results on this run');\n const lines: string[] = [];\n for (const [i, result] of results.entries()) {\n if (i > 0) lines.push('');\n lines.push(`${pc.bold(safeTerm(result.benchmarkName))} ${safeTerm(result.status)}`);\n lines.push(pc.dim(`${safeTerm(result.benchmarkRunId)} ${safeTerm(result.dashboardUrl)}`));\n const rows = [...overallRows(result)].sort((a, b) => (b.compositeScore ?? -1) - (a.compositeScore ?? -1));\n if (rows.length === 0) {\n lines.push(pc.dim(result.status === 'failed' ? ' failed before reporting results' : ' no results yet'));\n continue;\n }\n const width = Math.max(8, ...rows.map((p) => p.provider.length));\n lines.push(pc.dim(` ${'provider'.padEnd(width)} ${'score'.padStart(7)} ${'success'.padStart(7)} metrics`));\n for (const p of rows) {\n const metrics = Object.entries(p.metrics)\n .map(([name, m]) => `${safeTerm(name)} ${formatMetric(m.median)}${m.unit ? safeTerm(m.unit) : ''}`)\n .join(' ');\n const status = p.skipped ? pc.dim(`skipped${p.skipReason ? `: ${safeTerm(p.skipReason)}` : ''}`) : metrics;\n lines.push(` ${safeTerm(p.provider).padEnd(width)} ${formatScore(p.compositeScore).padStart(7)} ${formatRate(p.successRate).padStart(7)} ${status}`);\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\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\n/** A stored key's verification state: `connected …abcd`, `error (detail)`, `unconfigured`. */\nfunction keyStatusText(p: CiProviderInfo): string {\n const status = p.status === 'connected' ? pc.green('connected') : p.status === 'error' ? pc.red('error') : pc.gray('unconfigured');\n const hint = p.keyHint ? ` ${pc.dim(safeTerm(p.keyHint))}` : '';\n const detail = p.status === 'error' && p.statusDetail ? ` ${pc.dim(`(${safeTerm(p.statusDetail)})`)}` : '';\n return `${status}${hint}${detail}`;\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 ...(p.credential !== 'ambient' && p.status !== undefined ? [keyStatusText(p)] : []),\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\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 */\n/**\n * A workflow with no catalog row yet — a file the dispatched diff creates, or\n * one only the dispatched ref has — so it is addressed by path. `dispatchable`\n * is known only for a ref-only file; a diff's file is left to the platform.\n */\nexport type PatchedWorkflowTarget = { repoFullName: string; workflowPath: string; dispatchable?: boolean };\n\nexport function isPatchedWorkflowTarget(target: CiWorkflow | PatchedWorkflowTarget): target is PatchedWorkflowTarget {\n return 'workflowPath' in target;\n}\n\n/**\n * True when a unified diff creates or edits `path`: a `+++ b/<path>` header.\n * Git tab-terminates the header when the path contains whitespace and quotes\n * it (`+++ \"b/<path>\"`) for non-ASCII bytes under core.quotePath.\n */\nexport function patchTouches(patch: string, path: string): boolean {\n const plain = `+++ b/${path}`;\n const quoted = `+++ \"b/${path}\"`;\n return patch.split('\\n').some((line) => {\n const header = line.replace(/\\t.*$/, '');\n return header === plain || header === quoted;\n });\n}\n\nexport function dispatchBody(\n workflow: CiWorkflow | PatchedWorkflowTarget,\n opts: {\n ref?: string;\n inputs?: string[];\n manual?: boolean;\n provider?: string;\n providerRegion?: string;\n maxBid?: string;\n maxBidPer?: string;\n /** An uploaded diff (`POST /api/v1/actions/patches`) to run on top of the ref's head. */\n patchId?: string;\n },\n): Record<string, unknown> {\n const patched = isPatchedWorkflowTarget(workflow);\n const path = patched ? workflow.workflowPath : workflow.path;\n const pushOnly = workflow.dispatchable === false;\n if (pushOnly && !opts.manual) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${path}\" does not declare workflow_dispatch. Pass --manual to run it anyway (no inputs).`,\n );\n }\n if (pushOnly && opts.inputs !== undefined && opts.inputs.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${path}\" has no workflow_dispatch inputs; --manual runs of it take no --inputs.`,\n );\n }\n const ref = opts.ref ?? (patched ? undefined : 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 ...(patched ? { repoFullName: workflow.repoFullName, workflowPath: workflow.workflowPath } : { 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 ...(opts.patchId !== undefined && { patchId: opts.patchId }),\n };\n}\n\nexport type GitRunner = (args: string[]) => { status: number | null; stdout: string; stderr: string };\n\nconst runGit: GitRunner = (args) => {\n const r = spawnSync('git', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });\n return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };\n};\n\n/** True when a git remote URL (https or ssh, with or without `.git`) names `owner/repo`. */\nexport function remoteNamesRepo(remote: string, repo: string): boolean {\n const normalized = remote.trim().replace(/\\.git$/, '').replace(/\\/+$/, '');\n return normalized.toLowerCase().endsWith(`/${repo.toLowerCase()}`) || normalized.toLowerCase().endsWith(`:${repo.toLowerCase()}`);\n}\n\n/** The checked-out branch, or null outside a git repo / on a detached HEAD. */\nexport function currentBranch(git: GitRunner = runGit): string | null {\n const r = git(['rev-parse', '--abbrev-ref', 'HEAD']);\n if (r.status !== 0) return null;\n const name = r.stdout.trim();\n return name === '' || name === 'HEAD' ? null : name;\n}\n\n/** True when the working tree has uncommitted or untracked changes; false outside a repo. */\nexport function hasLocalChanges(git: GitRunner = runGit): boolean {\n const r = git(['status', '--porcelain', '--untracked-files=all']);\n return r.status === 0 && r.stdout.trim() !== '';\n}\n\n/**\n * `--with-changes`: everything the working tree has that the remote ref does\n * not — local commits past `origin/<ref>`, uncommitted edits, and untracked\n * files — as one unified diff against `origin/<ref>`. That is the commit the\n * platform resolves the ref to, so the diff applies exactly. Null when there\n * is nothing to send.\n */\nexport function localChangesPatch(\n ref: string,\n git: GitRunner = runGit,\n repo?: string,\n): { patch: string; files: number; base: string } | null {\n const branch = ref.replace(/^refs\\/heads\\//, '');\n const base = `origin/${branch}`;\n if (repo !== undefined) {\n const remote = git(['remote', 'get-url', 'origin']).stdout.trim();\n if (!remoteNamesRepo(remote, repo)) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--with-changes sends this checkout's changes, but its origin (${remote || 'none'}) is not ${repo}. Run it from a checkout of ${repo}.`,\n );\n }\n }\n // The platform resolves the ref on the remote, so the diff must be against\n // the remote's current head, not whatever origin/<branch> was last fetched as.\n const fetched = git(['fetch', '--quiet', 'origin', branch]);\n if (fetched.status !== 0) {\n throw new ActionsCliError('invalid_argument', `git fetch origin ${branch} failed: ${fetched.stderr.trim() || 'is the branch pushed?'}`);\n }\n if (git(['rev-parse', '--verify', '--quiet', `${base}^{commit}`]).status !== 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--with-changes diffs against ${base}, which does not exist locally. Push the branch (or run \\`git fetch origin ${branch}\\`), or pass --ref <branch that exists on origin>.`,\n );\n }\n const tracked = git(['diff', '--no-color', '--no-ext-diff', '--src-prefix=a/', '--dst-prefix=b/', base, '--']);\n if (tracked.status !== 0) {\n throw new ActionsCliError('invalid_argument', `git diff against ${base} failed: ${tracked.stderr.trim()}`);\n }\n const parts = [tracked.stdout];\n // Untracked files must be diffed from the repo root: `ls-files --others`\n // lists only the cwd's subtree and `diff --no-index` emits cwd-relative\n // paths, so from a subdirectory the patch would drop or misplace files.\n const topLevel = git(['rev-parse', '--show-toplevel']).stdout.replace(/\\r?\\n$/, '');\n const untracked = git(['-C', topLevel, 'ls-files', '--others', '--exclude-standard', '-z']);\n for (const file of untracked.stdout.split('\\0').filter((f) => f !== '')) {\n // --no-index exits 1 when the files differ, which is the expected case.\n const d = git(['-C', topLevel, 'diff', '--no-color', '--no-ext-diff', '--no-index', '--src-prefix=a/', '--dst-prefix=b/', '--', '/dev/null', file]);\n if (d.stdout !== '') parts.push(d.stdout);\n }\n const patch = parts.filter((p) => p !== '').join('');\n if (patch.trim() === '') return null;\n if (patch.includes('\\0') || /^Binary files .* differ$/m.test(patch)) {\n throw new ActionsCliError('invalid_argument', 'Local changes include a binary file; --with-changes sends text diffs only.');\n }\n const files = patch.match(/^\\+\\+\\+ /gm)?.length ?? 0;\n return { patch, files, base };\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\n/**\n * The label set a delivery choice becomes — `hosts:` rules for proxied,\n * `materialize` for injected. `vault set` and `vault delivery` share it so\n * both surfaces write identical labels.\n */\nexport function vaultDeliveryLabels(opts: {\n proxy?: boolean;\n inject?: boolean;\n hosts?: string[];\n}): string[] {\n if (opts.proxy && opts.inject) {\n throw new ActionsCliError('invalid_argument', '--proxy and --inject are mutually exclusive.');\n }\n const hosts = (opts.hosts ?? [])\n .flatMap((host) => host.split(/[\\s,]+/))\n .map((host) => host.trim().toLowerCase())\n .filter((host) => host !== '');\n if (opts.inject) {\n if (hosts.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n '--inject takes no --hosts — host rules only apply to --proxy.',\n );\n }\n return ['materialize'];\n }\n if (!opts.proxy) {\n throw new ActionsCliError('invalid_argument', 'Pick a delivery: --proxy (with --hosts) or --inject.');\n }\n if (hosts.length === 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n '--proxy needs --hosts — the hosts the real value may be attached to.',\n );\n }\n return [`hosts:${hosts.join(',')}`];\n}\n\n/** `vault set`'s labels: the delivery sugar, or raw --labels — never both. */\nexport function vaultSetLabels(opts: {\n labels?: string[];\n proxy?: boolean;\n inject?: boolean;\n hosts?: string[];\n}): string[] | undefined {\n const flagged = opts.proxy === true || opts.inject === true || (opts.hosts?.length ?? 0) > 0;\n if (flagged && (opts.labels?.length ?? 0) > 0) {\n throw new ActionsCliError('invalid_argument', 'Use --labels or --proxy/--inject --hosts, not both.');\n }\n if (!flagged) return opts.labels;\n return vaultDeliveryLabels(opts);\n}\n\nexport function formatVaultRow(item: CiVaultItem): string {\n const flags = [\n item.kind,\n ...(item.revealable && item.kind === 'secret' ? ['revealable'] : []),\n ...item.labels.map(safeTerm),\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); also finds a workflow file only this ref has')\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 Actions router')\n .option('--provider-region <region>', 'region for --provider (same as --provider <id>:<region>)')\n .addOption(new Option('--max-bid <usd>').hideHelp())\n .addOption(new Option('--max-bid-per <unit>').hideHelp())\n .option('--with-changes', 'run your local changes: everything the working tree has beyond origin/<ref> is sent as a diff and applied after checkout (default --ref: the current branch)'),\n ).action(async (repo: string, opts: CommonOpts & { workflow: string; ref?: string; inputs?: string[]; manual?: boolean; provider?: string; providerRegion?: string; maxBid?: string; maxBidPer?: string; withChanges?: boolean }) => {\n try {\n const c = await client(opts);\n let ref = opts.ref;\n let local: ReturnType<typeof localChangesPatch> = null;\n if (opts.withChanges) {\n ref ??= currentBranch() ?? undefined;\n if (!ref) throw new ActionsCliError('invalid_argument', '--with-changes needs a branch: check one out or pass --ref.');\n local = localChangesPatch(ref, undefined, repo);\n } else if (!opts.json && hasLocalChanges()) {\n console.error(pc.dim('You have uncommitted changes. Add --with-changes to run them.'));\n }\n const { workflows } = await c.get<{ workflows: CiWorkflow[] }>(\n '/api/v1/actions/workflows',\n { repo },\n );\n // A workflow file the diff creates has no catalog row yet; the platform\n // builds the run's definition from the diff when addressed by path.\n let workflow: CiWorkflow | PatchedWorkflowTarget | undefined =\n matchWorkflow(workflows, opts.workflow) ??\n (local && patchTouches(local.patch, opts.workflow) ? { repoFullName: repo, workflowPath: opts.workflow } : undefined);\n // A file only the ref has is not in the catalog either; it dispatches by path.\n let refOnly: CiRefOnlyWorkflow[] | undefined;\n if (!workflow && ref !== undefined) {\n refOnly = (await c.get<CiWorkflowsResponse>('/api/v1/actions/workflows', { repo, ref })).refOnly ?? [];\n const match = matchRefOnly(refOnly, opts.workflow);\n if (match) workflow = { repoFullName: repo, workflowPath: match.path, dispatchable: match.dispatchable };\n }\n if (!workflow) {\n const choices =\n workflowChoices(workflows) +\n (refOnly && refOnly.length > 0 ? `; only on ${ref}: ${workflowChoices(refOnly)}` : '');\n const hint =\n !opts.withChanges && hasLocalChanges() && /^\\.github\\/workflows\\//.test(opts.workflow)\n ? ' If it only exists in your working tree, add --with-changes.'\n : '';\n throw new ActionsCliError(\n 'workflow_not_found',\n `No workflow \"${opts.workflow}\" in ${repo}. Available: ${choices}${hint}`,\n );\n }\n let patch: { patchId: string; files: number; bytes: number } | undefined;\n if (local) {\n const uploaded = await c.postText<{ patchId: string; sha256: string; bytes: number; files: number }>(\n '/api/v1/actions/patches',\n local.patch,\n 'text/x-patch; charset=utf-8',\n );\n patch = { patchId: uploaded.patchId, files: uploaded.files, bytes: uploaded.bytes };\n } else if (opts.withChanges && !opts.json && ref) {\n console.error(pc.dim(`no local changes beyond origin/${ref.replace(/^refs\\/heads\\//, '')}; running the ref as is`));\n }\n const body = dispatchBody(workflow, { ...opts, ref, patchId: patch?.patchId });\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, ...(patch && { patch }) }, (r) => {\n console.log(`${r.created ? 'dispatched' : 'already running'} ${pc.cyan(r.runId)}`);\n console.log(`sha: ${r.headSha}${r.patch ? ` + ${r.patch.files} changed file${r.patch.files === 1 ? '' : 's'} (uncommitted)` : ''}`);\n console.log(`url: ${r.url}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n registerRunsCommands(actions, common, { client, fail, output, formatRunRow });\n registerWorkflowsCommands(actions, common, { client, fail, output });\n\n common(\n actions\n .command('schedule')\n .description('List upcoming scheduled fires and past runs in a time window')\n .option('--reliability', 'show only reliability runs and workflows (hidden by default)')\n .option('--from <timestamp>', 'inclusive start timestamp (default: now)')\n .option('--to <timestamp>', 'exclusive end timestamp (default: seven days after --from)')\n .option('--repo <repo>', 'repository in owner/repo format')\n .option('--workflow <path...>', 'workflow file paths; repeatable')\n .option('--event <event...>', 'trigger events: schedule, push, pull_request, workflow_dispatch')\n .option('--status <status...>', 'run conclusions: passed, failed, running, cancelled, none (excludes upcoming)')\n .option('--tz <zone>', 'IANA time zone (default: local)')\n .option('--limit <n>', 'past-run page size (default 100, max 500)')\n .option('--cursor <cursor>', 'nextCursor from a prior page; keep the window and filters unchanged'),\n ).action(async (opts: ScheduleOpts) => {\n opts.org ??= program.opts<CommonOpts>().org;\n try {\n const query = scheduleQuery(opts);\n const data = await (await client(opts)).get<CiSchedule>('/api/v1/actions/schedule', query);\n output(opts, data, (result) => console.log(formatSchedule(result, result.nextCursor ? nextScheduleCommand(result, opts) : undefined)));\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('benchmarks')\n .description('Show the benchmark runs this run produced: per-provider score and success rate')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const run = await (await client(opts)).get<CiRun>(`/api/v1/actions/runs/${runId}`);\n const benchmarks = run.benchmarks ?? [];\n output(opts, { runId: run.id, conclusion: run.conclusion, benchmarks }, () => console.log(formatRunResults(benchmarks)));\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 providers Actions can place on (order, act/usable, key status); keys and rates: compute byok');\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 // configure/verify/remove predate `compute byok` and stay on the\n // /api/v1/actions/providers aliases, which keep the actions OAuth scopes, so\n // logins made before the providers scopes existed keep working.\n common(\n providers\n .command('configure')\n .description('Deprecated: use `compute byok configure`. Save the org\\'s credential for a provider (owner/admin)')\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 // A provider key is a local secret: trusted hosts only, even with --allow-untrusted-host.\n const c = await secretValueClient(opts, 'provider keys');\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('Deprecated: use `compute byok verify`. Probe the stored provider key with a real sandbox')\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('Deprecated: use `compute byok remove`. 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 registerReposCommands(actions, common, { client, fail, output });\n registerIntegrationsCommands(actions, common, { client, fail, output });\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 .option('--proxy', 'hand the job a placeholder; the value is attached to requests for --hosts at egress')\n .option('--inject', 'inject the real value into the job environment (the default)')\n .option('--hosts <hosts...>', 'hosts the proxied value may be attached to (comma or space separated, *.example.com covers subdomains)'),\n ).action(async (name: string, opts: VaultOpts & { fromFile?: string; revealable?: boolean; description?: string; labels?: string[]; proxy?: boolean; inject?: boolean; hosts?: 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 labels = vaultSetLabels(opts);\n const body = vaultSetBody(name, value, { ...opts, kind, labels });\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('delivery')\n .description('Reclassify how a secret reaches a job — labels only, no value needed')\n .argument('<name>', 'item name')\n .option('--proxy', 'hand the job a placeholder; the value is attached to requests for --hosts at egress')\n .option('--inject', 'inject the real value into the job environment')\n .option('--hosts <hosts...>', 'hosts the proxied value may be attached to (comma or space separated, *.example.com covers subdomains)'),\n ).action(async (name: string, opts: VaultOpts & { proxy?: boolean; inject?: boolean; hosts?: string[] }) => {\n try {\n const kind = parseVaultKind(opts.kind);\n const labels = vaultDeliveryLabels(opts);\n const result = await (await client(opts)).patch<CiVaultSaveResponse>(\n vaultPath('/api/v1/vault', { repo: opts.repo }),\n { name, kind, labels },\n );\n output(opts, result, (r) => {\n const where = opts.repo ? safeTerm(opts.repo) : 'org';\n console.log(\n `reclassified ${pc.cyan(safeTerm(r.item.name))} ${pc.dim(`(labels: ${r.item.labels.join(', ') || 'none'}, v${r.item.version}, ${where})`)}`,\n );\n });\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 registerSettingsCommands(actions, 'actions', common, {\n client,\n fail,\n output,\n usageErrorOutput,\n });\n}\n","import { ActionsCliError, type ActionsClient } from './actions-client.js';\nimport { output, type CommonOpts } from './actions.js';\nimport type { CommandResult, SandboxProcess, SandboxProcessStatus } from '@computesdk/platform';\n\n/** A single argument is a shell program; multiple arguments preserve argv. */\nexport function execCommand(args: string[]): string {\n return args.length === 1 ? args[0] : args.map((arg) => `'${arg.replace(/'/g, `'\\\\''`)}'`).join(' ');\n}\n\nexport interface ExecOpts extends CommonOpts {\n cwd?: string;\n env?: string[];\n timeout?: string;\n timeoutMs?: string;\n detach?: boolean;\n stream?: boolean;\n}\n\n// The buffered command endpoint has a 300s route lifetime and reserves 10s.\nconst BUFFERED_MAX_MS = 290_000;\n\nexport function execTimeout(opts: ExecOpts): number | undefined {\n if (opts.detach && (opts.stream || opts.timeout !== undefined || opts.timeoutMs !== undefined)) {\n throw new ActionsCliError('invalid_argument', '--detach cannot be combined with --stream or a command timeout.');\n }\n if (opts.timeout !== undefined && opts.timeoutMs !== undefined) {\n throw new ActionsCliError('invalid_argument', 'Use --timeout (seconds) or --timeout-ms, not both.');\n }\n const raw = opts.timeout ?? opts.timeoutMs;\n if (raw === undefined) return undefined;\n const ms = Number(raw) * (opts.timeout !== undefined ? 1000 : 1);\n if (raw.trim() === '' || !Number.isSafeInteger(ms) || ms < 0 || ms > 2_147_483_647) {\n throw new ActionsCliError('invalid_argument', 'Timeout must be a non-negative duration up to 2147483647 ms (0 means no command time limit).');\n }\n return ms;\n}\n\n/** Execute against an existing sandbox; no provisioning or automatic retries. */\nexport async function execute(\n c: ActionsClient,\n sandboxId: string,\n body: { command: string; cwd?: string; env?: Record<string, string> },\n opts: ExecOpts,\n): Promise<void> {\n const timeoutMs = execTimeout(opts);\n if (!opts.detach && !opts.stream && timeoutMs !== 0 && (timeoutMs === undefined || timeoutMs <= BUFFERED_MAX_MS)) {\n const res = await c.post<{ commandId: string } & CommandResult>(\n `/api/v1/sandboxes/${sandboxId}/commands`,\n { ...body, ...(timeoutMs !== undefined ? { timeoutMs } : {}) },\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 if (res.exitCode !== 0) process.exitCode = res.exitCode;\n return;\n }\n const { process: job } = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${sandboxId}/processes`, body,\n );\n if (opts.detach) {\n output(opts, job, (p) => {\n console.log(p.jobId);\n console.error(`Follow: compute logs ${sandboxId} ${p.jobId} --follow`);\n });\n return;\n }\n // Use bounded waits and cumulative output so jobs can outlive a single\n // HTTP request, without replaying output or starting another process.\n await streamJob(c, sandboxId, job.jobId, timeoutMs ?? BUFFERED_MAX_MS, opts);\n}\n\nasync function streamJob(c: ActionsClient, sandboxId: string, jobId: string, timeoutMs: number, opts: ExecOpts): Promise<void> {\n const base = `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`;\n const controller = new AbortController();\n let stopCode: number | undefined;\n let stopping: Promise<void> | undefined;\n let killError: string | undefined;\n const stop = (code: number, signal: string) => {\n if (stopping) return;\n stopCode = code;\n stopping = c.post(`${base}/kill`, { signal }, { signal: AbortSignal.timeout(10_000) })\n .then(() => undefined)\n .catch(() => {\n killError = `Could not stop job ${jobId}; run compute instances kill ${sandboxId} ${jobId}.`;\n if (!opts.json) console.error(killError);\n })\n .finally(() => controller.abort());\n };\n const onInterrupt = () => stop(130, 'SIGINT');\n const onTerminate = () => stop(143, 'SIGTERM');\n process.on('SIGINT', onInterrupt);\n process.on('SIGTERM', onTerminate);\n const deadline = timeoutMs === 0 ? undefined : Date.now() + timeoutMs;\n const timer = timeoutMs === 0 ? undefined : setTimeout(() => stop(124, 'SIGKILL'), timeoutMs);\n let stdoutOffset = 0;\n let stderrOffset = 0;\n try {\n while (stopCode === undefined) {\n const remaining = deadline === undefined ? 1000 : deadline - Date.now();\n if (remaining <= 0) { stop(124, 'SIGKILL'); break; }\n const { process: status } = await c.post<{ process: SandboxProcessStatus }>(\n `${base}/wait`, { timeoutMs: Math.min(1000, remaining) },\n { signal: controller.signal },\n );\n const emit = (event: string, data: Record<string, unknown>) => {\n if (opts.json) process.stdout.write(JSON.stringify({ event, ...data }) + '\\n');\n else if (event === 'stdout') process.stdout.write(String(data.chunk));\n else if (event === 'stderr') process.stderr.write(String(data.chunk));\n };\n if (status.stdout.length > stdoutOffset) emit('stdout', { chunk: status.stdout.slice(stdoutOffset) });\n if (status.stderr.length > stderrOffset) emit('stderr', { chunk: status.stderr.slice(stderrOffset) });\n stdoutOffset = status.stdout.length;\n stderrOffset = status.stderr.length;\n if (status.status === 'exited') {\n const code = status.exitCode ?? 128;\n emit('exit', { exitCode: code });\n if (code !== 0) process.exitCode = code;\n return;\n }\n }\n } catch (error) {\n if (stopCode === undefined) {\n // The process may still be running. Do not replay the start request.\n const recovery = `Job ${jobId} remains available: compute logs ${sandboxId} ${jobId} --follow`;\n if (error instanceof Error) {\n error.message += `. ${recovery}`;\n throw error;\n }\n throw new Error(`${String(error)}. ${recovery}`);\n }\n } finally {\n clearTimeout(timer);\n process.removeListener('SIGINT', onInterrupt);\n process.removeListener('SIGTERM', onTerminate);\n await stopping;\n if (stopCode !== undefined) {\n process.exitCode = stopCode;\n if (opts.json) process.stdout.write(JSON.stringify({ event: 'exit', exitCode: stopCode, ...(killError ? { error: killError } : {}) }) + '\\n');\n }\n }\n}\n","\nexport interface SyncEntry {\n path: string;\n type: 'file' | 'directory' | 'symlink';\n mode: number;\n protected?: boolean;\n links?: number;\n hash?: string;\n link?: string;\n}\nexport interface TreeRequest {\n root: string;\n missing?: boolean;\n destination?: boolean;\n remove?: SyncEntry[];\n directories?: SyncEntry[];\n entries?: SyncEntry[];\n}\n\n/** Self-contained: the same function runs locally and in a sandbox's Node runtime. */\nexport async function treeOperation(input: TreeRequest, requireModule: NodeRequire, exclude?: (name: string, directory: boolean) => boolean): Promise<SyncEntry[]> {\n const fs = requireModule('node:fs') as typeof import('node:fs');\n const path = requireModule('node:path') as typeof import('node:path');\n const crypto = requireModule('node:crypto') as typeof import('node:crypto');\n const root = path.resolve(input.root);\n if (root.split(path.sep).includes('.git')) throw new Error('Sync cannot target .git.');\n if (root === path.parse(root).root) throw new Error('Sync requires a project directory, not a filesystem root.');\n // Never follow a destination symlink while applying changes.\n const checked = (relative: string): string => {\n if (path.isAbsolute(relative) || relative.split(/[\\\\/]/).some((s) => s === '..' || s === '.git') || relative.includes('\\0')) {\n throw new Error('Unsafe sync path: ' + relative);\n }\n const full = path.join(root, relative);\n let cursor = path.parse(full).root;\n const parts = full.slice(cursor.length).split(path.sep);\n for (const segment of parts.slice(0, -1)) {\n cursor = path.join(cursor, segment);\n try {\n if (fs.lstatSync(cursor).isSymbolicLink()) throw new Error('Sync cannot traverse symlink: ' + cursor);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n }\n return full;\n };\n checked('');\n try {\n const stat = fs.lstatSync(root);\n if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Sync requires a real directory: ' + root);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || !input.missing) throw error;\n if (!input.directories && !input.remove) return [];\n fs.mkdirSync(root, { recursive: true });\n }\n for (const expected of input.remove ?? []) {\n const relative = expected.path;\n const full = checked(relative);\n if (!relative) throw new Error('Cannot delete the sync root.');\n // Files first, directories last. rmdir refuses unexpected/new children.\n const stat = fs.lstatSync(full);\n const type = stat.isSymbolicLink() ? 'symlink' : stat.isDirectory() ? 'directory' : 'file';\n let hash: string | undefined;\n if (type === 'file') {\n const digest = crypto.createHash('sha256');\n for await (const chunk of fs.createReadStream(full)) digest.update(chunk);\n hash = digest.digest('hex');\n }\n if (type !== expected.type || type === 'file' && (hash !== expected.hash || (stat.mode & 0o777) !== expected.mode) ||\n type === 'symlink' && fs.readlinkSync(full) !== expected.link) throw new Error('Destination changed before deletion: ' + relative);\n if (stat.isDirectory()) fs.rmdirSync(full);\n else fs.unlinkSync(full);\n }\n for (const entry of input.directories ?? []) {\n const full = checked(entry.path);\n try {\n if (!fs.lstatSync(full).isDirectory()) throw new Error('Sync type conflict: ' + entry.path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n fs.mkdirSync(full, { mode: entry.mode | 0o700 });\n }\n }\n if (input.remove || input.directories) return [];\n const result: SyncEntry[] = [];\n // The checkpoint engine owns traversal and hashing. This pass only checks\n // planned paths against current filesystem metadata and sync's boundaries.\n for (const entry of input.entries ?? []) {\n const full = checked(entry.path);\n const stat = fs.lstatSync(full);\n const type = stat.isSymbolicLink() ? 'symlink' : stat.isDirectory() ? 'directory' : stat.isFile() ? 'file' : undefined;\n if (!type || type !== entry.type || (stat.mode & 0o777) !== entry.mode) throw new Error('Project changed during snapshot scan: ' + entry.path);\n if (exclude?.(entry.path, type === 'directory')) continue;\n if (type === 'symlink') {\n const link = fs.readlinkSync(full);\n const target = path.resolve(path.dirname(full), link);\n if (!input.destination && (path.isAbsolute(link) || target !== root && !target.startsWith(root + path.sep))) throw new Error('Symlink points outside sync root: ' + entry.path);\n if (link !== entry.link) throw new Error('Project changed during snapshot scan: ' + entry.path);\n }\n result.push({ ...entry,\n ...(input.destination && type === 'file' && stat.nlink > 1 ? { links: stat.nlink } : {}),\n ...(input.destination && type === 'directory' && fs.existsSync(path.join(full, '.git')) ? { protected: true } : {}),\n });\n }\n return result;\n}\nexport const localTree = async (input: TreeRequest, exclude?: (name: string, directory: boolean) => boolean): Promise<SyncEntry[]> => {\n const { scanLocalTree } = await import('./snapshot-engine.js');\n return scanLocalTree(input, exclude);\n};\n","/** Adapter around the exact OCI checkpoint engine shipped by the platform. */\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { tmpdir } from 'node:os';\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { randomUUID, createHash } from 'node:crypto';\nimport type { ActionsClient } from './actions-client.js';\nimport { execCommand } from './exec.js';\nimport { treeOperation, type SyncEntry, type TreeRequest } from './sync-fs.js';\nimport { createRequire } from 'node:module';\n\nconst executeFile = promisify(execFile);\nexport const ENGINE_FILE = fileURLToPath(new URL('../checkpoint.cjs', import.meta.url));\nconst RUNNER_FILE = fileURLToPath(new URL('../checkpoint-runner.cjs', import.meta.url));\nexport interface IndexEntry { type: 'dir' | 'file' | 'symlink'; mode: number; sha?: string; link?: string; layer: number; size?: number; mtime?: number }\nexport interface CheckpointConfig {\n kind: string; files: Record<string, IndexEntry>; capture: { paths: string[]; exclude: string[] };\n [key: string]: unknown;\n}\nexport interface CaptureResult { manifestKey: string; configDigest: string; layers: { root: string; digest: string }[] }\nexport interface EngineDiff { added: string[]; changed: { path: string }[]; deleted: string[] }\nexport type EngineEndpoint = { local: string } | { id: string; remote: string };\nexport const endpointRoot = (e: EngineEndpoint): string => 'local' in e ? e.local : e.remote;\nconst requireModule = createRequire(import.meta.url);\n\n/** Snapshot selectors are globs; fail rather than accidentally widen an exact path. */\nexport function exactSelector(value: string): string {\n if (/[*?]/.test(value)) throw new Error('Snapshot sync cannot address literal * or ? in a path: ' + value);\n return value.split(path.sep).join('/');\n}\nexport function ignoredPaths(root: string, exclude?: (name: string, directory: boolean) => boolean): string[] {\n const paths = ['**/.git', '**/.git/**'];\n if (!exclude || !fs.existsSync(root)) return paths;\n const visit = (dir: string) => {\n for (const entry of fs.readdirSync(path.join(root, dir), { withFileTypes: true })) {\n const name = dir ? dir + '/' + entry.name : entry.name;\n if (entry.name === '.git' || exclude(name, entry.isDirectory())) paths.push(exactSelector(path.join(root, name)));\n else if (entry.isDirectory()) visit(name);\n }\n };\n visit('');\n return paths;\n}\n\nexport function indexEntries(config: CheckpointConfig, root: string): SyncEntry[] {\n const result: SyncEntry[] = [];\n for (const [absolute, entry] of Object.entries(config.files)) {\n if (absolute === root) continue;\n const relative = path.posix.relative(root, absolute);\n if (!relative || relative.startsWith('/') || relative.includes('\\\\') || relative.split('/').some((p) => !p || p === '..' || p === '.' || p === '.git') || relative.includes('\\0')) throw new Error('Unsafe checkpoint file index.');\n if (!['dir', 'file', 'symlink'].includes(entry.type)) throw new Error('Unsupported checkpoint entry.');\n result.push({ path: relative, type: entry.type === 'dir' ? 'directory' : entry.type, mode: entry.mode & 0o777,\n ...(entry.sha ? { hash: entry.sha } : {}), ...(entry.link !== undefined ? { link: entry.link } : {}) });\n }\n return result.sort((a, b) => a.path.localeCompare(b.path));\n}\n\nexport class SnapshotSession {\n readonly temp = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'compute-sync-')));\n private remoteRoots = new Map<string, string>();\n constructor(private c?: ActionsClient) {}\n async command(id: string, script: string): Promise<string> {\n const result = await this.c!.post<{ exitCode: number; stdout: string; stderr: string }>(`/api/v1/sandboxes/${id}/commands`, {\n command: execCommand(['node', '--input-type=commonjs', '-e', script]), timeoutMs: 290_000,\n });\n if (result.exitCode !== 0) throw new Error(`Snapshot sync failed: ${result.stderr || result.stdout || 'Node.js is required in the sandbox.'}`);\n return result.stdout;\n }\n async remoteRoot(id: string): Promise<string> {\n const existing = this.remoteRoots.get(id);\n if (existing) return existing;\n const root = JSON.parse(await this.command(id, `const fs=require('node:fs');console.log(JSON.stringify(fs.mkdtempSync(require('node:path').join(require('node:os').tmpdir(),'compute-sync-'))))`));\n if (typeof root !== 'string' || !root.startsWith('/') || !path.posix.basename(root).startsWith('compute-sync-')) throw new Error('Invalid snapshot work directory.');\n this.remoteRoots.set(id, root);\n await this.write(id, path.posix.join(root, 'checkpoint.cjs'), fs.readFileSync(ENGINE_FILE, 'utf8'));\n await this.write(id, path.posix.join(root, 'runner.cjs'), fs.readFileSync(RUNNER_FILE, 'utf8'));\n return root;\n }\n async write(id: string, file: string, content: string): Promise<void> {\n await this.c!.post(`/api/v1/sandboxes/${id}/files`, { path: file, content });\n }\n async read(id: string, file: string): Promise<string> {\n const response = await this.c!.get<{ type: string; content?: string }>(`/api/v1/sandboxes/${id}/files`, { path: file });\n if (response.type !== 'file' || response.content === undefined) throw new Error('Snapshot result file is unavailable.');\n return response.content;\n }\n async operation<T>(id: string | undefined, operation: string, args: Record<string, unknown>): Promise<T> {\n const root = id ? await this.remoteRoot(id) : this.temp;\n const payload = path.join(root, randomUUID() + '.args.json');\n const resultPath = path.join(root, randomUUID() + '.result.json');\n const json = JSON.stringify({ ...args, resultPath });\n if (id) {\n await this.write(id, payload, json);\n const res = await this.c!.post<{ exitCode: number; stderr: string; stdout: string }>(`/api/v1/sandboxes/${id}/commands`, {\n command: execCommand(['node', path.posix.join(root, 'runner.cjs'), path.posix.join(root, 'checkpoint.cjs'), operation, payload]), timeoutMs: 290_000,\n });\n if (res.exitCode !== 0) {\n let detail = res.stderr || res.stdout;\n try { detail = await this.read(id, resultPath); } catch { /* no result if startup failed */ }\n throw new Error(`Snapshot ${operation} failed: ${detail}`);\n }\n return JSON.parse(await this.read(id, resultPath));\n }\n fs.writeFileSync(payload, json, { mode: 0o600 });\n try { await executeFile(process.execPath, [RUNNER_FILE, ENGINE_FILE, operation, payload], { timeout: 300_000, maxBuffer: 1024 * 1024 }); }\n catch (error) {\n const detail = fs.existsSync(resultPath) ? fs.readFileSync(resultPath, 'utf8') : (error as Error).message;\n throw new Error(`Snapshot ${operation} failed: ${detail}`);\n }\n return JSON.parse(fs.readFileSync(resultPath, 'utf8'));\n }\n async guard(endpoint: EngineEndpoint, request: Omit<TreeRequest, 'root'>): Promise<SyncEntry[]> {\n const input = { root: endpointRoot(endpoint), ...request };\n if ('local' in endpoint) return treeOperation(input, requireModule);\n const root = await this.remoteRoot(endpoint.id);\n const payload = path.posix.join(root, randomUUID() + '.guard.json');\n const resultPath = payload + '.result';\n await this.write(endpoint.id, payload, JSON.stringify(input));\n await this.command(endpoint.id, `const fs=require('node:fs');(${treeOperation.toString()})(JSON.parse(fs.readFileSync(${JSON.stringify(payload)},'utf8')),require).then(entries=>fs.writeFileSync(${JSON.stringify(resultPath)},JSON.stringify(entries))).catch(e=>{console.error(e.message);process.exitCode=1})`);\n return JSON.parse(await this.read(endpoint.id, resultPath));\n }\n async scan(endpoint: EngineEndpoint, destination = false, exclude?: (name: string, directory: boolean) => boolean): Promise<{ config: CheckpointConfig; entries: SyncEntry[] }> {\n const root = endpointRoot(endpoint);\n await this.guard(endpoint, { missing: destination });\n const result = await this.operation<{ config: CheckpointConfig; missing: string[] }>('id' in endpoint ? endpoint.id : undefined, 'scan', {\n paths: [root], exclude: 'local' in endpoint ? ignoredPaths(root, exclude) : ['**/.git', '**/.git/**'],\n });\n if (result.missing.length && !(destination && result.missing.length === 1 && result.missing[0] === root)) throw new Error('Snapshot scan could not read all project paths: ' + result.missing.join(', '));\n const entries = await this.guard(endpoint, { missing: destination, destination, entries: indexEntries(result.config, root) });\n return { config: result.config, entries };\n }\n async diff(source: SyncEntry[], destination: SyncEntry[]): Promise<EngineDiff> {\n const toConfig = (entries: SyncEntry[]) => ({ files: Object.fromEntries(entries.map((e) => [e.path, { type: e.type === 'directory' ? 'dir' : e.type, mode: e.mode, sha: e.hash, link: e.link }])) });\n const a = path.join(this.temp, randomUUID() + '.json'), b = path.join(this.temp, randomUUID() + '.json');\n fs.writeFileSync(a, JSON.stringify(toConfig(destination)), { mode: 0o600 });\n fs.writeFileSync(b, JSON.stringify(toConfig(source)), { mode: 0o600 });\n return (await this.operation<{ diff: EngineDiff }>(undefined, 'diff', { a: { configPath: a }, b: { configPath: b } })).diff;\n }\n async close(): Promise<void> {\n try {\n for (const [id, root] of this.remoteRoots) {\n try { await this.command(id, `require('node:fs').rmSync(${JSON.stringify(root)},{recursive:true,force:true})`); } catch { /* private scratch only; do not mask a transfer failure */ }\n }\n } finally { fs.rmSync(this.temp, { recursive: true, force: true }); }\n }\n}\n\n/** Build a valid, content-addressed OCI view containing only the planned writes. */\nexport function selectSnapshot(store: string, manifestKey: string, root: string, copy: SyncEntry[], destination: { config: CheckpointConfig; entries: SyncEntry[] }, destinationRoot: string): string {\n if (!/^manifests\\/[a-f0-9-]+\\.json$/.test(manifestKey)) throw new Error('Invalid snapshot manifest key.');\n const manifest = JSON.parse(fs.readFileSync(path.join(store, manifestKey), 'utf8'));\n if (!/^sha256:[a-f0-9]{64}$/.test(manifest.config?.digest)) throw new Error('Invalid snapshot config digest.');\n const configHex = manifest.config.digest.slice(7);\n const bytes = fs.readFileSync(path.join(store, 'blobs', configHex));\n if (createHash('sha256').update(bytes).digest('hex') !== configHex) throw new Error('Snapshot config digest mismatch.');\n const raw = JSON.parse(bytes.toString('utf8'));\n const config: CheckpointConfig = raw.computesdk?.kind === 'sandbox-checkpoint' ? raw.computesdk : raw;\n const files: Record<string, IndexEntry> = {};\n const wantedLayers = new Set<number>();\n const dest = new Map(destination.entries.map((e) => [e.path, e]));\n for (const entry of copy) {\n const absolute = path.posix.join(root, entry.path);\n const captured = config.files[absolute];\n if (!captured || captured.type !== (entry.type === 'directory' ? 'dir' : entry.type) || captured.sha !== entry.hash || captured.link !== entry.link || (captured.mode & 0o777) !== entry.mode) throw new Error('Source changed during snapshot capture; rerun sync.');\n files[absolute] = { ...captured, mode: entry.mode };\n if (entry.type !== 'directory') wantedLayers.add(captured.layer);\n let parent = path.posix.dirname(absolute);\n while (parent === root || parent.startsWith(root + '/')) {\n const index = config.files[parent];\n if (!index || index.type !== 'dir') throw new Error('Snapshot is missing a parent directory.');\n const relative = path.posix.relative(root, parent);\n const mode = relative ? dest.get(relative)?.mode : destination.config.files[destinationRoot]?.mode;\n files[parent] ??= { ...index, mode: (mode ?? index.mode) & 0o777 };\n if (parent === root) break;\n parent = path.posix.dirname(parent);\n }\n }\n config.files = files;\n const allLayers = manifest.layers as { annotations: Record<string, string> }[];\n const indexes = allLayers.map((layer, index) => wantedLayers.has(config.capture.paths.indexOf(layer.annotations['com.computesdk.checkpoint.root'])) ? index : -1).filter((index) => index >= 0);\n manifest.layers = indexes.map((index) => allLayers[index]);\n if (raw.rootfs) raw.rootfs.diff_ids = indexes.map((index) => raw.rootfs.diff_ids[index]);\n const selected = Buffer.from(JSON.stringify(raw));\n const hex = createHash('sha256').update(selected).digest('hex');\n fs.writeFileSync(path.join(store, 'blobs', hex), selected, { mode: 0o600 });\n manifest.config = { ...manifest.config, digest: 'sha256:' + hex, size: selected.length };\n const key = 'manifests/selected.json';\n fs.writeFileSync(path.join(store, key), JSON.stringify(manifest), { mode: 0o600 });\n return key;\n}\n\nexport async function scanLocalTree(input: TreeRequest, exclude?: (name: string, directory: boolean) => boolean): Promise<SyncEntry[]> {\n const session = new SnapshotSession();\n try {\n if (input.remove || input.directories) return session.guard({ local: input.root }, input);\n return (await session.scan({ local: input.root }, !!input.missing, exclude)).entries;\n } finally { await session.close(); }\n}\n","/**\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 # SDK provider credentials in this environment\n * compute byok … # the org's BYOK provider keys and custom rates\n * compute org … # active org, members, invitations\n * compute invitations … # your own invitations (show/accept/decline)\n * compute actions … # Actions API\n * compute credits [ledger | topup <usd>] # prepaid credit, which managed accounts bill from\n * compute market … # not generally available (hidden from help)\n * compute new [vercel | --vercel] # create a sandbox (short for `compute sandboxes create`)\n * compute instances … # platform compute-instance control plane\n * (alias: compute sandboxes, compute sbx)\n * compute bench … # benchmarks platform CLI (runs, results, fork, …)\n */\n\nimport 'dotenv/config';\nimport { Command, Option } 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 { registerByokCommands } from './byok.js';\nimport { registerMarketCommands } from './market.js';\nimport { registerCreditsCommands } from './credits.js';\nimport { inheritParentOptions } from './option-inheritance.js';\nimport { registerSandboxesCommands } from './sandboxes.js';\nimport { registerAgentsCommands } from './agents.js';\nimport { fail } from './actions.js';\nimport { registerSyncCommand } from './sync.js';\nimport { registerStatusCommand } from './status.js';\nimport { login, clearPendingLogins, type LoginOptions } from './login.js';\nimport { parseBenchDispatch, runBench } from './bench.js';\nimport { registerManifestCommand } from './manifest.js';\nimport { registerInvitationsCommands, registerOrgMemberCommands } from './org-members.js';\nimport { benchAuth, envBaseUrl, fetchWhoami, formatWhoami } from './session.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// `compute credits --org x topup 50`: a parent's flags reach the subcommand.\ninheritParentOptions(program);\n\nprogram\n .name('compute')\n .description('ComputeSDK CLI')\n .version(VERSION, '-v, --version', 'print the CLI version')\n .enablePositionalOptions()\n .passThroughOptions();\n\n// Keep the previous uppercase shorthand compatible as well.\nprogram.addOption(new Option('-V', 'print the CLI version').hideHelp());\nprogram.on('option:V', () => { console.log(VERSION); process.exit(0); });\nprogram.addHelpText('before', 'Run code on a cloud sandbox:\\n compute new\\n compute exec echo hello\\n compute destroy\\n');\n\n// Reports the OAuth login just made, so it reads the stored login rather\n// than COMPUTE_API_KEY.\nasync function printSessionLine(options?: { baseUrl?: string }): Promise<void> {\n try {\n const { getMe, resolveAuth } = await import('@benchsdk/cli');\n const me = await getMe(await resolveAuth({ baseUrl: options?.baseUrl ?? envBaseUrl() }));\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?: LoginOptions): Promise<void> {\n await login(options);\n}\n\nasync function runLogout(): Promise<void> {\n const { clearCredentials } = await import('@benchsdk/cli');\n await clearCredentials();\n clearPendingLogins();\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 .option('--no-browser', 'print the sign-in URL instead of opening a browser')\n .option('--json', 'return a sign-in URL and code immediately; use --wait to complete login')\n .option('--wait', 'wait for approval (default without --json)')\n .option('--new', 'replace the pending sign-in with a new code')\n .action(async (opts) => {\n try { await runLogin(opts); } catch (error) { fail(error, opts); return; }\n if (opts.json) return;\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 me = await fetchWhoami(await benchAuth({ baseUrl: options.baseUrl }));\n if (options.json) {\n console.log(JSON.stringify(me, null, 2));\n return;\n }\n for (const line of formatWhoami(me)) console.log(line);\n}\n\nconst org = program.command('org').description('Manage the active organization, its members and invitations');\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 // The switch belongs to the stored user login: COMPUTE_API_KEY (an org\n // key, no user) must not stand in for it, so only the URL is overridden.\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\n// members / invitations / invite / member set-role|remove / leave, over the\n// v1 organization routes with the `current` org alias (src/org-members.ts).\nregisterOrgMemberCommands(org);\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// ─── invitations ─────────────────────────────────────────────────────────────\n// The signed-in user's own invitations: list, show, accept, decline.\n\nregisterInvitationsCommands(program);\n\n// ─── actions ─────────────────────────────────────────────────────────────────\n\nregisterActionsCommands(program);\n\n// ─── byok ────────────────────────────────────────────────────────────────────\n// `compute byok` drives /api/v1/providers — the org's BYOK provider keys and\n// custom rates, shared by Actions and sandboxes (src/byok.ts).\n\nregisterByokCommands(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// ─── credits ─────────────────────────────────────────────────────────────────\n// `compute credits` — prepaid credit (balance, ledger, top-ups), which managed\n// accounts bill from (src/credits.ts).\nregisterCreditsCommands(program);\nregisterStatusCommand(program);\n\n// ─── sandboxes ───────────────────────────────────────────────────────────────\n// `compute instances` (alias `compute sandboxes`/`sbx`) drives\n// /api/v1/sandboxes — the customer-facing compute control plane\n// (create/exec/processes/files/urls). Same auth as actions.\n\nregisterSandboxesCommands(program);\nregisterSyncCommand(program);\n\n// ─── agents ──────────────────────────────────────────────────────────────────\n// `compute agents` (alias `ag`) drives /api/v1/agents — managed agents:\n// durable configs whose sessions run inside routed sandboxes. Same auth.\n\nregisterAgentsCommands(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// fork/iterations/artifacts/logs/export all dispatch through it,\n// with COMPUTE_PLATFORM_URL, COMPUTE_API_KEY and COMPUTE_ORG/--org forwarded\n// (src/bench.ts).\n\nprogram\n .command('bench')\n .description('Benchmarks platform CLI (run, auth, org, benchmarks, runs, results, fork, artifacts, export, ...)')\n .allowUnknownOption()\n .helpOption(false)\n .action(() => {\n // Never reached: bench args are dispatched pre-parse below.\n });\n\n// ─── __manifest (hidden) ─────────────────────────────────────────────────────\n// Regenerate the committed cli-manifest.json with\n// `pnpm --filter @computesdk/cli run manifest` after changing commands.\n\nregisterManifestCommand(program, {\n version: packageJson.version,\n packageDir: join(__dirname, '..'),\n});\n\n// ─── Run ─────────────────────────────────────────────────────────────────────\n\n// Bench args are opaque to commander (its own --flags, `--` separators, file\n// paths), so they dispatch before parsing — including `compute --org x bench`.\n// `@benchsdk/runner`'s run() owns the process — it exits itself after dispatch.\nasync function main() {\n const bench = parseBenchDispatch(process.argv.slice(2));\n if (bench) {\n await runBench(bench);\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","/**\n * `compute byok` — the org's BYOK providers over `/api/v1/providers`: the\n * providers it brings its own key for, each key's state, and the org's custom\n * rate. Keys and custom rates serve every product that places sandboxes\n * (Actions jobs and sandbox creates alike), which is why they live here and\n * not under `compute actions` or `compute instances`.\n *\n * A custom rate is the org's own number for cost reporting (typically what it\n * pays the provider). Sandbox costs on that provider are reported at it\n * instead of the platform rate; it never changes what the org is billed.\n *\n * `compute providers` is a different thing: the provider credentials in the\n * local environment that the SDK would use.\n */\n\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport { output, client, fail, parseInputs, secretValueClient, usageErrorOutput, type CommonOpts } from './actions.js';\nimport { confirmWrite } from './confirm.js';\nimport { formatRateAllUnits, type RateAllUnits, type RatePer } from './rate-display.js';\nimport { safeTerm } from './term.js';\n\n// Wire shapes: benchmarks-platform lib/providers/byok-wire.ts.\n\nexport interface ProviderRate {\n usd: number;\n per: RatePer;\n rateUsd: RateAllUnits;\n}\n\nexport interface ByokKey {\n provider: string;\n /** Masked tail of the stored key; null when none is stored. Never the key. */\n keyHint: string | null;\n lastCheckedAt: string | null;\n status: 'connected' | 'unconfigured' | 'error';\n statusDetail: string | null;\n actCapable: boolean;\n credential: 'key';\n fields: Array<{ name: string; label: string; placeholder?: string; secret: boolean; required?: boolean }>;\n /** Region-keyed credentials (archil): each region's masked hint. */\n pairs?: Array<{ region: string; keyHint: string | null }>;\n}\n\nexport interface ByokProvider {\n provider: string;\n regions: string[];\n key: ByokKey;\n /** What costs are reported at: `customRate` when set, else `platformRate`. */\n rate: ProviderRate;\n customRate: ProviderRate | null;\n platformRate: ProviderRate;\n}\n\nexport interface ByokKeyResponse {\n key: ByokKey;\n /** Present on the verify response. */\n verified?: boolean;\n}\n\nconst RATE_UNITS: RatePer[] = ['second', 'minute', 'hour'];\nconst MAX_RATE_USD = 1_000;\n\nfunction providerPath(provider: string, rest = ''): string {\n return `/api/v1/providers/${encodeURIComponent(provider)}${rest}`;\n}\n\nfunction keyText(key: ByokKey): string {\n if (key.keyHint === null) return pc.gray('no key');\n const status =\n key.status === 'connected' ? pc.green('connected') : key.status === 'error' ? pc.red('error') : pc.yellow('untested');\n const hints = key.pairs?.length\n ? key.pairs.map((p) => `${safeTerm(p.keyHint ?? '—')}@${safeTerm(p.region)}`).join(',')\n : safeTerm(key.keyHint);\n return `${status} ${pc.dim(hints)}`;\n}\n\nfunction rateText(p: ByokProvider): string {\n return p.customRate\n ? `${formatRateAllUnits(p.customRate.rateUsd)} ${pc.cyan('custom')}`\n : `${formatRateAllUnits(p.platformRate.rateUsd)} ${pc.dim('platform')}`;\n}\n\n/** `● blaxel connected …abcd $0.1008/hr · … platform`. */\nexport function formatByokRow(p: ByokProvider): string {\n const ready = p.key.status === 'connected';\n const icon = ready ? pc.green('●') : pc.gray('○');\n const name = ready ? pc.white(safeTerm(p.provider)) : pc.gray(safeTerm(p.provider));\n return ` ${icon} ${name} ${keyText(p.key)} ${rateText(p)}`;\n}\n\nexport function formatByokDetail(p: ByokProvider): string {\n const lines = [\n `${pc.white(safeTerm(p.provider))} ${keyText(p.key)}`,\n ` regions ${p.regions.length > 0 ? p.regions.map(safeTerm).join(', ') : 'account default'}`,\n ` last tested ${p.key.lastCheckedAt === null ? '—' : safeTerm(p.key.lastCheckedAt)}`,\n ` platform rate ${formatRateAllUnits(p.platformRate.rateUsd)}`,\n ` custom rate ${p.customRate ? formatRateAllUnits(p.customRate.rateUsd) : pc.dim('none (costs report at the platform rate)')}`,\n ];\n if (p.key.status === 'error' && p.key.statusDetail) lines.push(` last error ${pc.dim(safeTerm(p.key.statusDetail))}`);\n return lines.join('\\n');\n}\n\nexport function formatByokVerify(r: ByokKeyResponse): string {\n const head = r.verified === true ? pc.green('verified') : pc.red('not verified');\n const detail = r.key.statusDetail ? pc.dim(` ${safeTerm(r.key.statusDetail)}`) : '';\n const act = r.key.actCapable ? pc.green(' act-capable') : '';\n return `${head} ${safeTerm(r.key.provider)}${act}${detail}`;\n}\n\n/** `<usd>` and `--per` as the rate route takes them; refuses what the server would. */\nexport function parseRateArgs(usd: string, per: string | undefined): { usd: number; per: RatePer } {\n const amount = Number(usd);\n if (usd.trim() === '' || !Number.isFinite(amount) || amount < 0 || amount > MAX_RATE_USD) {\n throw new Error(`<usd> must be a number from 0 to ${MAX_RATE_USD}`);\n }\n const unit = (per ?? 'hour') as RatePer;\n if (!RATE_UNITS.includes(unit)) throw new Error('--per must be second, minute or hour');\n return { usd: amount, per: unit };\n}\n\n/** The `PUT …/key` body from `--key` or `--field name=value`. */\nexport function keyBody(opts: { key?: string; field?: string[] }): Record<string, unknown> {\n if (opts.field !== undefined) {\n if (opts.key !== undefined) throw new Error('Pass either --key or --field, not both.');\n return { fields: parseInputs(opts.field) };\n }\n if (opts.key !== undefined) return { key: opts.key };\n throw new Error('Pass --key <key> or --field name=value.');\n}\n\nexport function registerByokCommands(program: Command): void {\n const byok = program\n .command('byok')\n .description(\"The org's BYOK providers: their keys and custom rates, shared by Actions and sandboxes\")\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 const list = async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<{ providers: ByokProvider[] }>('/api/v1/providers');\n output(opts, data, (d) => {\n for (const p of d.providers) console.log(formatByokRow(p));\n });\n } catch (e) {\n fail(e, opts);\n }\n };\n common(byok).action(list);\n common(byok.command('list').alias('ls').description('Every provider the org may bring a key for, with key state and rate')).action(list);\n\n common(\n byok\n .command('show')\n .description(\"One provider's key state, platform rate and custom rate\")\n .argument('<provider>', 'provider id (e.g. tensorlake, blaxel)'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<{ provider: ByokProvider }>(providerPath(provider));\n output(opts, data, (d) => console.log(formatByokDetail(d.provider)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n byok\n .command('configure')\n .description(\"Save the org's key for a provider; untested until verified (owner/admin)\")\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', 'test the key with a real sandbox after saving'),\n ).action(async (provider: string, opts: CommonOpts & { key?: string; field?: string[]; verify?: boolean }) => {\n try {\n // A provider key is a local secret: trusted hosts only, even with --allow-untrusted-host.\n const c = await secretValueClient(opts, 'provider keys');\n const saved = await c.put<ByokKeyResponse>(providerPath(provider, '/key'), keyBody(opts));\n const verification = opts.verify ? await c.post<ByokKeyResponse>(providerPath(provider, '/verify')) : undefined;\n output(opts, verification ? { key: saved.key, verification } : saved, () => {\n console.log(`saved ${safeTerm(saved.key.provider)} ${pc.dim(safeTerm(saved.key.keyHint ?? ''))} ${safeTerm(saved.key.status)}`);\n if (verification) console.log(formatByokVerify(verification));\n });\n if (verification?.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n byok\n .command('verify')\n .description('Test the stored key by placing a real sandbox with it (\"Test\" in Settings; owner/admin)')\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<ByokKeyResponse>(providerPath(provider, '/verify'));\n output(opts, result, (r) => console.log(formatByokVerify(r)));\n if (result.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n byok\n .command('remove')\n .alias('rm')\n .description(\"Delete the org's stored key for a provider; nothing places on it until a new key passes (owner/admin)\")\n .argument('<provider>', 'provider id')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (provider: string, opts: CommonOpts & { yes?: boolean }) => {\n try {\n await confirmWrite(`Remove the ${provider} key? Sandboxes and Actions jobs stop placing on ${provider}.`, opts);\n const result = await (await client(opts)).del<{ provider: string; deleted: boolean }>(providerPath(provider, '/key'));\n output(opts, result, (r) => console.log(`deleted ${safeTerm(r.provider)}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const rate = byok\n .command('rate')\n .description('Custom rates: report sandbox costs at your own price. Reporting only; billing is unchanged');\n\n common(\n rate\n .command('set')\n .description(\"Report a provider's sandbox costs at your own rate, e.g. what you pay it (owner/admin). Doesn't change what you're billed\")\n .argument('<provider>', 'provider id')\n .argument('<usd>', 'the rate in USD')\n .option('--per <unit>', 'second, minute or hour', 'hour'),\n ).action(async (provider: string, usd: string, opts: CommonOpts & { per?: string }) => {\n try {\n const body = parseRateArgs(usd, opts.per);\n const data = await (await client(opts)).put<{ provider: ByokProvider }>(providerPath(provider, '/rate'), body);\n output(opts, data, (d) => {\n console.log(`${safeTerm(d.provider.provider)} costs now report at ${formatRateAllUnits(d.provider.rate.rateUsd)}`);\n console.log(pc.dim('Reporting only: billing is unchanged. Applies to sandboxes created from now on.'));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n rate\n .command('clear')\n .description(\"Drop a provider's custom rate; its costs report at the platform rate again (owner/admin)\")\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).del<{ provider: ByokProvider }>(providerPath(provider, '/rate'));\n output(opts, data, (d) =>\n console.log(`${safeTerm(d.provider.provider)} costs now report at the platform rate, ${formatRateAllUnits(d.provider.platformRate.rateUsd)}`),\n );\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * Shared display helpers for money and rates.\n *\n * Every human-readable rate the CLI prints shows all three units — per hour\n * first — as `$0.1008/hr · $0.00168/min · $0.000028/s`. Amounts print with up\n * to 4 significant decimals, never scientific notation, trailing zeros\n * trimmed.\n */\n\nexport type RatePer = 'second' | 'minute' | 'hour';\n\n/** A rate in the API's input shape: an amount plus the unit it's priced per. */\nexport interface UsdPer {\n usd: number;\n per: string;\n}\n\n/** The same rate normalized to all three units — the API's `rateUsd` shape. */\nexport interface RateAllUnits {\n perSecond: number;\n perMinute: number;\n perHour: number;\n}\n\nconst SECONDS_PER_MINUTE = 60;\nconst SECONDS_PER_HOUR = 3600;\n\n/** `{usd, per}` → `{perSecond, perMinute, perHour}`. */\nexport function rateAllUnits(rate: UsdPer): RateAllUnits {\n const perSecond =\n rate.per === 'second'\n ? rate.usd\n : rate.per === 'minute'\n ? rate.usd / SECONDS_PER_MINUTE\n : rate.usd / SECONDS_PER_HOUR;\n return {\n perSecond,\n perMinute: perSecond * SECONDS_PER_MINUTE,\n perHour: perSecond * SECONDS_PER_HOUR,\n };\n}\n\n/**\n * `$0.1008`, `$14.12`, `$3600`, `$0.000028` — up to 4 significant decimals,\n * trailing zeros trimmed, never scientific notation.\n */\nexport function formatUsd(usd: number): string {\n if (!Number.isFinite(usd)) return '$—';\n if (usd === 0) return '$0';\n // Decimals needed for 4 significant digits; Math.log10(1e-9) = -9 still\n // lands on a plain toFixed call, so tiny per-second values never go\n // exponential.\n // toFixed accepts at most 100 decimals; a rate smaller than 1e-100 would\n // ask for more, so cap it (the string rounds to $0 rather than throwing).\n const decimals = Math.min(100, Math.max(0, 3 - Math.floor(Math.log10(Math.abs(usd)))));\n const fixed = usd.toFixed(decimals);\n // Trailing zeros only count after a decimal point — \"3600\" stays \"3600\".\n const trimmed = fixed.includes('.') ? fixed.replace(/0+$/, '').replace(/\\.$/, '') : fixed;\n return `$${trimmed}`;\n}\n\n/**\n * `$1,234.56`, `$20.00`, `$0.10` — money *amounts* (balances, costs, holds,\n * credits, settlements): always 2 decimals with thousands separators.\n * Non-zero amounts under $0.01 keep up to 4 significant digits (`$0.0042`),\n * negatives render `-$0.50`. Rates use `formatUsd`, not this.\n */\nexport function formatMoney(usd: number): string {\n if (!Number.isFinite(usd)) return '$—';\n const sign = usd < 0 ? '-' : '';\n const abs = Math.abs(usd);\n if (abs !== 0 && abs < 0.01) {\n return `${sign}${formatUsd(abs)}`;\n }\n const s = abs.toLocaleString('en-US', {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n });\n return `${sign}$${s}`;\n}\n\n/** `$0.1008/hr · $0.00168/min · $0.000028/s` — per hour first. */\nexport function formatRateAllUnits(rate: RateAllUnits): string {\n return `${formatUsd(rate.perHour)}/hr · ${formatUsd(rate.perMinute)}/min · ${formatUsd(rate.perSecond)}/s`;\n}\n\n/** Convenience for a `{usd, per}` straight off the wire. */\nexport function formatUsdPer(rate: UsdPer): string {\n return formatRateAllUnits(rateAllUnits(rate));\n}\n","/**\n * `compute market` — both sides of the compute market. Sellers post listings,\n * reprice/pause/resume/withdraw them, and read payouts; buyers set the org\n * market cap, post standing bids, and manage prepaid credits. Everyone reads\n * the book.\n *\n * Auth: identical to `compute actions` — --api-key / COMPUTE_API_KEY / the\n * stored `compute login` (or `compute bench auth login`) session. Seller\n * commands need an org the platform flags `market_provider`; buyer commands\n * need a `market` buyer lane. 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';\nimport { formatMoney, formatUsdPer } from './rate-display.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/** `describeBid` — one row of GET /api/v1/market/bids. */\nexport interface MarketBid {\n id: string;\n size: string;\n region: string | null;\n useCase?: 'actions' | 'sandbox';\n maxUsd: number;\n per: MarketRatePer;\n status: 'open' | 'filled' | 'cancelled';\n createdAt: string;\n expiresAt: string | null;\n}\n\n/** `describeCap` — the org market cap, or null when none is set. */\nexport interface MarketCap {\n usd: number;\n per: MarketRatePer;\n}\n\n/** GET /api/v1/billing/balance. */\nexport interface MarketCreditBalance {\n balanceMicroUsd: number;\n heldMicroUsd: number;\n holds: { id: string; microUsd: number; runId: string | null; jobId: string | null; createdAt: string }[];\n}\n\n/** `describeLedgerEntry` — one row of GET /api/v1/billing/ledger. */\nexport interface MarketLedgerEntry {\n id: string;\n kind: string;\n label: string;\n microUsd: number;\n runId: string | null;\n jobId: string | null;\n createdAt: string;\n}\n\n/** `describePurchase` — one row of GET /api/v1/market/purchases. */\nexport interface MarketPurchase {\n id: string;\n provider: string;\n sellerName: string;\n size: string;\n region: string | null;\n useCase: string;\n usd: number;\n per: MarketRatePer;\n status: 'live' | 'closed' | 'replaced';\n startedAt: string;\n endedAt: string | null;\n secondsBilled: number | null;\n /** Null while the fill is still running. */\n costMicroUsd: number | null;\n runId: string | null;\n jobId: string | null;\n sandboxId: string | null;\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/** How a listing (or offer, or sale) is priced — all three units, per hour first. */\nexport function formatRate(usd: number, per: MarketRatePer): string {\n return formatUsdPer({ 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 = formatMoney(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 ${formatMoney(s.grossUsd)}`,\n `net ${formatMoney(s.netUsd)}`,\n paid,\n ].join(' ');\n}\n\nconst MICRO_USD = 1_000_000;\n\n/**\n * The `POST /api/v1/market/bids` body for `bid`: `{size, region?, maxUsd,\n * per, expiresInHours?, useCase}`. Same `--price <usd>/<unit>` rule as\n * `sell` — the unit is never implied.\n */\nexport function bidBody(opts: {\n size: string;\n price: string;\n per?: string;\n region?: string;\n expiresIn?: string;\n useCase?: string;\n}): Record<string, unknown> {\n const rate = parseRate(opts.price, opts.per);\n const expiresInHours = parseExpiresIn(opts.expiresIn);\n return {\n size: opts.size,\n ...(opts.region !== undefined && { region: opts.region }),\n maxUsd: rate.usd,\n per: rate.per,\n ...(expiresInHours !== undefined && { expiresInHours }),\n useCase: parseMarketLane(opts.useCase),\n };\n}\n\n/** `topup <usd>` → `amountUsd`: a positive dollar amount. */\nexport function parseTopupAmount(value: string): number {\n const usd = Number(value.replace(/^\\$/, ''));\n if (!USD_RE.test(value.replace(/^\\$/, '')) || !Number.isFinite(usd) || usd <= 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid amount \"${value}\". Expected a positive dollar amount (e.g. 50).`,\n );\n }\n return usd;\n}\n\nexport function formatCap(cap: MarketCap | null): string {\n return cap === null\n ? 'No market cap — market-placed jobs need their own bid to fill.'\n : `market cap ${formatRate(cap.usd, cap.per)}`;\n}\n\nexport function formatBidRow(bid: MarketBid): string {\n const status =\n bid.status === 'open'\n ? pc.green('open')\n : bid.status === 'filled'\n ? pc.cyan('filled')\n : pc.gray('cancelled');\n return [\n bid.id,\n status,\n pc.dim(bid.useCase === 'sandbox' ? 'sandbox' : 'actions'),\n safeTerm(bid.size),\n safeTerm(bid.region ?? 'any region'),\n `≤ ${formatRate(bid.maxUsd, bid.per)}`,\n pc.dim(bid.expiresAt ? `expires ${bid.expiresAt}` : 'standing'),\n ].join(' ');\n}\n\nexport function formatCredits(b: MarketCreditBalance): string {\n const lines = [`available ${formatMoney(b.balanceMicroUsd / MICRO_USD)}`];\n if (b.holds.length > 0) {\n lines.push(\n pc.dim(`reserved ${formatMoney(b.heldMicroUsd / MICRO_USD)} across ${b.holds.length} running sandbox${b.holds.length === 1 ? '' : 'es'} or job${b.holds.length === 1 ? '' : 's'}`),\n );\n }\n return lines.join('\\n');\n}\n\nexport function formatLedgerRow(e: MarketLedgerEntry): string {\n const usd = e.microUsd / MICRO_USD;\n const amount = usd < 0 ? `-${formatMoney(-usd)}` : `+${formatMoney(usd)}`;\n return [\n pc.dim(e.createdAt.slice(0, 19).replace('T', ' ')),\n (usd < 0 ? pc.red : pc.green)(amount.padStart(10)),\n safeTerm(e.label),\n pc.dim(e.jobId ? `job ${e.jobId}` : ''),\n ].join(' ').trimEnd();\n}\n\nexport function formatPurchaseRow(p: MarketPurchase): string {\n const cost =\n p.costMicroUsd !== null\n ? formatMoney(p.costMicroUsd / MICRO_USD)\n : p.status === 'live'\n ? pc.yellow('running')\n : '-';\n return [\n pc.dim(p.startedAt.slice(0, 19).replace('T', ' ')),\n cost.padStart(10),\n pc.cyan(safeTerm(p.sellerName)),\n pc.dim(`${safeTerm(p.provider)}/${safeTerm(p.region ?? 'any')}`),\n formatRate(p.usd, p.per),\n p.secondsBilled !== null ? pc.dim(`${p.secondsBilled}s`) : '',\n p.status === 'replaced' ? pc.yellow('replaced') : '',\n pc.dim(p.runId ? `run ${p.runId}` : p.sandboxId ? `sandbox ${p.sandboxId}` : ''),\n ]\n .filter((part) => part !== '')\n .join(' ');\n}\n\n// ─── Commands ───────────────────────────────────────────────────────────────\n\nexport function registerMarketCommands(program: Command): void {\n // Not generally available: registered for the orgs that use it, kept out\n // of `compute --help`.\n const market = program\n .command('market', { hidden: true })\n .description('Buy and 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 // ── Buyer side ──────────────────────────────────────────────────────────\n\n const cap = market\n .command('cap')\n .description('The org market cap: the most a market-placed job pays without its own bid');\n\n common(cap.command('show', { isDefault: true }).description('Show the current cap')).action(\n async (opts: CommonOpts) => {\n try {\n const { marketCap } = await (await client(opts)).get<{ marketCap: MarketCap | null }>(\n '/api/v1/market/bids',\n );\n output(opts, marketCap, (c) => console.log(formatCap(c)));\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n common(\n cap\n .command('set')\n .description('Set the cap')\n .requiredOption('--price <usd/unit>', 'max price per unit of time (e.g. 0.40/hour)')\n .option('--per <unit>', 'unit for a bare --price usd (second, minute, or hour)'),\n ).action(async (opts: CommonOpts & { price: string; per?: string }) => {\n try {\n const rate = parseRate(opts.price, opts.per);\n const { marketCap } = await (await client(opts)).post<{ marketCap: MarketCap | null }>(\n '/api/v1/market/bids',\n { marketCap: rate },\n );\n output(opts, marketCap, (c) => console.log(formatCap(c)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n cap\n .command('clear')\n .description('Remove the cap (refused while your placement order still names market)'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { marketCap } = await (await client(opts)).post<{ marketCap: MarketCap | null }>(\n '/api/v1/market/bids',\n { marketCap: null },\n );\n output(opts, marketCap, (c) => console.log(formatCap(c)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('bids')\n .description(\"Your org's standing bids — open, filled, and cancelled\"),\n ).action(async (opts: CommonOpts) => {\n try {\n const { bids } = await (await client(opts)).get<{ bids: MarketBid[] }>(\n '/api/v1/market/bids',\n );\n output(opts, bids, (rows) => {\n if (rows.length === 0) {\n console.log('No bids yet — post one with `compute market bid`.');\n return;\n }\n for (const bid of rows) console.log(formatBidRow(bid));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('bid')\n .description('Post a standing bid: the most you will pay for a size tier')\n .requiredOption('--size <tier>', 'size tier to buy (e.g. xlarge)')\n .requiredOption('--price <usd/unit>', 'max price per unit of time (e.g. 0.40/hour)')\n .option('--per <unit>', 'unit for a bare --price usd (second, minute, or hour)')\n .option('--region <region>', 'only fill in this region (default: any)')\n .option('--use-case <lane>', 'lane to buy on: actions or sandbox (default: actions)')\n .option('--expires-in <hours>', 'cancel after this many hours (default: standing)'),\n ).action(async (opts: CommonOpts & { size: string; price: string; per?: string; region?: string; useCase?: string; expiresIn?: string }) => {\n try {\n const result = await (await client(opts)).post<{ bid: MarketBid }>(\n '/api/v1/market/bids',\n bidBody(opts),\n );\n output(opts, result, (r) => {\n console.log(`bid placed ${pc.cyan(r.bid.id)}`);\n console.log(formatBidRow(r.bid));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('cancel-bid')\n .description('Cancel an open standing bid')\n .argument('<bid-id>', 'bid ID'),\n ).action(async (bidId: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ bid: MarketBid }>(\n `/api/v1/market/bids?id=${encodeURIComponent(bidId)}`,\n );\n output(opts, result, (r) => console.log(`cancelled ${pc.cyan(r.bid.id)}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('purchases')\n .description('What the market ran for you: seller, price, duration, and cost, newest first')\n .option('--limit <n>', 'purchases per page (max 200, default 50)')\n .option('--cursor <cursor>', 'continue from a previous page'),\n ).action(async (opts: CommonOpts & { limit?: string; cursor?: string }) => {\n try {\n const page = await (await client(opts)).get<{\n purchases: MarketPurchase[];\n nextCursor: string | null;\n }>('/api/v1/market/purchases', { limit: opts.limit, cursor: opts.cursor });\n output(opts, page, (p) => {\n if (p.purchases.length === 0) {\n console.log('No market purchases yet.');\n return;\n }\n for (const row of p.purchases) console.log(formatPurchaseRow(row));\n if (p.nextCursor) console.log(pc.dim(`more: --cursor ${p.nextCursor}`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('credits')\n .description('Prepaid market credits: available balance and reserved holds'),\n ).action(async (opts: CommonOpts) => {\n try {\n const balance = await (await client(opts)).get<MarketCreditBalance>(\n '/api/v1/billing/balance',\n );\n output(opts, balance, (b) => console.log(formatCredits(b)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('ledger')\n .description('Credit history, newest first: top-ups, charges, holds, refunds')\n .option('--limit <n>', 'entries per page (max 200, default 50)')\n .option('--cursor <cursor>', 'continue from a previous page'),\n ).action(async (opts: CommonOpts & { limit?: string; cursor?: string }) => {\n try {\n const page = await (await client(opts)).get<{\n entries: MarketLedgerEntry[];\n nextCursor: string | null;\n }>('/api/v1/billing/ledger', { limit: opts.limit, cursor: opts.cursor });\n output(opts, page, (p) => {\n if (p.entries.length === 0) {\n console.log('No credit activity yet — add credit with `compute credits topup <usd>`.');\n return;\n }\n for (const entry of p.entries) console.log(formatLedgerRow(entry));\n if (p.nextCursor) console.log(pc.dim(`more: --cursor ${p.nextCursor}`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('topup')\n .description('Buy prepaid credits — prints a Stripe checkout link to pay in your browser')\n .argument('<usd>', 'amount in USD (e.g. 50)'),\n ).action(async (amount: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<{ url: string; amountMicroUsd: number }>(\n '/api/v1/billing/topups',\n { amountUsd: parseTopupAmount(amount) },\n );\n output(opts, result, (r) => {\n console.log(`Pay ${formatMoney(r.amountMicroUsd / MICRO_USD)} at:`);\n console.log(r.url);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n // ── Seller credential ───────────────────────────────────────────────────\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 credits` — the org's prepaid credit, which managed accounts bill\n * from: balance, ledger and top-ups over `/api/v1/billing/*`. These lived\n * under `compute market`; credit is every org's now, so they have their own\n * top-level home (`compute market credits|ledger|topup` stay, hidden).\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { client, fail, output, usageErrorOutput, type CommonOpts } from './actions.js';\nimport {\n formatCredits,\n formatLedgerRow,\n parseTopupAmount,\n type MarketCreditBalance,\n type MarketLedgerEntry,\n} from './market.js';\nimport { formatMoney } from './rate-display.js';\n\nconst MICRO_USD = 1_000_000;\n\n/** POST /api/v1/billing/topups. `creditMicroUsd`/`feeBps` arrive from platforms with the top-up fee. */\ninterface TopupCheckout {\n url: string | null;\n amountMicroUsd: number;\n creditMicroUsd?: number;\n feeBps?: number;\n}\n\nexport function registerCreditsCommands(program: Command): void {\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 const credits = common(\n program\n .command('credits')\n .description('Your prepaid credit — managed accounts bill from it: balance, ledger, top-ups')\n .configureOutput({ outputError: usageErrorOutput }),\n ).action(async (opts: CommonOpts) => {\n try {\n const balance = await (await client(opts)).get<MarketCreditBalance>('/api/v1/billing/balance');\n output(opts, balance, (b) => console.log(formatCredits(b)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n credits\n .command('ledger')\n .description('Credit history, newest first: top-ups, grants, holds, charges, refunds')\n .option('--limit <n>', 'entries per page (max 200, default 50)')\n .option('--cursor <cursor>', 'continue from a previous page'),\n ).action(async (opts: CommonOpts & { limit?: string; cursor?: string }) => {\n try {\n const page = await (await client(opts)).get<{ entries: MarketLedgerEntry[]; nextCursor: string | null }>(\n '/api/v1/billing/ledger',\n { limit: opts.limit, cursor: opts.cursor },\n );\n output(opts, page, (p) => {\n if (p.entries.length === 0) {\n console.log('No credit activity yet — add credit with `compute credits topup <usd>`.');\n return;\n }\n for (const entry of p.entries) console.log(formatLedgerRow(entry));\n if (p.nextCursor) console.log(pc.dim(`more: --cursor ${p.nextCursor}`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n credits\n .command('topup')\n .description('Add credit — prints a Stripe checkout link to pay in your browser (owner/admin)')\n .argument('<usd>', 'amount to pay in USD (e.g. 50)'),\n ).action(async (amount: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<TopupCheckout>('/api/v1/billing/topups', {\n amountUsd: parseTopupAmount(amount),\n });\n output(opts, result, (r) => {\n const pay = formatMoney(r.amountMicroUsd / MICRO_USD);\n if (r.creditMicroUsd !== undefined && r.feeBps !== undefined && r.feeBps > 0) {\n console.log(`Pay ${pay} for ${formatMoney(r.creditMicroUsd / MICRO_USD)} of credit (${r.feeBps / 100}% top-up fee) at:`);\n } else {\n console.log(`Pay ${pay} at:`);\n }\n console.log(r.url ?? pc.dim('(no checkout link returned)'));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * Flags given to a parent command reach its subcommand.\n *\n * Several groups declare the shared flags (--org, --api-key, --base-url,\n * --json, …) on the parent as well as on each subcommand, so\n * `compute credits --org team-b topup 50` parses: but commander stores\n * `--org` on `credits`, and `topup`'s action only reads its own options —\n * the checkout would go to the active org instead of team-b. This hook, on\n * the root program, runs before every action and copies each option a parent\n * received (on the command line or from env) onto the subcommand that\n * declares the same option and didn't get it itself. The subcommand's own\n * value always wins, and the nearest parent wins over farther ones.\n */\n\nimport type { Command } from 'commander';\n\nconst GIVEN = new Set(['cli', 'env']);\n\nexport function inheritParentOptions(program: Command): Command {\n return program.hook('preAction', (_hooked, actionCommand) => {\n const declared = new Set(actionCommand.options.map((option) => option.attributeName()));\n for (let parent = actionCommand.parent; parent; parent = parent.parent) {\n for (const [key, value] of Object.entries(parent.opts())) {\n if (!declared.has(key) || value === undefined) continue;\n if (!GIVEN.has(parent.getOptionValueSource(key) ?? '')) continue;\n if (GIVEN.has(actionCommand.getOptionValueSource(key) ?? '')) continue;\n actionCommand.setOptionValueWithSource(key, value, parent.getOptionValueSource(key)!);\n }\n }\n });\n}\n","/**\n * `compute instances` (alias `compute sandboxes`) — drive instances 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 * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as readline from 'node:readline';\nimport { Readable } from 'node:stream';\nimport { Command, Option } from 'commander';\nimport pc from 'picocolors';\nimport * as tar from 'tar';\nimport { ActionsApiError, 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';\nimport {\n clearCurrentInstance,\n dirKey,\n isUuid,\n orgKey,\n readFileCurrent,\n resolveInstanceId,\n setCurrentInstance,\n shortId,\n} from './current-instance.js';\nimport { formatMoney, formatRateAllUnits, formatUsd, formatUsdPer, rateAllUnits } from './rate-display.js';\nimport { parseMaxPrice, registerSettingsCommands } from './settings.js';\nimport { registerBillingCommands } from './sandbox-billing.js';\nimport { syncOnce, sourceFilter, type SyncPlan } from './sync.js';\nimport { localTree } from './sync-fs.js';\nimport { creationClient } from './onboarding.js';\nimport { execute, execCommand, execTimeout, type ExecOpts } from './exec.js';\n\n// ─── Wire types (mirror benchmarks-platform lib/sandboxes) ──────────────────\n// The definitions moved to @computesdk/platform in cli 2.x — re-exported here\n// for one release so the CLI's public names don't change.\nexport type {\n CommandResult,\n FileEntry,\n PathView,\n SandboxCost,\n SandboxDetail,\n SandboxProcess,\n SandboxProcessStatus,\n SandboxSnapshot,\n SandboxSummary,\n} from '@computesdk/platform';\nimport type {\n PathView,\n SandboxDetail,\n SandboxProcess,\n SandboxProcessStatus,\n SandboxSnapshot,\n SandboxSummary,\n} from '@computesdk/platform';\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\n/** `$0.12/h` — the compact one-unit rate the instance line shows. */\nfunction shortRate(rate: { usd: number; per: string }): string {\n return `${formatUsd(rateAllUnits(rate).perHour)}/h`;\n}\n\n/**\n * Who the sandbox runs under: a ComputeSDK managed account (billed from\n * prepaid credit) or the org's own BYOK key (billed by the provider).\n */\nexport function placementLane(source: string | undefined): string {\n if (source === 'house') return 'managed';\n if (source === 'own-key') return 'BYOK';\n return source ?? '—';\n}\n\n/** Where a placement's compute is billed. */\nfunction billedBy(source: string | undefined, provider: string): string {\n if (source === 'house') return 'billed from your ComputeSDK credit';\n if (source === 'own-key') return `billed by ${provider} to your account`;\n return 'billed from your ComputeSDK credit';\n}\n\n/** `2026-10-27 14:02` — a timestamp in the viewer's local time. */\nfunction formatLocalTime(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n const p = (n: number) => String(n).padStart(2, '0');\n return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;\n}\n\n/**\n * The default instance view: one line of ID, status, provider, size and\n * rate, plus a label line when one is set. `--verbose` adds everything the\n * old output printed (providerSandboxId, image, full placement, command\n * count, attach). `attach` never leaves `--json`.\n */\nfunction printSandbox(s: SandboxSummary, verbose = false): void {\n const p = s.placement;\n console.log(\n `${pc.cyan(s.id)} ${s.status} ${p?.box?.provider ?? s.provider ?? '—'} · ${placementLane(p?.source)} ${p?.size ?? '—'} ${p ? shortRate(p.rate) : '—'}`,\n );\n if (s.label) {\n console.log(` label: ${s.label} created: ${formatLocalTime(s.createdAt)}`);\n }\n if (s.destroyError) console.log(` destroyError: ${pc.red(s.destroyError)}`);\n if (!verbose) return;\n console.log(` providerSandboxId: ${s.providerSandboxId ?? '—'} commands: ${s.commandCount}`);\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 (p) {\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 const provider = p.box?.provider ?? s.provider ?? 'the provider';\n console.log(\n ` placement: ${placementLane(p.source)}${box} rate: ${formatUsdPer(p.rate)} ${pc.dim(billedBy(p.source, provider))}`,\n );\n }\n const attach = 'attach' in s ? (s as SandboxDetail).attach : undefined;\n if (attach !== undefined) {\n console.log(\n attach === null\n ? ' attach: none (managed account or platform provider — drive it through ComputeSDK)'\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: 'house' | 'own-key' | 'market';\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\n\nconst usdAmount = (n: number | undefined): string => (n === undefined ? '—' : formatMoney(n));\n\n/** A walk entry as people read it: `daytona (managed)`, `e2b (BYOK)`. */\nfunction walkEntry(entry: string): string {\n if (entry.startsWith('managed/')) return `${entry.slice('managed/'.length)} (managed)`;\n if (entry === 'market' || entry.startsWith('market:')) return entry;\n return `${entry} (BYOK)`;\n}\n\n/** Why a quote can't place, in the caller's terms. */\nfunction quoteRefusal(q: SandboxQuoteWire): string {\n switch (q.reason) {\n case 'insufficient_credits':\n return `not enough ComputeSDK credit for the hold (need ${usdAmount(q.requiredHoldUsd)}, have ${usdAmount(q.creditBalanceUsd)})`;\n case 'no_provider_configured':\n return 'nothing in the router can place this size: no live managed account prices it, and no BYOK key covers it';\n default:\n return q.reason ?? 'nothing in the router can place it';\n }\n}\n\n/**\n * Where a create would land and what it would cost: the provider and whether\n * it's a managed account (billed from credit, with a hold) or your BYOK key\n * (billed by the provider), the rate, and the router's walk.\n */\nfunction printQuote(q: SandboxQuoteWire, timeoutMs?: string): void {\n const row = (label: string, value: string) => console.log(`${label.padEnd(10)} ${value}`);\n if (!q.ok || !q.placement) {\n row('Lands on', pc.red(`nowhere — ${quoteRefusal(q)}`));\n if (q.reason === 'insufficient_credits' && q.topUpPath) row('Top up', q.topUpPath);\n } else {\n const p = q.placement;\n const provider = p.box?.provider ?? p.provider;\n row('Lands on', `${provider} · ${placementLane(p.source)} · ${p.size ?? p.box?.sizeName ?? 'custom size'}`);\n row('Rate', q.rateUsd ? formatRateAllUnits(q.rateUsd) : q.rate ? formatUsdPer(q.rate) : '—');\n if (p.source === 'own-key') {\n row('Billing', `billed by ${provider} to your account`);\n } else if (q.requiredHoldUsd !== undefined) {\n const timeout = timeoutMs !== undefined ? ` for ${timeoutMs}ms` : ' for the timeout';\n row('Billing', `from your ComputeSDK credit: ${usdAmount(q.requiredHoldUsd)} held${timeout}, settled at actual runtime (balance ${usdAmount(q.creditBalanceUsd)})`);\n } else {\n // No hold quoted: the estimate is just that.\n row('Billing', `from your ComputeSDK credit (balance ${usdAmount(q.creditBalanceUsd)})`);\n if (q.estimatedCostUsd !== undefined) row('Estimate', usdAmount(q.estimatedCostUsd));\n }\n }\n row('Tries', q.providerOrder.map(walkEntry).join(' → ') || '—');\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 COMMAND_LEAD_OPTS: LeadOptSpec[] = [\n ...AUTH_LEAD_OPTS,\n { aliases: ['--cwd'], key: 'cwd', flag: 'value' },\n { aliases: ['-e', '--env'], key: 'env', flag: 'repeat' },\n { aliases: ['--timeout-ms'], key: 'timeoutMs', flag: 'value' },\n];\n\nconst EXEC_LEAD_OPTS: LeadOptSpec[] = [\n ...COMMAND_LEAD_OPTS,\n { aliases: ['--timeout'], key: 'timeout', flag: 'value' },\n { aliases: ['--stream'], key: 'stream', flag: 'bool' },\n { aliases: ['-d', '--detach'], key: 'detach', flag: 'bool' },\n];\n\nconst SPAWN_LEAD_OPTS: LeadOptSpec[] = [\n ...AUTH_LEAD_OPTS,\n { aliases: ['-q', '--quiet'], key: 'quiet', flag: 'bool' },\n { aliases: ['--cwd'], key: 'cwd', flag: 'value' },\n { aliases: ['-e', '--env'], key: 'env', flag: 'repeat' },\n { aliases: ['--stdin'], key: 'stdin', flag: 'bool' },\n];\n\nconst SERVE_LEAD_OPTS: LeadOptSpec[] = [\n ...SPAWN_LEAD_OPTS,\n { aliases: ['--port'], key: 'port', flag: 'value' },\n { aliases: ['--timeout-ms'], key: 'timeoutMs', flag: 'value' },\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\n// ─── Output modes and current-instance resolution ────────────────────────────\n\ntype QuietOpts = CommonOpts & { quiet?: boolean; verbose?: boolean; browser?: boolean };\n\n/** `--quiet` and `--json` together is a usage error. */\nfunction checkQuietJson(opts: QuietOpts): void {\n if (opts.quiet && opts.json) throw new Error('--quiet and --json cannot be combined');\n}\n\n/** --quiet prints only `quietLine(data)`; otherwise the --json/human path. */\nfunction emitResult<T>(\n opts: QuietOpts,\n data: T,\n quietLine: (d: T) => string,\n render: (d: T) => void,\n): void {\n if (opts.quiet) {\n console.log(quietLine(data));\n return;\n }\n output(opts, data, render);\n}\n\nconst NO_INSTANCE_HINT =\n 'No sandbox selected. Run `compute new`, pass an ID, or run `compute use <id>`.';\n\ninterface ResolvedSandbox {\n id: string;\n /** Clears the stored pick when the API proves it stale (404), and says so. */\n clearStale: (error: unknown) => void;\n}\n\n/**\n * Resolves the instance a command runs on: explicit UUID > COMPUTE_INSTANCE >\n * this directory's stored pick. When the pick was implicit a dim line names\n * it on stderr so a human sees which box the command hit (silent in\n * --json/--quiet so scripts stay clean).\n */\nfunction resolveSandbox(argId: string | undefined, opts: QuietOpts): ResolvedSandbox {\n const r = resolveInstanceId(argId, opts);\n if (!r) throw new Error(NO_INSTANCE_HINT);\n if (r.source !== 'argument' && !opts.json && !opts.quiet) {\n console.error(\n pc.dim(\n `instance ${shortId(r.id)} (${r.source === 'env' ? 'COMPUTE_INSTANCE' : `current for ${r.dir}`})`,\n ),\n );\n }\n const org = orgKey(opts);\n return {\n id: r.id,\n clearStale: (error) => {\n if (\n r.source === 'file' &&\n error instanceof ActionsApiError &&\n error.status === 404 &&\n readFileCurrent(org) === r.id\n ) {\n clearCurrentInstance(org);\n console.error(pc.dim(`cleared stale current instance ${shortId(r.id)}`));\n }\n },\n };\n}\n\n/** The positional-id rule: only a UUID may occupy the `[sandboxId]` slot. */\nfunction requireUuidOrImplicit(argId: string | undefined, opts: QuietOpts): ResolvedSandbox {\n if (argId !== undefined && !isUuid(argId)) {\n throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n }\n return resolveSandbox(argId, opts);\n}\n\n/**\n * `[resourceOrSandboxId] [resourceId]` commands (logs/wait/kill/stdin/\n * close-stdin/snapshot-delete): one positional is the resource on the\n * implicit instance — UUID-shaped or not; two positionals are always\n * `<sandboxId> <resourceId>`.\n */\nfunction resolveTwoArgTarget(\n argId: string | undefined,\n resourceId: string | undefined,\n opts: QuietOpts,\n label: string,\n): { resolved: ResolvedSandbox; resource: string } {\n if (resourceId === undefined) {\n if (argId === undefined) throw new Error(`missing ${label}`);\n return { resolved: resolveSandbox(undefined, opts), resource: argId };\n }\n if (argId !== undefined && !isUuid(argId)) {\n throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n }\n return { resolved: resolveSandbox(argId, opts), resource: resourceId };\n}\n\n// ─── create/run shared flags ─────────────────────────────────────────────────\n\n/** The create options `create` and `run` share — declared once. */\nfunction addCreateFlags(c: Command): Command {\n return c\n .option('--provider <names>', 'place only on these providers, through your router (its BYOK mode and order), e.g. daytona or daytona,e2b')\n .option('--byok', 'use only your own keys for this create')\n .option('--managed', 'use only ComputeSDK managed accounts for this create')\n // Pre-router: walk exactly these BYOK providers. --provider + --byok covers it.\n .addOption(new Option('--order <providers>').hideHelp())\n .option('--size <size>', 'platform size: small (1 vCPU/2 GiB), medium, large, xlarge, 2xlarge (16/32 GiB), 3xlarge (32/128 GiB); 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 .addOption(new Option('--max-price <usd/unit>').hideHelp())\n .addOption(new Option('--max-price-per <unit>').hideHelp())\n .addOption(new Option('--market').hideHelp())\n .addOption(new Option('--order-type <type>').hideHelp())\n .option('--timeout-ms <ms>', 'sandbox timeout in ms (provider minimums apply, e.g. blaxel ≥5m)')\n .option('--secret <name>', 'vault secret name to inject (repeatable)', (v, a: string[]) => a.concat(v), [] as string[]);\n}\n\ninterface CreateFlagOpts {\n order?: string; provider?: string; byok?: boolean; managed?: boolean; 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\n/** `--provider daytona,e2b` → ['daytona', 'e2b']; empty is a usage error. */\nfunction providerNames(value: string): string[] {\n const names = value.split(',').map((name) => name.trim()).filter(Boolean);\n if (names.length === 0) throw new Error(`--provider \"${value}\" names no providers.`);\n return names;\n}\n\n/** `--byok` → the router's BYOK mode \"only\"; `--managed` → \"off\"; neither → the router's own. */\nfunction accountMode(opts: { byok?: boolean; managed?: boolean }): 'only' | 'off' | undefined {\n if (opts.byok && opts.managed) throw new Error('--byok and --managed are mutually exclusive.');\n return opts.byok ? 'only' : opts.managed ? 'off' : undefined;\n}\n\n/** The POST /api/v1/sandboxes body `create` and `run` share. */\nfunction buildCreateBody(opts: CreateFlagOpts): Record<string, unknown> {\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.provider && opts.order) {\n throw new Error('--provider narrows your router; --order skips it. Pass one.');\n }\n if (opts.provider) body.only = providerNames(opts.provider);\n const mode = accountMode(opts);\n if (mode !== undefined) {\n if (opts.order) throw new Error('--byok/--managed apply to your router; --order skips it.');\n body.byok = mode;\n }\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 return body;\n}\n\n/** `1h` / `30m` / `90s` — compact timeout text for the detach summary. */\nfunction fmtTimeout(ms: number): string {\n if (ms % 3_600_000 === 0) return `${ms / 3_600_000}h`;\n if (ms % 60_000 === 0) return `${ms / 60_000}m`;\n if (ms % 1_000 === 0) return `${ms / 1_000}s`;\n return `${ms}ms`;\n}\n\n/** Mirrors DEFAULT_SANDBOX_TIMEOUT_MS in benchmarks-platform lib/sandboxes/acquire.ts. */\nconst PLATFORM_DEFAULT_TIMEOUT_MS = 30 * 60_000;\n\ntype ListOpts = {\n status?: string;\n customerOnly?: boolean;\n search?: string;\n sort?: string;\n direction?: string;\n limit?: string;\n cursor?: string;\n};\n\nconst LIST_SORTS = ['created', 'name', 'cost', 'runtime'];\n\n/** The `GET /api/v1/sandboxes` query for `compute instances list`. */\nexport function listQuery(opts: ListOpts): Record<string, string | undefined> {\n if (opts.sort !== undefined && !LIST_SORTS.includes(opts.sort)) {\n throw new Error(`--sort must be one of ${LIST_SORTS.join(', ')}`);\n }\n if (opts.direction !== undefined && opts.direction !== 'asc' && opts.direction !== 'desc') {\n throw new Error('--direction must be asc or desc');\n }\n return {\n status: opts.status,\n customerOnly: opts.customerOnly ? 'true' : undefined,\n q: opts.search,\n sort: opts.sort,\n direction: opts.direction,\n limit: opts.limit,\n cursor: opts.cursor,\n };\n}\n\n/** GET /api/v1/sandboxes/options. */\ninterface SandboxOptionsWire {\n byokMode: 'off' | 'first' | 'fallback' | 'only';\n /** How managed rows are ordered, and the size that order is for (absent from older servers). */\n strategy?: 'computesdk' | 'cheapest' | 'custom';\n size?: string;\n options: Array<\n | { account: 'managed'; provider: string; sizes: { name: string; label: string; rate: { usd: number; per: string } | null }[] }\n | { account: 'byok'; provider: string; region: string | null; ready: boolean }\n >;\n}\n\nconst STRATEGY_LINE: Record<NonNullable<SandboxOptionsWire['strategy']>, string> = {\n computesdk: \"ComputeSDK's recommended order\",\n cheapest: 'cheapest first',\n custom: 'your own order',\n};\n\nconst BYOK_MODE_LINE: Record<SandboxOptionsWire['byokMode'], string> = {\n off: 'managed accounts only',\n first: 'your keys first, then managed accounts',\n fallback: 'managed accounts first, then your keys',\n only: 'your keys only',\n};\n\n/**\n * Everything a create can land on, in the router's order: managed accounts\n * with a price per size (billed from credit), BYOK providers (billed by the\n * provider). The first usable row is where a plain `compute new` goes.\n */\nfunction printSandboxOptions(o: SandboxOptionsWire): void {\n if (o.options.length === 0) {\n console.log('Nothing to create on yet: no managed account is live and no BYOK key is set up.');\n return;\n }\n const sizeNames = [...new Set(o.options.flatMap((row) => (row.account === 'managed' ? row.sizes.map((size) => size.name) : [])))]\n .filter((name) => name !== 'default');\n const order = ['small', 'medium', 'large', 'xlarge'];\n sizeNames.sort((a, b) => order.indexOf(a) - order.indexOf(b));\n const providerWidth = Math.max(8, ...o.options.map((row) => (row.account === 'byok' && row.region ? `${row.provider}:${row.region}` : row.provider).length));\n const cell = (text: string) => text.padEnd(11);\n console.log(pc.dim(`${'Provider'.padEnd(providerWidth)} ${'Account'.padEnd(8)} ${sizeNames.map(cell).join(' ')}`.trimEnd()));\n let first: string | null = null;\n for (const row of o.options) {\n const name = row.account === 'byok' && row.region ? `${row.provider}:${row.region}` : row.provider;\n let detail: string;\n let usable: boolean;\n if (row.account === 'managed') {\n const fixed = row.sizes.length === 1 && row.sizes[0]!.name === 'default';\n usable = row.sizes.some((size) => size.rate !== null);\n detail = fixed\n ? row.sizes[0]!.rate ? `default size ${shortRate(row.sizes[0]!.rate)}` : pc.dim('not priced yet')\n : sizeNames.map((size) => {\n const priced = row.sizes.find((entry) => entry.name === size)?.rate;\n return cell(priced ? shortRate(priced) : '—');\n }).join(' ').trimEnd();\n } else {\n usable = row.ready;\n detail = row.ready ? pc.dim(`billed by ${row.provider} to your account`) : pc.dim('key not tested — compute byok verify ' + row.provider);\n }\n if (usable && first === null) first = row.provider;\n console.log(`${name.padEnd(providerWidth)} ${(row.account === 'managed' ? 'managed' : 'BYOK').padEnd(8)} ${detail}`);\n }\n console.log('');\n console.log(`Router: ${BYOK_MODE_LINE[o.byokMode]} (BYOK ${o.byokMode}).`);\n if (o.strategy !== undefined && o.byokMode !== 'only') {\n const size = o.strategy === 'cheapest' && o.size !== undefined ? ` at ${o.size}` : '';\n console.log(`Managed accounts: ${STRATEGY_LINE[o.strategy]}${size} — change with compute sandboxes settings set --routing <computesdk|cheapest|providers>.`);\n }\n if (first !== null) console.log(pc.dim(`A plain \\`compute new\\` lands on ${first}. Pick one: compute new --${first} --size <size>`));\n}\n\nasync function showSandboxOptions(opts: CommonOpts): Promise<void> {\n const c = await client(opts);\n output(opts, await c.get<SandboxOptionsWire>('/api/v1/sandboxes/options'), printSandboxOptions);\n}\n\n/**\n * The `create` flags and action, on `compute sandboxes create` and on the\n * `compute new` shorthand. With `providerShorthand`, the command's operands\n * — `vercel` or an unknown `--vercel` flag, which commander hands over as\n * operands — name providers, as `--provider` does.\n */\nfunction registerCreate(command: Command, { providerShorthand = false }: { providerShorthand?: boolean } = {}): void {\n addCreateFlags(command)\n .option('--no-use', 'do not mark the new instance as this directory\\'s current instance')\n .option('--no-browser', 'print the sign-in URL instead of opening a browser')\n .option('-q, --quiet', 'print only the new instance ID')\n .option('--verbose', 'print the full instance details')\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 if (providerShorthand) {\n command\n .option('--org <slug>', 'organization slug for this command (or $COMPUTE_ORG)')\n .option('--list', 'list what you can create on, with prices, instead of creating (= compute sandboxes options)');\n }\n command\n .action(async (...args: unknown[]) => {\n const operands = providerShorthand ? (args[0] as string[]) : [];\n const opts = args[providerShorthand ? 1 : 0] as QuietOpts & CreateFlagOpts & { use?: boolean; list?: boolean };\n try {\n if (opts.list) {\n if (operands.length > 0) throw new Error('--list shows every option; drop the provider names.');\n await showSandboxOptions(opts);\n return;\n }\n checkQuietJson(opts);\n const { providers, project } = splitCreateOperands(operands);\n if (project) await localTree({ root: project }, sourceFilter(project));\n const named = shorthandProviders(providers);\n if (named.length > 0) {\n if (opts.provider) throw new Error('Name providers either as words/flags or with --provider, not both.');\n opts.provider = named.join(',');\n }\n const body = buildCreateBody(opts);\n const c = await creationClient(opts);\n if (!opts.json && !opts.quiet) await previewPlacement(c, opts);\n const res = await c.post<{ sandbox: SandboxDetail }>('/api/v1/sandboxes', body);\n let projectSync: SyncPlan | undefined;\n if (project) {\n try {\n projectSync = await syncOnce(c, { local: project }, { id: res.sandbox.id, remote: '/app' }, opts);\n } catch (error) {\n let destroyed = false;\n try {\n const cleanup = await c.del<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${res.sandbox.id}`);\n destroyed = cleanup.sandbox.status === 'destroyed';\n } catch { /* include the handle for manual cleanup below */ }\n throw new Error(`Initial sync failed for ${res.sandbox.id}: ${error instanceof Error ? error.message : String(error)}. ` +\n (destroyed ? 'The new sandbox was destroyed.' : `Cleanup unconfirmed; run compute destroy ${res.sandbox.id}.`));\n }\n }\n // Commander stores --no-use as `use: false`.\n if (opts.use !== false) {\n setCurrentInstance(res.sandbox.id, orgKey(opts));\n if (!opts.json && !opts.quiet) {\n console.error(pc.dim(`instance ${shortId(res.sandbox.id)} (current for ${dirKey()})`));\n }\n }\n const detail = { ...res.sandbox, ...(projectSync?.snapshot ? { syncSnapshot: projectSync.snapshot } : {}) };\n emitResult(opts, detail, (s) => s.id, (s) => {\n printSandbox(s, opts.verbose);\n if (s.syncSnapshot) console.log(`Snapshot ${s.syncSnapshot.id} retained until ${s.syncSnapshot.expiresAt}.`);\n });\n if (!opts.json && !opts.quiet) printNextSteps(res.sandbox.id, opts, project ? '/app' : undefined);\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n\n/**\n * Before the create (which only returns once the box is up), say where the\n * router will place it: the same quote `compute sandboxes route` prints.\n * It's the router's first choice; if that provider fails at create time the\n * walk moves on, and the created sandbox's line says where it landed. On\n * stderr, and never fatal: a failed quote just skips the line.\n */\nasync function previewPlacement(c: Awaited<ReturnType<typeof client>>, opts: CreateFlagOpts): Promise<void> {\n // --order and the market flags don't walk the router the quote describes.\n if (opts.order || opts.market || opts.orderType || opts.maxPrice) return;\n const mode = accountMode(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 timeoutMs: opts.timeoutMs,\n only: opts.provider === undefined ? undefined : providerNames(opts.provider).join(','),\n byok: mode,\n };\n let quote: SandboxQuoteWire;\n try {\n quote = (await c.get<{ quote: SandboxQuoteWire }>('/api/v1/sandboxes/quote', params)).quote;\n } catch {\n return; // A preview only; the create below reports any real problem.\n }\n if (!quote.ok || !quote.placement) {\n console.error(pc.dim(`→ the router can't place this: ${quoteRefusal(quote)}`));\n return;\n }\n const p = quote.placement;\n const provider = p.box?.provider ?? p.provider;\n console.error(\n pc.dim(`→ placing on ${provider} · ${placementLane(p.source)} · ${p.size ?? p.box?.sizeName ?? 'custom size'} (${billedBy(p.source, provider)}) …`),\n );\n}\n\n/**\n * Suggest commands for the newly selected instance. An explicit ID is needed\n * when --no-use or COMPUTE_INSTANCE prevents it from becoming current.\n * Keep one-off org/base URL flags and leave stdout available to scripts.\n */\nfunction printNextSteps(id: string, opts: { org?: string; baseUrl?: string; use?: boolean }, cwd?: string): void {\n const context = `${opts.org ? ` --org ${opts.org}` : ''}${opts.baseUrl ? ` --base-url ${opts.baseUrl}` : ''}`;\n const target = opts.use === false || (process.env.COMPUTE_INSTANCE && process.env.COMPUTE_INSTANCE !== id) ? ` ${id}` : '';\n const steps: [string, string][] = [\n [`compute exec${target}${context}${cwd ? ` --cwd ${cwd}` : ''} echo hello`, 'run your first command'],\n [`compute list${context}`, 'see your sandboxes'],\n [`compute destroy${target}${context}`, 'stop billing'],\n ];\n const width = Math.max(...steps.map(([command]) => command.length));\n console.error('');\n console.error('Use it:');\n for (const [command, does] of steps) console.error(` ${command.padEnd(width)} ${pc.dim(does)}`);\n console.error(pc.dim('It runs and bills until it times out or is destroyed.'));\n}\n\n/** Explicit path syntax avoids confusing provider names with local folder names. */\nexport function splitCreateOperands(operands: string[]): { providers: string[]; project?: string } {\n const index = operands.findIndex((value) => value === '.' || value === '..' || value.startsWith('./') || value.startsWith('../') || path.isAbsolute(value) || /^[A-Za-z]:[\\\\/]/.test(value));\n if (index === -1) return { providers: operands };\n if (index !== operands.length - 1) throw new Error('Put the local project directory after the providers: compute new e2b ./my-app.');\n return { providers: operands.slice(0, index), project: path.resolve(operands[index]) };\n}\n\n/** `['--vercel', 'e2b']` → `['vercel', 'e2b']`; anything else is a usage error. */\nfunction shorthandProviders(operands: string[]): string[] {\n return operands.map((operand) => {\n const name = operand.startsWith('--') ? operand.slice(2) : operand;\n if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {\n throw new Error(`\"${operand}\" isn't a provider name — use e.g. \\`compute new vercel\\` or \\`compute new --vercel\\`.`);\n }\n return name;\n });\n}\n\nexport function registerSandboxesCommands(program: Command): void {\n const cmd = program\n .command('instances')\n .alias('sandboxes')\n .alias('sbx')\n .description('Create and drive compute instances through the platform')\n .enablePositionalOptions()\n .configureOutput({ outputError: usageErrorOutput });\n\n registerCreate(\n cmd\n .command('create')\n .description('Create a sandbox through your Sandboxes router (`compute sandboxes route` shows where it lands)'),\n );\n\n // `compute new` — the short form of `compute sandboxes create`. Providers\n // narrow the router like --provider, as words or as flags:\n // `compute new vercel` / `compute new --vercel` = `--provider vercel`.\n registerCreate(\n program\n .command('new')\n .description('Create a sandbox; compute new e2b . creates on e2b and syncs a local project to /app')\n .argument('[providersAndPath...]', 'provider names followed by an optional local directory (e.g. e2b ./my-app)')\n .allowUnknownOption()\n .configureOutput({ outputError: usageErrorOutput }),\n { providerShorthand: true },\n );\n\n registerSandboxOperations(cmd);\n\n // Each spelling needs its own Command (Commander stores parser state and\n // its parent on the object); both sets use the registrations below.\n const shortcuts = new Command().enablePositionalOptions();\n registerSandboxOperations(shortcuts);\n const rootCommands = new Set(['list', 'get', 'use', 'destroy', 'run', 'serve', 'exec', 'spawn', 'ps', 'logs', 'kill', 'wait', 'cp', 'url']);\n for (const sub of shortcuts.commands) {\n if (rootCommands.has(sub.name())) {\n sub.configureOutput({ outputError: usageErrorOutput });\n program.addCommand(sub);\n }\n }\n}\n\nfunction registerSandboxOperations(cmd: Command): void {\n // `options`: everything a create can land on, with prices, in router order.\n cmd\n .command('options')\n .description('List what you can create sandboxes on: managed accounts with prices per size, and your BYOK providers, in router order')\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 try {\n await showSandboxOptions(opts);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n // `route`: where a create would land under the Sandboxes router, and what\n // it costs — managed (ComputeSDK credit) or BYOK (billed by the provider).\n // `quote` is its pre-router name, kept hidden for existing scripts; the\n // market-only flags are accepted but stay out of help.\n for (const name of ['route', 'quote'] as const) {\n const command = cmd\n .command(name, { hidden: name === 'quote' })\n .description('Show where a sandbox create would land, how it is billed, and the price — creates nothing')\n .option('--size <size>', 'platform size: small, medium (default), large, xlarge, 2xlarge (16/32 GiB), 3xlarge (32/128 GiB)')\n .option('--provider <names>', 'only these providers, through your router (e.g. daytona)')\n .option('--byok', 'only your own keys')\n .option('--managed', 'only ComputeSDK managed accounts')\n .option('--cpus <n>', 'CPU cores (raw resources instead of --size)')\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; a managed account holds credit for it')\n .addOption(new Option('--order-type <type>').hideHelp())\n .addOption(new Option('--market').hideHelp())\n .addOption(new Option('--max-price <usd/unit>').hideHelp())\n .addOption(new Option('--max-price-per <unit>').hideHelp())\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response');\n command.action(async (opts: CommonOpts & {\n size?: string; provider?: string; byok?: boolean; managed?: boolean; 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 only: opts.provider === undefined ? undefined : providerNames(opts.provider).join(','),\n byok: accountMode(opts),\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\n cmd\n .command('list')\n .description('List sandboxes')\n .option('--status <status>', 'active (not destroyed) | creating | running | destroyed')\n .option('--customer-only', 'exclude idle platform sandboxes (warm pool, CI sync, snapshot builds); Actions job sandboxes stay')\n .option('--search <text>', 'match label, id, provider, provider sandbox id or product (Sandboxes, Actions)')\n .option('--sort <column>', 'created (default, newest first) | name | cost | runtime')\n .option('--direction <dir>', 'asc | desc (default: asc for name, desc for the others)')\n .option('--limit <n>', 'page size')\n .option('--cursor <cursor>', 'page cursor from a previous response (pass the same --sort and --direction)')\n .option('-q, --quiet', 'print only instance IDs, one per line')\n .option('--verbose', 'print the full instance details')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (opts: QuietOpts & ListOpts) => {\n try {\n checkQuietJson(opts);\n const c = await client(opts);\n const res = await c.get<{ sandboxes: SandboxSummary[]; nextCursor: string | null }>(\n '/api/v1/sandboxes',\n listQuery(opts),\n );\n emitResult(\n opts,\n res,\n (page) => page.sandboxes.map((s) => s.id).join('\\n'),\n (page) => {\n page.sandboxes.forEach((s) => printSandbox(s, opts.verbose));\n if (page.nextCursor) console.log(pc.dim(`nextCursor: ${page.nextCursor}`));\n },\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('--verbose', 'print the full instance details')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (argId: string | undefined, opts: QuietOpts) => {\n try {\n checkQuietJson(opts);\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.get<{ sandbox: SandboxDetail }>(`/api/v1/sandboxes/${resolved.id}`);\n output(opts, res.sandbox, (s) => printSandbox(s, opts.verbose));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('use [sandboxId]')\n .description('Show or set this directory\\'s current instance (COMPUTE_INSTANCE always wins)')\n .option('--clear', 'forget this directory\\'s current instance')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (argId: string | undefined, opts: QuietOpts & { clear?: boolean }) => {\n try {\n const org = orgKey(opts);\n if (opts.clear) {\n const prev = clearCurrentInstance(org);\n output(opts, { cleared: prev ?? null }, () =>\n console.log(\n prev\n ? `forgot ${shortId(prev)} (was current for ${dirKey()})`\n : 'nothing to forget',\n ),\n );\n return;\n }\n if (argId === undefined) {\n const r = resolveInstanceId(undefined, opts);\n output(opts, { id: r?.id ?? null, source: r?.source ?? null }, () => {\n if (!r) console.log(NO_INSTANCE_HINT);\n else {\n const where =\n r.source === 'env' ? 'COMPUTE_INSTANCE' : `current for ${r.dir}`;\n console.log(`instance ${shortId(r.id)} (${where})`);\n }\n });\n return;\n }\n if (!isUuid(argId)) {\n throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n }\n const c = await client(opts);\n const res = await c.get<{ sandbox: SandboxDetail }>(`/api/v1/sandboxes/${argId}`);\n if (res.sandbox.status === 'destroyed') {\n throw new Error(`instance ${shortId(argId)} is destroyed — pick a running instance`);\n }\n setCurrentInstance(argId, org);\n output(opts, { id: argId, dir: dirKey() }, () =>\n console.log(`instance ${shortId(argId)} (current for ${dirKey()})`),\n );\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 (argId: string | undefined, opts: QuietOpts) => {\n try {\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.del<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${resolved.id}`)\n .catch((e) => { resolved.clearStale(e); throw e; });\n // Never leave a dead instance as this directory's current pick.\n const org = orgKey(opts);\n if (readFileCurrent(org) === resolved.id) {\n clearCurrentInstance(org);\n if (!opts.json) {\n console.error(pc.dim(`cleared current instance ${shortId(resolved.id)}`));\n }\n }\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n addCreateFlags(\n cmd\n .command('run [command...]')\n .description(\n 'Create an instance, run a command on it, and tear it down. ' +\n '`run <cmd>` waits and destroys; `--keep` waits and keeps; `-d` returns immediately.',\n ),\n )\n .option('--no-browser', 'print the sign-in URL instead of opening a browser')\n .option('--keep', 'keep the instance after the command exits (it becomes this directory\\'s current instance)')\n .option('-d, --detach', 'start the command and return immediately (instance becomes current)')\n .option('--yes', 'non-interactive: Ctrl-C destroys without asking')\n .option('-q, --quiet', 'with --detach, print only the instance ID')\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 (rawCommand: string[], rawOpts: QuietOpts & CreateFlagOpts & { keep?: boolean; detach?: boolean; yes?: boolean }) => {\n let opts = rawOpts;\n try {\n checkQuietJson(opts);\n if (opts.keep && opts.detach) throw new Error('--keep and --detach are mutually exclusive.');\n const lead = takeLeadingOptions(rawCommand, COMMAND_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 await runInstanceCommand(command, opts);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('serve [sandboxId] [command...]')\n .description('Start a server, wait for its port to listen publicly, and print the URL')\n .option('--port <n>', 'the TCP port the server listens on (required)')\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('--timeout-ms <ms>', 'give up waiting for the port after this (default 120000)')\n .option('-q, --quiet', 'print only the URL')\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 (argId: string | undefined, rawCommand: string[], rawOpts: QuietOpts & { port: string; cwd?: string; env?: string[]; timeoutMs?: string }) => {\n let opts = rawOpts;\n try {\n checkQuietJson(opts);\n if (argId !== undefined && !isUuid(argId)) {\n rawCommand.unshift(argId);\n argId = undefined;\n }\n const lead = takeLeadingOptions(rawCommand, SERVE_LEAD_OPTS);\n opts = mergeLeadOpts(rawOpts, lead.inline);\n const command = lead.command;\n if (command.length === 0) throw new Error('missing command to serve');\n if (opts.port === undefined) throw new Error('--port is required');\n const port = Number(opts.port);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error('--port must be an integer between 1 and 65535');\n }\n const resolved = resolveSandbox(argId, opts);\n await serveInstanceCommand(resolved.id, command, port, opts);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('exec [sandboxId] [command...]')\n .description('Run a shell command or argv in a sandbox; --stream follows output, --detach returns a job ID')\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('--timeout <seconds>', 'command timeout in seconds (0: no command time limit)')\n .option('--timeout-ms <ms>', 'command timeout in ms (legacy spelling)')\n .option('--stream', 'print stdout and stderr while the command runs')\n .option('-d, --detach', 'start a background process and print its job ID')\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 (argId: string | undefined, rawCommand: string[], rawOpts: ExecOpts) => {\n let opts = rawOpts;\n try {\n // A non-UUID first positional is the first word of the command, not\n // an ID — `exec ls -la` works on the implicit instance.\n if (argId !== undefined && !isUuid(argId)) {\n rawCommand.unshift(argId);\n argId = undefined;\n }\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 // Reject incompatible options before resolving auth or starting work.\n execTimeout(opts);\n const resolved = resolveSandbox(argId, opts);\n const c = await client(opts);\n await execute(c, resolved.id, {\n command: execCommand(command),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {}),\n }, opts).catch((e) => { resolved.clearStale(e); throw e; });\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('-q, --quiet', 'print only the job ID')\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 (argId: string | undefined, rawCommand: string[], rawOpts: QuietOpts & { cwd?: string; env?: string[]; stdin?: boolean }) => {\n let opts = rawOpts;\n try {\n if (argId !== undefined && !isUuid(argId)) {\n rawCommand.unshift(argId);\n argId = undefined;\n }\n const lead = takeLeadingOptions(rawCommand, SPAWN_LEAD_OPTS);\n opts = mergeLeadOpts(rawOpts, lead.inline);\n checkQuietJson(opts);\n const command = lead.command;\n if (command.length === 0) throw new Error('missing command to spawn');\n const resolved = resolveSandbox(argId, opts);\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${resolved.id}/processes`,\n {\n command: execCommand(command),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {}),\n ...(opts.stdin ? { stdin: true } : {}),\n },\n ).catch((e) => { resolved.clearStale(e); throw e; });\n emitResult(opts, res.process, (p) => p.jobId, 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 (argId: string | undefined, opts: QuietOpts) => {\n try {\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.get<{ processes: SandboxProcess[] }>(\n `/api/v1/sandboxes/${resolved.id}/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 [jobOrSandboxId] [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 (argId: string | undefined, jobId: string | undefined, opts: QuietOpts & { follow?: boolean }) => {\n try {\n // `logs <jobId>` — a non-UUID first positional is the job, not the instance.\n const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, 'jobId');\n const c = await client(opts);\n if (opts.follow) {\n await followProcess(c, resolved.id, job);\n return;\n }\n const res = await c.get<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${resolved.id}/processes/${job}`,\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 [jobOrSandboxId] [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 (argId: string | undefined, jobId: string | undefined, opts: QuietOpts & { timeoutMs?: string }) => {\n try {\n const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, 'jobId');\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${resolved.id}/processes/${job}/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 [jobOrSandboxId] [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 (argId: string | undefined, jobId: string | undefined, opts: QuietOpts & { signal?: string }) => {\n try {\n const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, 'jobId');\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${resolved.id}/processes/${job}/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 [jobOrSandboxId] [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 (argId: string | undefined, jobId: string | undefined, opts: QuietOpts & { data?: string; file?: string; base64?: boolean }) => {\n try {\n const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, 'jobId');\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/${resolved.id}/processes/${job}/stdin`,\n { data, ...(opts.base64 ? { encoding: 'base64' } : {}) },\n );\n output(opts, res, () => console.log(`wrote ${data.length} chars to ${job}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('close-stdin [jobOrSandboxId] [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 (argId: string | undefined, jobId: string | undefined, opts: QuietOpts) => {\n try {\n const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, 'jobId');\n const c = await client(opts);\n const res = await c.post<{ ok: boolean }>(\n `/api/v1/sandboxes/${resolved.id}/processes/${job}/close-stdin`,\n {},\n );\n output(opts, res, () => console.log(`closed stdin on ${job}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('ls [pathOrSandboxId] [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 (argId: string | undefined, path: string | undefined, opts: QuietOpts) => {\n try {\n // `ls /app` — a non-UUID first positional is the path.\n let resolved: ResolvedSandbox;\n let p: string;\n if (argId !== undefined && !isUuid(argId)) {\n if (path !== undefined) throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n resolved = resolveSandbox(undefined, opts);\n p = argId;\n } else {\n resolved = resolveSandbox(argId, opts);\n p = path ?? '/';\n }\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${resolved.id}/files`, {\n path: p,\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 [pathOrSandboxId] [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 (argId: string | undefined, path: string | undefined, opts: QuietOpts) => {\n try {\n let resolved: ResolvedSandbox;\n let p: string;\n if (argId !== undefined && !isUuid(argId)) {\n if (path !== undefined) throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n resolved = resolveSandbox(undefined, opts);\n p = argId;\n } else {\n resolved = resolveSandbox(argId, opts);\n if (path === undefined) throw new Error('missing path');\n p = path;\n }\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${resolved.id}/files`, { path: p });\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 [pathOrSandboxId] [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 (argId: string | undefined, path: string | undefined, opts: QuietOpts & { content?: string; file?: string }) => {\n try {\n let resolved: ResolvedSandbox;\n let p: string;\n if (argId !== undefined && !isUuid(argId)) {\n if (path !== undefined) throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n resolved = resolveSandbox(undefined, opts);\n p = argId;\n } else {\n resolved = resolveSandbox(argId, opts);\n if (path === undefined) throw new Error('missing path');\n p = path;\n }\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/${resolved.id}/files`,\n { path: p, 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 [pathOrSandboxId] [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 (argId: string | undefined, path: string | undefined, opts: QuietOpts) => {\n try {\n let resolved: ResolvedSandbox;\n let p: string;\n if (argId !== undefined && !isUuid(argId)) {\n if (path !== undefined) throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n resolved = resolveSandbox(undefined, opts);\n p = argId;\n } else {\n resolved = resolveSandbox(argId, opts);\n if (path === undefined) throw new Error('missing path');\n p = path;\n }\n const c = await client(opts);\n const res = await c.post<{ path: string }>(`/api/v1/sandboxes/${resolved.id}/files`, {\n path: p,\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 [pathOrSandboxId] [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 (argId: string | undefined, path: string | undefined, opts: QuietOpts) => {\n try {\n let resolved: ResolvedSandbox;\n let p: string;\n if (argId !== undefined && !isUuid(argId)) {\n if (path !== undefined) throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n resolved = resolveSandbox(undefined, opts);\n p = argId;\n } else {\n resolved = resolveSandbox(argId, opts);\n if (path === undefined) throw new Error('missing path');\n p = path;\n }\n const c = await client(opts);\n const res = await c.del<{ path: string; removed: boolean }>(\n `/api/v1/sandboxes/${resolved.id}/files?path=${encodeURIComponent(p)}`,\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('cp <src> <dst>')\n .description('Copy files/dirs between here and an instance — remote side is [id:]/abs/path')\n .option('-q, --quiet', 'print nothing on success')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--org <slug>')\n .option('--json', 'print the raw response')\n .action(async (src: string, dst: string, opts: QuietOpts) => {\n try {\n checkQuietJson(opts);\n await cpCommand(src, dst, opts);\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('-q, --quiet', 'print only the URL (the default)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (argId: string | undefined, opts: QuietOpts & { port: string; protocol?: string }) => {\n try {\n checkQuietJson(opts);\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.get<{ url: string }>(`/api/v1/sandboxes/${resolved.id}/urls`, {\n port: opts.port,\n protocol: opts.protocol,\n });\n emitResult(opts, res, (r) => safeTerm(r.url), (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 (argId: string | undefined, opts: QuietOpts) => {\n try {\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.get<{ snapshots: SandboxSnapshot[] }>(\n `/api/v1/sandboxes/${resolved.id}/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 (argId: string | undefined, opts: QuietOpts & { label?: string }) => {\n try {\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.post<{ snapshot: SandboxSnapshot }>(\n `/api/v1/sandboxes/${resolved.id}/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 [snapOrSandboxId] [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 (argId: string | undefined, snapshotId: string | undefined, opts: QuietOpts) => {\n try {\n const { resolved, resource: snap } = resolveTwoArgTarget(argId, snapshotId, opts, 'snapshotId');\n const c = await client(opts);\n const res = await c.del<{ ok: boolean }>(\n `/api/v1/sandboxes/${resolved.id}/snapshots/${snap}`,\n );\n output(opts, res, () => console.log(`deleted snapshot ${snap}`));\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 // Registered after the --org pass so `settings`, `costs` and their subcommands declare\n // their own full option set (the loop above only covers direct children).\n const nestedCommon = (sub: Command) =>\n sub\n .option('--api-key <key>', 'platform API key (or COMPUTE_API_KEY)')\n .option('--base-url <url>', 'platform base URL')\n .option('--org <slug>', 'organization slug for this command (or $COMPUTE_ORG)')\n .option('--allow-untrusted-host', 'allow non-computesdk.com base URLs')\n .option('--json', 'print the raw response');\n registerSettingsCommands(cmd, 'sandboxes', nestedCommon, { client, fail, output, usageErrorOutput });\n registerBillingCommands(cmd, nestedCommon, { client, fail, output });\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\n// ─── run ─────────────────────────────────────────────────────────────────────\n\n/** The `-d`/`Ctrl-C d` summary — everything needed to re-attach later. */\nfunction printDetachSummary(sandboxId: string, jobId: string, timeoutText: string): void {\n console.log(`instance ${sandboxId} job ${jobId} (running; ${timeoutText})`);\n // Explicit ids: COMPUTE_INSTANCE and the pick can point elsewhere.\n console.log(` follow: compute instances logs ${sandboxId} ${jobId}`);\n console.log(` wait: compute instances wait ${sandboxId} ${jobId}`);\n console.log(` destroy: compute instances destroy ${sandboxId}`);\n}\n\n/** The timeout text for the detach summary: requested, else the platform default. */\nfunction runTimeoutText(opts: { timeoutMs?: string }): string {\n return opts.timeoutMs\n ? `instance timeout: ${fmtTimeout(Number(opts.timeoutMs))}`\n : `instance timeout: ${fmtTimeout(PLATFORM_DEFAULT_TIMEOUT_MS)} (platform default)`;\n}\n\nfunction confirmedDestroyedSandbox(result: { sandbox: SandboxSummary }, id: string): SandboxSummary {\n if (result?.sandbox?.status !== 'destroyed') {\n throw new Error('Teardown was not confirmed; run compute destroy ' + id);\n }\n return result.sandbox;\n}\n\n/**\n * `compute instances run` — create, spawn, stream via repeated `wait` calls\n * (each returns the cumulative buffers; we print only the delta), then destroy\n * in a `finally`. `--keep` skips the destroy, `-d` skips the wait too; both\n * leave the instance as this directory's current one.\n */\nasync function runInstanceCommand(\n command: string[],\n opts: QuietOpts & CreateFlagOpts & { keep?: boolean; detach?: boolean; yes?: boolean },\n): Promise<void> {\n const startedAt = Date.now();\n const body = buildCreateBody(opts);\n const c = await creationClient(opts);\n const created = await c.post<{ sandbox: SandboxDetail }>('/api/v1/sandboxes', body);\n const sandbox = created.sandbox;\n const org = orgKey(opts);\n // Before anything else: the ID on stderr, so a `kill -9` leaves a handle.\n if (!opts.json) console.error(pc.dim(`instance ${sandbox.id}`));\n\n const spawned = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${sandbox.id}/processes`,\n { command: command.map(shellQuote).join(' ') },\n ).catch(async (e) => {\n try { await c.del(`/api/v1/sandboxes/${sandbox.id}`); } catch { /* best effort */ }\n throw e;\n });\n const jobId = spawned.process.jobId;\n\n if (opts.detach) {\n setCurrentInstance(sandbox.id, org);\n if (opts.json) console.log(JSON.stringify({ type: 'detached', sandboxId: sandbox.id, jobId }));\n else if (opts.quiet) console.log(sandbox.id);\n else printDetachSummary(sandbox.id, jobId, runTimeoutText(opts));\n return;\n }\n\n let exitCode: number | null = null;\n let destroyRequested = false;\n let detachRequested = false;\n let prompting = false;\n let deleted = false;\n let kept = false;\n let settledCostUsd: number | undefined;\n let cleanupError: string | undefined;\n let printedOut = 0;\n let printedErr = 0;\n\n const flush = (p: SandboxProcessStatus) => {\n if (prompting) return; // Ctrl-C prompt owns the terminal right now\n if (p.stdout.length > printedOut) {\n const data = p.stdout.slice(printedOut);\n if (opts.json) console.log(JSON.stringify({ type: 'stdout', data }));\n else process.stdout.write(data);\n printedOut = p.stdout.length;\n }\n if (p.stderr.length > printedErr) {\n const data = p.stderr.slice(printedErr);\n if (opts.json) console.log(JSON.stringify({ type: 'stderr', data }));\n else process.stderr.write(data);\n printedErr = p.stderr.length;\n }\n };\n\n const onSignal = () => {\n if (!process.stdin.isTTY || opts.json || opts.yes || prompting) {\n // Non-TTY, --yes, or a 2nd Ctrl-C mid-prompt: destroy outright\n // (a mid-prompt Ctrl-C counts as N — keep waiting — unless readline\n // already closed, in which case fall through to destroy below).\n if (prompting) return;\n destroyRequested = true;\n return;\n }\n prompting = true;\n const rl = readline.createInterface({ input: process.stdin, output: process.stderr });\n rl.question(`Destroy instance ${shortId(sandbox.id)}? [y/N/d] `, (answer) => {\n rl.close();\n prompting = false;\n const a = answer.trim().toLowerCase();\n if (a === 'y') destroyRequested = true;\n else if (a === 'd') detachRequested = true;\n // N/Enter: keep waiting.\n });\n };\n process.on('SIGINT', onSignal);\n process.on('SIGTERM', onSignal);\n\n try {\n const deadline = opts.timeoutMs ? Date.now() + Number(opts.timeoutMs) : undefined;\n // Repeated waits, streaming the cumulative buffers' new tail each round.\n // ~55s per call stays under the route's wall-clock cap.\n while (exitCode === null && !destroyRequested && !detachRequested) {\n const remaining = deadline === undefined ? 55_000 : Math.max(1, deadline - Date.now());\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandbox.id}/processes/${jobId}/wait`,\n { timeoutMs: Math.min(55_000, remaining) },\n );\n flush(res.process);\n if (res.process.status === 'exited') {\n exitCode = res.process.exitCode ?? 128;\n } else if (deadline !== undefined && Date.now() >= deadline) {\n destroyRequested = true;\n }\n }\n } finally {\n process.removeListener('SIGINT', onSignal);\n process.removeListener('SIGTERM', onSignal);\n if (detachRequested) {\n kept = true;\n setCurrentInstance(sandbox.id, org);\n if (!opts.json) printDetachSummary(sandbox.id, jobId, runTimeoutText(opts));\n } else if (opts.keep && exitCode !== null) {\n kept = true;\n // --keep only keeps a run that reached an exit; a wait error or a\n // destroy request falls through to deletion so a failed run can't\n // leave a running instance behind.\n setCurrentInstance(sandbox.id, org);\n if (!opts.json && opts.quiet) console.log(sandbox.id);\n else if (!opts.json) {\n console.error(pc.dim(`kept instance ${shortId(sandbox.id)} (current for ${dirKey()})`));\n console.log(sandbox.id);\n }\n } else {\n try {\n const result = await c.del<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${sandbox.id}`);\n const cost = confirmedDestroyedSandbox(result, sandbox.id).cost;\n deleted = true;\n if (cost?.settled && cost.costUsd !== null && Number.isFinite(cost.costUsd)) settledCostUsd = cost.costUsd;\n } catch (e) {\n cleanupError = e instanceof Error ? e.message : String(e);\n if (!opts.json) console.error(pc.red(`destroy failed for ${sandbox.id}: ${safeTerm(cleanupError)}`));\n }\n const orgNow = orgKey(opts);\n if (readFileCurrent(orgNow) === sandbox.id) clearCurrentInstance(orgNow);\n }\n const summary = {\n type: 'summary', sandboxId: sandbox.id, jobId, exitCode,\n elapsedSeconds: (Date.now() - startedAt) / 1000,\n provider: sandbox.placement?.box?.provider ?? sandbox.provider,\n deleted, kept,\n ...(cleanupError ? { cleanupError } : {}),\n ...(settledCostUsd !== undefined ? { costUsd: settledCostUsd } : {}),\n };\n if (opts.json) console.log(JSON.stringify(summary));\n else console.error(pc.dim(\n `exit ${exitCode ?? 'unknown'} · ${summary.elapsedSeconds.toFixed(1)}s · ${safeTerm(summary.provider ?? 'unknown provider')}` +\n (settledCostUsd !== undefined ? ` · $${settledCostUsd.toFixed(4)}` : '') +\n ` · ${sandbox.id} ${deleted ? 'deleted' : summary.kept ? 'kept' : 'cleanup unconfirmed'}`,\n ));\n }\n\n process.exitCode = detachRequested ? 0 : (cleanupError && exitCode === 0 ? 1 : exitCode ?? (destroyRequested ? 130 : 1));\n}\n\n// ─── serve ───────────────────────────────────────────────────────────────────\n\ninterface PortsResponse {\n ports: { port: number; address: string; public: boolean }[];\n waited?: boolean;\n found?: boolean;\n}\n\n/** Wait-cap per `/ports?wait=` call — the route caps at 60s. */\nconst SERVE_POLL_MS = 30_000;\nconst SERVE_DEFAULT_WAIT_MS = 120_000;\n\n/**\n * `compute instances serve` — start a server process and wait until its port\n * listens on a public address, then print the provider URL.\n *\n * Failure modes per spec: a loopback-only bind fails with the bind hint; the\n * process exiting early prints its exit code and last log lines.\n */\nasync function serveInstanceCommand(\n id: string,\n command: string[],\n port: number,\n opts: QuietOpts & { cwd?: string; env?: string[]; timeoutMs?: string },\n): Promise<void> {\n const c = await client(opts);\n const spawned = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${id}/processes`,\n {\n command: command.map(shellQuote).join(' '),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.env?.length ? { env: parseInputs(opts.env) } : {}),\n },\n );\n const jobId = spawned.process.jobId;\n\n const jobStatus = () =>\n c.get<{ process: SandboxProcessStatus }>(`/api/v1/sandboxes/${id}/processes/${jobId}`);\n const reportExit = (proc: SandboxProcessStatus): void => {\n if (!opts.json) {\n const logs = `${proc.stdout}${proc.stderr}`.trimEnd().split('\\n');\n if (logs.length > 0 && logs[0] !== '') {\n console.error(pc.dim('--- last log lines ---'));\n for (const line of logs.slice(-50)) console.error(safeTerm(line));\n }\n }\n fail(new Error(`The server exited (code ${proc.exitCode ?? '?'}) before port ${port} listened.`), opts);\n };\n\n const waitMs = opts.timeoutMs ? Number(opts.timeoutMs) : SERVE_DEFAULT_WAIT_MS;\n const deadline = Date.now() + waitMs;\n let entry: PortsResponse['ports'][number] | undefined;\n let remaining = waitMs;\n while (!entry && remaining > 0) {\n const res = await c.get<PortsResponse>(\n `/api/v1/sandboxes/${id}/ports?wait=${port}&timeoutMs=${Math.min(SERVE_POLL_MS, remaining)}`,\n );\n entry = res.ports.find((p) => p.port === port);\n if (entry) break;\n // Not listening — did the server die?\n const proc = await jobStatus();\n if (proc.process.status === 'exited') {\n reportExit(proc.process);\n return; // fail() stubs process.exit in tests — don't keep polling.\n }\n remaining = deadline - Date.now();\n }\n\n if (entry) {\n // A listener doesn't prove our server bound the port — when another\n // process already owns it our job dies silently. Check before printing.\n const proc = await jobStatus();\n if (proc.process.status === 'exited') {\n reportExit(proc.process);\n return;\n }\n } else {\n if (!opts.json) printServeJobFooter(id, jobId);\n fail(new Error(`Port ${port} never listened within ${fmtTimeout(waitMs)}.`), opts);\n return;\n }\n\n if (!entry.public) {\n if (!opts.json) printServeJobFooter(id, jobId);\n fail(new Error(\n `Port ${port} is listening on ${safeTerm(entry.address)} only. ` +\n `Bind to 0.0.0.0 (e.g. --host 0.0.0.0) so it can be reached.`),\n opts,\n );\n return;\n }\n\n const { url } = await c.get<{ url: string }>(`/api/v1/sandboxes/${id}/urls?port=${port}`);\n if (opts.quiet) {\n console.log(safeTerm(url));\n return;\n }\n // --json emits the raw field; only terminal output is sanitized.\n output(opts, { url }, () => {\n console.log(safeTerm(url));\n printServeJobFooter(id, jobId);\n });\n}\n\nfunction printServeJobFooter(sandboxId: string, jobId: string): void {\n // Always name the instance: the implicit instance may be a different box.\n console.error(pc.dim(` job ${jobId}`));\n console.error(pc.dim(` logs: compute instances logs ${sandboxId} ${jobId}`));\n console.error(pc.dim(` kill: compute instances kill ${sandboxId} ${jobId}`));\n}\n\n\n\n// ─── cp ─────────────────────────────────────────────────────────────────────\n\n/** Wire shapes for the platform `/transfers` endpoints. */\ninterface TransferCreate {\n transferId: string;\n uploadUrl?: string;\n downloadUrl?: string;\n expiresAt?: string;\n bytes?: number;\n files?: number;\n}\ninterface TransferComplete {\n path: string;\n bytes: number;\n files: number;\n}\n\n/** Stderr progress appears past this size on TTYs. */\nconst CP_PROGRESS_MIN_BYTES = 10 * 1024 * 1024;\n\n/** Presigned transfer URLs must be https — except loopback, for local dev. */\nfunction assertTransferUrl(raw: string): void {\n let u: URL;\n try {\n u = new URL(raw);\n } catch {\n throw new Error('platform returned a malformed transfer URL');\n }\n if (u.protocol === 'https:') return;\n const loopback = ['localhost', '127.0.0.1', '::1', '[::1]'].includes(u.hostname);\n if (!(u.protocol === 'http:' && loopback)) {\n throw new Error(`refusing insecure transfer URL: ${u.protocol}//${u.hostname} (expected https)`);\n }\n}\n\n/** tar entries that would write outside the extract root. */\nfunction tarEntryIsSafe(p: string, entry: unknown): boolean {\n if (path.isAbsolute(p) || p.split('/').includes('..')) return false;\n const { type, linkpath } = entry as { type?: string; linkpath?: string };\n if ((type === 'Link' || type === 'SymbolicLink') && linkpath) {\n if (path.isAbsolute(linkpath) || linkpath.split('/').includes('..')) return false;\n }\n return true;\n}\n\n/**\n * One side of `cp <src> <dst>`: a remote endpoint is `[uuid:]/abs/path`\n * (omitted uuid = the current instance); anything else is a local path —\n * `box:./x` and `label:…` stay local, matching the positional-ID rule.\n */\nfunction parseCpEndpoint(arg: string): { remoteId?: string; remotePath: string } | { local: string } {\n const m = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})?:(\\/.*)$/.exec(arg);\n if (m) return { remoteId: m[1] || undefined, remotePath: m[2] };\n return { local: arg };\n}\n\n/**\n * `compute instances cp` — one side remote (`[id:]/abs/path`), one side local.\n * Upload: tar.gz the local path → PUT the presigned `uploadUrl` → `/complete`\n * makes the box pull + extract under the remote dir. Download: `/transfers`\n * makes the box tar + PUT; we GET the `downloadUrl` and extract into the\n * local dir (created if missing — the remote basename always stays the\n * top-level entry, docker-style `cp src dst/…` semantics; no rename form).\n */\nasync function cpCommand(src: string, dst: string, opts: QuietOpts): Promise<void> {\n const s = parseCpEndpoint(src);\n const d = parseCpEndpoint(dst);\n const sRemote = 'remotePath' in s;\n const dRemote = 'remotePath' in d;\n if (sRemote === dRemote) {\n throw new Error('cp needs exactly one remote side — write it as [id:]/abs/path (e.g. 3f2a…:/app or :/app)');\n }\n const c = await client(opts);\n if (!sRemote && 'remotePath' in d && 'local' in s) {\n const resolved = resolveSandbox(d.remoteId, opts);\n const r = await cpUpload(c, resolved.id, s.local, d.remotePath, opts);\n output(opts, r, (done) => {\n if (!opts.quiet) console.log(`copied ${done.files} files (${formatBytes(done.bytes)}) → ${shortId(resolved.id)}:${d.remotePath}`);\n });\n } else if ('remotePath' in s && 'local' in d) {\n const resolved = resolveSandbox(s.remoteId, opts);\n const r = await cpDownload(c, resolved.id, s.remotePath, d.local, opts);\n output(opts, r, (done) => {\n if (!opts.quiet) console.log(`copied ${done.files} files (${formatBytes(done.bytes)}) → ${d.local}`);\n });\n }\n}\n\n/** Write `X/Y MB` progress to stderr while a known total streams by. */\nfunction cpProgress(total: number, opts: QuietOpts): { bump: (n: number) => void; done: () => void } {\n const show = !opts.quiet && !opts.json && process.stderr.isTTY && total > CP_PROGRESS_MIN_BYTES;\n let sent = 0;\n return {\n bump(n) {\n if (!show) return;\n sent += n;\n process.stderr.write(`\\r${formatBytes(sent)} / ${formatBytes(total)} (${Math.round((sent / total) * 100)}%)`);\n },\n done() {\n if (show) process.stderr.write('\\n');\n },\n };\n}\n\nasync function cpUpload(\n c: ActionsClient,\n sandboxId: string,\n localPath: string,\n remotePath: string,\n opts: QuietOpts,\n): Promise<TransferComplete> {\n // statSync first so a missing path errors before anything is created.\n const abs = path.resolve(localPath);\n fs.statSync(abs);\n // Private 0700 dir: a shared /tmp path can be pre-created by another\n // local user and the tarball written somewhere attacker-readable.\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'compute-cp-up-'));\n const tmp = path.join(tmpDir, 'archive.tar.gz');\n try {\n await tar.create({ gzip: true, file: tmp, cwd: path.dirname(abs) }, [path.basename(abs)]);\n const size = fs.statSync(tmp).size;\n const created = await c.post<TransferCreate>(\n `/api/v1/sandboxes/${sandboxId}/transfers`,\n { direction: 'upload', path: remotePath },\n );\n if (!created.uploadUrl) throw new Error('platform did not return an upload URL');\n assertTransferUrl(created.uploadUrl);\n const progress = cpProgress(size, opts);\n try {\n const stream = fs.createReadStream(tmp);\n stream.on('data', (chunk: Buffer | string) => progress.bump(typeof chunk === 'string' ? chunk.length : chunk.byteLength));\n const res = await fetch(created.uploadUrl, {\n method: 'PUT',\n headers: { 'content-length': String(size), 'content-type': 'application/gzip' },\n // @ts-expect-error Readable.toWeb body is supported at runtime; DOM types lag\n body: Readable.toWeb(stream),\n duplex: 'half',\n });\n if (!res.ok) throw new Error(`upload failed: HTTP ${res.status}`);\n } finally {\n progress.done();\n }\n return await c.post<TransferComplete>(\n `/api/v1/sandboxes/${sandboxId}/transfers/${created.transferId}/complete`,\n {},\n );\n } finally {\n fs.rmSync(tmpDir, { recursive: true, force: true });\n }\n}\n\nasync function cpDownload(\n c: ActionsClient,\n sandboxId: string,\n remotePath: string,\n localDir: string,\n opts: QuietOpts,\n): Promise<TransferComplete> {\n const created = await c.post<TransferCreate>(\n `/api/v1/sandboxes/${sandboxId}/transfers`,\n { direction: 'download', path: remotePath },\n );\n if (!created.downloadUrl) throw new Error('platform did not return a download URL');\n assertTransferUrl(created.downloadUrl);\n const res = await fetch(created.downloadUrl);\n if (!res.ok) throw new Error(`download failed: HTTP ${res.status}`);\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'compute-cp-dl-'));\n const tmp = path.join(tmpDir, 'archive.tar.gz');\n try {\n const progress = cpProgress(created.bytes ?? 0, opts);\n const ws = fs.createWriteStream(tmp);\n try {\n // A stream error (e.g. ENOSPC) must fail the copy, not hang on 'drain'.\n await new Promise<void>((resolve, reject) => {\n ws.once('error', reject);\n const reader = res.body!.getReader();\n const pump = async (): Promise<void> => {\n for (;;) {\n const { done, value } = await reader.read();\n if (done || value === undefined) break;\n progress.bump(value.byteLength);\n if (!ws.write(value)) await new Promise<void>((r) => ws.once('drain', () => r()));\n }\n };\n pump().then(\n () => ws.end(() => resolve()),\n reject,\n );\n });\n } finally {\n ws.destroy();\n }\n progress.done();\n fs.mkdirSync(localDir, { recursive: true });\n await tar.extract({ file: tmp, cwd: localDir, filter: tarEntryIsSafe });\n return { path: localDir, bytes: created.bytes ?? fs.statSync(tmp).size, files: created.files ?? 0 };\n } finally {\n fs.rmSync(tmpDir, { recursive: true, force: true });\n }\n}\n\n/** Human byte count for the cp summary line and progress. */\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n const units = ['KB', 'MB', 'GB', 'TB'];\n let v = n / 1024;\n let i = 0;\n while (v >= 1024 && i < units.length - 1) { v /= 1024; i += 1; }\n return `${v >= 100 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;\n}\n","/**\n * The \"current instance\" — the instance a directory's commands default to.\n *\n * One global setting would be unsafe (two agents or terminals would stomp on\n * each other), so the entry is scoped twice: to the working directory's git\n * root (the cwd itself outside a repo) and to the org the command runs as.\n * `COMPUTE_INSTANCE` always wins for agents and CI; an explicit ID argument\n * wins over everything.\n *\n * The file lives next to `credentials.json` (`~/.benchsdk/current-instances.json`,\n * mode 0600). Nothing is written into the user's project.\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/** Resolved lazily so tests can point BENCHSDK_STATE_DIR at a tmp dir. */\nfunction stateDir(): string {\n return process.env.BENCHSDK_STATE_DIR ?? join(homedir(), '.benchsdk');\n}\n\nfunction statePath(): string {\n return join(stateDir(), 'current-instances.json');\n}\n\n/** `[dirKey][orgKey] = sandboxId`. */\ntype Store = Record<string, Record<string, string>>;\n\nexport type InstanceSource = 'argument' | 'env' | 'file';\n\nexport interface ResolvedInstance {\n id: string;\n source: InstanceSource;\n /** The directory key the `file` hit came from — shown in the dim line. */\n dir?: string;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** The platform validates sandbox ids as UUIDs; only a UUID may take the id slot. */\nexport function isUuid(value: string | undefined): value is string {\n return value !== undefined && UUID_RE.test(value);\n}\n\n/** The git root when inside a repo, else the working directory itself. */\nexport function dirKey(cwd = process.cwd()): string {\n const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8' });\n return r.status === 0 && r.stdout.trim() !== '' ? r.stdout.trim() : cwd;\n}\n\n/** A stable org discriminator: the slug override, else a hash of the bearer key. */\nexport function orgKey(opts: { org?: string; apiKey?: string }): string {\n const slug = opts.org || process.env.COMPUTE_ORG;\n if (slug) return `org:${slug}`;\n const key = opts.apiKey || process.env.COMPUTE_API_KEY || process.env.BENCHMARKS_PLATFORM_API_KEY;\n if (key) return `key:${createHash('sha256').update(key).digest('hex').slice(0, 12)}`;\n // OAuth login: key the pick to the org recorded by the last `org use` on\n // this machine (a cache — the consent row is the truth), so switching orgs\n // doesn't silently reuse the previous org's instance.\n try {\n const raw = JSON.parse(readFileSync(join(stateDir(), 'credentials.json'), 'utf8')) as {\n orgId?: string;\n orgSlug?: string;\n };\n const org = raw?.orgId ?? raw?.orgSlug;\n if (org) return `org:${org}`;\n } catch {\n // No stored login — unauthenticated commands share 'default'.\n }\n return 'default';\n}\n\nfunction readStore(): Store {\n try {\n const parsed = JSON.parse(readFileSync(statePath(), 'utf8')) as unknown;\n if (typeof parsed !== 'object' || parsed === null) return {};\n return parsed as Store;\n } catch {\n return {};\n }\n}\n\nfunction writeStore(store: Store): void {\n mkdirSync(stateDir(), { recursive: true });\n // tmp+rename: readers never see a truncated file, and the rename lands with\n // the fresh file's 0600 mode even when replacing a permissive old one.\n const tmp = `${statePath()}.${process.pid}.tmp`;\n writeFileSync(tmp, JSON.stringify(store, null, 2) + '\\n', { mode: 0o600 });\n renameSync(tmp, statePath());\n}\n\n/**\n * mkdir is atomic: the first creator wins. Writers serialize their\n * read-modify-write so two commands updating different picks can't clobber\n * each other; gives up after ~1s rather than hang on a stale lock dir.\n */\nfunction withStoreLock<T>(fn: () => T): T {\n const lock = `${statePath()}.lock`;\n for (let attempt = 0; ; attempt++) {\n try {\n mkdirSync(lock);\n break;\n } catch {\n if (attempt === 99) return fn();\n const until = Date.now() + 10;\n while (Date.now() < until) {\n // spin — writes take microseconds, so a short busy wait suffices\n }\n }\n }\n try {\n return fn();\n } finally {\n try {\n rmSync(lock, { recursive: true, force: true });\n } catch {\n // Already gone — another process took over a stale lock.\n }\n }\n}\n\n/** Persist `sandboxId` as the current instance for this directory + org. */\nexport function setCurrentInstance(sandboxId: string, org: string, dir = dirKey()): void {\n withStoreLock(() => {\n const store = readStore();\n (store[dir] ??= {})[org] = sandboxId;\n writeStore(store);\n });\n}\n\n/** Forget this directory + org's current instance; returns the forgotten id. */\nexport function clearCurrentInstance(org: string, dir = dirKey()): string | undefined {\n return withStoreLock(() => {\n const store = readStore();\n const prev = store[dir]?.[org];\n if (prev === undefined) return undefined;\n delete store[dir][org];\n if (Object.keys(store[dir]).length === 0) delete store[dir];\n writeStore(store);\n return prev;\n });\n}\n\n/** What `use --clear` and destroyed-instance cleanup report on. */\nexport function readFileCurrent(org: string, dir = dirKey()): string | undefined {\n return readStore()[dir]?.[org];\n}\n\n/**\n * The instance a command targets: the explicit argument if it is a UUID, else\n * `COMPUTE_INSTANCE`, else this directory's stored pick. `undefined` when none\n * apply — the caller prints the no-instance hint.\n */\nexport function resolveInstanceId(\n arg: string | undefined,\n opts: { org?: string; apiKey?: string },\n dir = dirKey(),\n): ResolvedInstance | undefined {\n if (isUuid(arg)) return { id: arg, source: 'argument' };\n const env = process.env.COMPUTE_INSTANCE;\n if (env) return { id: env, source: 'env' };\n const file = readFileCurrent(orgKey(opts), dir);\n if (file) return { id: file, source: 'file', dir };\n return undefined;\n}\n\n/** `3f2a…` — the short id form used in informational lines. */\nexport function shortId(id: string): string {\n return id.length > 8 ? `${id.slice(0, 4)}…` : id;\n}\n\n/** Delete the state file wholesale (logout-style hygiene; not wired today). */\nexport function _resetStateFileForTests(): void {\n const p = statePath();\n if (existsSync(p)) rmSync(p);\n}\n","/**\n * `compute instances costs` — the org's sandbox spend\n * (`GET /api/v1/sandboxes/costs`).\n */\n\nimport type { Command } from 'commander';\nimport type { ActionsClient } from './actions-client.js';\nimport type { CommonOpts } from './actions.js';\nimport { formatMoney } from './rate-display.js';\nimport { safeTerm } from './term.js';\n\n/** Injected by `sandboxes.ts`, matching the settings commands. */\nexport interface BillingDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n}\n\n// Wire shape mirrors benchmarks-platform lib/sandboxes/router.ts (`OrgSandboxCosts`).\n\nexport interface SandboxCosts {\n currency: string;\n running: { count: number; costUsd: number };\n settled: { count: number; costUsd: number };\n totalUsd: number;\n byProvider: Array<{\n provider: string;\n count: number;\n costUsd: number;\n /** Absent on servers that predate the per-provider split. */\n running?: { count: number; costUsd: number };\n settled?: { count: number; costUsd: number };\n }>;\n}\n\nfunction printTable(header: string[], rows: string[][]): void {\n const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));\n const line = (cells: string[]) => cells.map((c, i) => c.padEnd(widths[i])).join(' ').trimEnd();\n console.log(line(header));\n for (const row of rows) console.log(line(row));\n}\n\n/** Older servers send no per-provider running / settled split; those cells show `—`. */\nexport function printCosts(c: SandboxCosts, customerOnly: boolean): void {\n if (customerOnly) console.log('customer sandboxes only');\n printTable(\n ['PROVIDER', 'SANDBOXES', 'RUNNING', 'RUNNING COST', 'SETTLED', 'TOTAL'],\n [\n [\n 'all',\n String(c.running.count + c.settled.count),\n String(c.running.count),\n formatMoney(c.running.costUsd),\n `${c.settled.count} · ${formatMoney(c.settled.costUsd)}`,\n formatMoney(c.totalUsd),\n ],\n ...c.byProvider.map((p) => [\n safeTerm(p.provider),\n String(p.count),\n p.running ? String(p.running.count) : '—',\n p.running ? formatMoney(p.running.costUsd) : '—',\n p.settled ? `${p.settled.count} · ${formatMoney(p.settled.costUsd)}` : '—',\n formatMoney(p.costUsd),\n ]),\n ],\n );\n if (c.currency !== 'USD') console.log(`currency: ${safeTerm(c.currency)}`);\n}\n\nexport function registerBillingCommands(\n group: Command,\n common: (cmd: Command) => Command,\n deps: BillingDeps,\n): void {\n common(\n group\n .command('costs')\n .description(\"Show the org's sandbox spend: running, settled and per provider\")\n .option('--customer-only', 'exclude idle platform sandboxes (warm pool, CI sync, snapshot builds); Actions job sandboxes stay'),\n ).action(async (opts: CommonOpts & { customerOnly?: boolean }) => {\n try {\n const c = await deps.client(opts);\n const res = await c.get<SandboxCosts>(\n '/api/v1/sandboxes/costs',\n opts.customerOnly ? { customerOnly: 'true' } : undefined,\n );\n deps.output(opts, res, (data) => printCosts(data, opts.customerOnly === true));\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport ignore, { type Ignore } from 'ignore';\nimport * as tar from 'tar';\nimport { Command } from 'commander';\nimport { client, fail, output, safeTerm, type CommonOpts } from './actions.js';\nimport type { ActionsClient } from './actions-client.js';\nimport { isUuid, resolveInstanceId } from './current-instance.js';\nimport type { SyncEntry } from './sync-fs.js';\nimport { SnapshotSession, selectSnapshot, endpointRoot, ignoredPaths, type CaptureResult } from './snapshot-engine.js';\nimport { randomUUID } from 'node:crypto';\nimport { retainCapture, type RetainedSnapshot } from './sync-retention.js';\n\nexport type SyncEndpoint = { local: string } | { id: string; remote: string };\nexport interface SyncOptions extends CommonOpts { delete?: boolean; dryRun?: boolean; watch?: boolean }\nexport interface SyncPlan { copy: SyncEntry[]; remove: SyncEntry[]; snapshot?: RetainedSnapshot }\n\nexport function syncEndpoint(value: string, opts: CommonOpts): SyncEndpoint {\n const match = /^([^:]*):(\\/.*)$/.exec(value);\n if (!match || /^[a-zA-Z]:[\\\\/]/.test(value)) return { local: path.resolve(value) };\n const id = match[1] || resolveInstanceId(undefined, opts)?.id;\n if (!id || !isUuid(id)) throw new Error('Use a sandbox UUID or select one with compute new / compute use <id>.');\n const remote = path.posix.normalize(match[2]);\n if (remote === '/' || remote.split('/').includes('.git')) throw new Error('Sync requires a project directory outside .git.');\n return { id, remote };\n}\n\n/** Nested .gitignore rules, relative to each rule file. Ignored trees are never read. */\nexport function sourceFilter(root: string): (name: string, directory: boolean) => boolean {\n const git = spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' });\n const filterRoot = git.status === 0 ? git.stdout.trim() : root;\n const prefix = path.relative(filterRoot, root).split(path.sep).join('/');\n const cache = new Map<string, { base: string; rules: Ignore }[]>();\n const rulesFor = (dir: string): { base: string; rules: Ignore }[] => {\n if (cache.has(dir)) return cache.get(dir)!;\n const inherited = dir ? rulesFor(path.posix.dirname(dir) === '.' ? '' : path.posix.dirname(dir)) : [];\n let rules = inherited;\n try {\n rules = [...inherited, { base: dir, rules: ignore().add(fs.readFileSync(path.join(filterRoot, dir, '.gitignore'), 'utf8')) }];\n } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }\n cache.set(dir, rules);\n return rules;\n };\n return (name, directory) => {\n if (name.split('/').includes('.git')) return true;\n name = prefix ? prefix + '/' + name : name;\n const parent = path.posix.dirname(name);\n let ignored = false;\n for (const { base, rules } of rulesFor(parent === '.' ? '' : parent)) {\n const relative = (base ? name.slice(base.length + 1) : name) + (directory ? '/' : '');\n const result = rules.test(relative);\n if (result.ignored) ignored = true;\n if (result.unignored) ignored = false;\n }\n return ignored;\n };\n}\n\nexport async function planSync(session: SnapshotSession, source: SyncEntry[], destination: SyncEntry[], remove: boolean, excluded: (name: string, directory: boolean) => boolean = () => false): Promise<SyncPlan> {\n const difference = await session.diff(source, destination);\n const changes = new Set([...difference.added, ...difference.changed.map((e) => e.path)]);\n const deleted = new Set(difference.deleted);\n const src = new Map(source.map((e) => [e.path, e]));\n const dst = new Map(destination.map((e) => [e.path, e]));\n const copy: SyncEntry[] = [];\n for (const entry of source) {\n const previous = dst.get(entry.path);\n if (previous && previous.type !== entry.type) throw new Error(`Sync type conflict at ${entry.path}; move or remove the destination entry first.`);\n if (changes.has(entry.path) && (!previous || entry.type !== 'directory')) {\n if (previous?.links && previous.links > 1) throw new Error(`Sync cannot overwrite a hard-linked destination file: ${entry.path}. Move or unlink it first.`);\n copy.push(entry);\n }\n }\n // Never delete ignored entries or a directory containing protected children.\n const ignoredPaths = destination.filter((e) => excluded(e.path, e.type === 'directory')).map((e) => e.path);\n const protectedPaths = destination.filter((e) => e.protected || excluded(e.path, e.type === 'directory')).map((e) => e.path);\n const removed = remove ? destination.filter((e) => !e.protected && deleted.has(e.path) && !src.has(e.path) && !ignoredPaths.some((p) => e.path === p || e.path.startsWith(p + '/')) &&\n !protectedPaths.some((p) => p.startsWith(e.path + '/'))) : [];\n removed.sort((a, b) => b.path.split('/').length - a.path.split('/').length || b.path.localeCompare(a.path));\n return { copy, remove: removed };\n}\n\nfunction transferUrl(raw: string): string {\n const url = new URL(raw);\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) throw new Error('Insecure sync transfer URL.');\n return raw;\n}\nasync function download(c: ActionsClient, source: { id: string; remote: string }, target: string): Promise<string> {\n const created = await c.post<{ downloadUrl: string }>(`/api/v1/sandboxes/${source.id}/transfers`, { direction: 'download', path: source.remote });\n const response = await fetch(transferUrl(created.downloadUrl), { redirect: 'error' });\n if (!response.ok || !response.body) throw new Error(`Sync download failed (${response.status}).`);\n const file = path.join(target, 'source.tar.gz');\n await pipeline(Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0]), fs.createWriteStream(file, { mode: 0o600 }));\n const wrapper = path.posix.basename(source.remote);\n const validate = (name: string, entry: { type?: string; linkpath?: string }) => {\n const parts = name.replace(/\\/$/, '').split('/');\n if (parts[0] !== wrapper || parts.some((p) => p === '..' || p === '' || p === '.') || name.includes('\\\\')) throw new Error('Unsafe sync archive entry.');\n if (parts.includes('.git')) return false;\n if (!['File', 'Directory'].includes(entry.type ?? '')) throw new Error('Unsupported sync archive entry.');\n return true;\n };\n // Validate the complete archive before writing any of its entries.\n let invalid: unknown;\n await tar.list({ file, onReadEntry: (entry) => {\n try { validate(entry.path, entry); } catch (error) { invalid = error; }\n entry.resume();\n } });\n if (invalid) throw invalid;\n const unpacked = path.join(target, 'unpacked');\n fs.mkdirSync(unpacked);\n await tar.extract({ file, cwd: unpacked, filter: (name, entry) => validate(name, entry as tar.ReadEntry), strict: true });\n return path.join(unpacked, wrapper);\n}\nasync function upload(c: ActionsClient, destination: { id: string; remote: string }, root: string, entries: SyncEntry[], temp: string): Promise<void> {\n if (!entries.length) return;\n const archive = path.join(temp, 'changes.tar.gz');\n await tar.create({ file: archive, gzip: true, cwd: root, noDirRecurse: true, portable: true }, entries.map((e) => e.path));\n const created = await c.post<{ transferId: string; uploadUrl: string }>(`/api/v1/sandboxes/${destination.id}/transfers`, { direction: 'upload', path: destination.remote });\n const response = await fetch(transferUrl(created.uploadUrl), {\n method: 'PUT', redirect: 'error', headers: { 'content-type': 'application/gzip', 'content-length': String(fs.statSync(archive).size) },\n // @ts-expect-error Node fetch accepts a web stream with duplex.\n body: Readable.toWeb(fs.createReadStream(archive)), duplex: 'half',\n });\n if (!response.ok) throw new Error(`Sync upload failed (${response.status}).`);\n await c.post(`/api/v1/sandboxes/${destination.id}/transfers/${created.transferId}/complete`, {});\n}\n\nexport async function syncOnce(c: ActionsClient, source: SyncEndpoint, destination: SyncEndpoint, opts: SyncOptions): Promise<SyncPlan> {\n if ('local' in source && 'local' in destination) throw new Error('Sync requires at least one sandbox endpoint ([id]:/path).');\n if ('id' in source && 'id' in destination && source.id.toLowerCase() === destination.id.toLowerCase() &&\n (source.remote === destination.remote || source.remote.startsWith(destination.remote + '/') || destination.remote.startsWith(source.remote + '/'))) throw new Error('Source and destination sync directories must not overlap.');\n const session = new SnapshotSession(c);\n try {\n const excluded = 'local' in source ? sourceFilter(source.local) : () => false;\n const src = await session.scan(source, false, 'local' in source ? excluded : undefined);\n const dst = await session.scan(destination, true);\n const plan = await planSync(session, src.entries, dst.entries, !!opts.delete, excluded);\n if (opts.dryRun) return plan;\n if (!plan.copy.length && !plan.remove.length) {\n await session.guard(destination, { missing: true, directories: [] });\n return plan;\n }\n if (plan.copy.length) {\n const sourceRoot = endpointRoot(source);\n const captureRoot = 'id' in source ? await session.remoteRoot(source.id) : session.temp;\n const sourceStore = path.posix.join(captureRoot, 'store');\n const checkpointId = randomUUID();\n const capture = await session.operation<CaptureResult & { missing?: string[] }>('id' in source ? source.id : undefined, 'capture', {\n checkpointId, paths: [sourceRoot, ...src.entries.filter((e) => e.type === 'directory' && !e.path.includes('/')).map((e) => path.posix.join(sourceRoot, e.path))],\n exclude: 'local' in source ? ignoredPaths(source.local, excluded) : ['**/.git', '**/.git/**'],\n store: { kind: 'fs', root: sourceStore },\n });\n if (capture.missing?.length) throw new Error('Source changed during snapshot capture.');\n if (capture.manifestKey !== `manifests/${checkpointId}.json`) throw new Error('Invalid snapshot manifest key.');\n const store = 'local' in source ? sourceStore : path.join(session.temp, 'metadata');\n if ('id' in source) {\n fs.mkdirSync(path.join(store, 'manifests'), { recursive: true });\n fs.mkdirSync(path.join(store, 'blobs'));\n const manifestText = await session.read(source.id, path.posix.join(sourceStore, capture.manifestKey));\n const metadata = JSON.parse(manifestText);\n if (!/^sha256:[a-f0-9]{64}$/.test(metadata.config?.digest)) throw new Error('Invalid snapshot config digest.');\n fs.writeFileSync(path.join(store, capture.manifestKey), manifestText);\n fs.writeFileSync(path.join(store, 'blobs', metadata.config.digest.slice(7)), await session.read(source.id, path.posix.join(sourceStore, 'blobs', metadata.config.digest.slice(7))));\n }\n plan.snapshot = await retainCapture(c, session, source, sourceStore, store, capture.manifestKey, 'id' in source ? source.id : (destination as { id: string }).id, [sourceRoot]);\n const manifest = selectSnapshot(store, capture.manifestKey, sourceRoot, plan.copy, dst, endpointRoot(destination));\n // Only the config and layers referenced by this selected OCI view travel.\n let bundle = path.join(session.temp, 'bundle');\n fs.mkdirSync(path.join(bundle, 'blobs'), { recursive: true });\n fs.mkdirSync(path.join(bundle, 'manifests'));\n const selected = JSON.parse(fs.readFileSync(path.join(store, manifest), 'utf8'));\n const refs = [selected.config, ...selected.layers] as { digest: string }[];\n const entries: SyncEntry[] = [\n { path: 'blobs', type: 'directory', mode: 0o700 }, { path: 'manifests', type: 'directory', mode: 0o700 },\n { path: manifest, type: 'file', mode: 0o600 },\n ];\n fs.copyFileSync(path.join(store, manifest), path.join(bundle, manifest));\n for (const ref of refs) {\n if (!/^sha256:[a-f0-9]{64}$/.test(ref.digest)) throw new Error('Invalid snapshot blob digest.');\n const relative = 'blobs/' + ref.digest.slice(7);\n if ('local' in source || ref === selected.config) fs.copyFileSync(path.join(store, relative), path.join(bundle, relative));\n entries.push({ path: relative, type: 'file', mode: 0o600 });\n }\n if ('id' in source) {\n const remoteBundle = path.posix.join(captureRoot, 'selected-store');\n const layers = refs.slice(1).map((ref) => ref.digest.slice(7));\n const layerList = path.posix.join(captureRoot, 'selected-layers.json');\n await session.write(source.id, layerList, JSON.stringify(layers));\n await session.command(source.id, `const fs=require('node:fs'),p=require('node:path'),dest=${JSON.stringify(remoteBundle)},src=${JSON.stringify(sourceStore)};fs.mkdirSync(p.join(dest,'blobs'),{recursive:true});fs.mkdirSync(p.join(dest,'manifests'));for(const hex of JSON.parse(fs.readFileSync(${JSON.stringify(layerList)},'utf8')))fs.copyFileSync(p.join(src,'blobs',hex),p.join(dest,'blobs',hex));`);\n await session.write(source.id, path.posix.join(remoteBundle, manifest), fs.readFileSync(path.join(bundle, manifest), 'utf8'));\n const configFile = 'blobs/' + selected.config.digest.slice(7);\n await session.write(source.id, path.posix.join(remoteBundle, configFile), fs.readFileSync(path.join(bundle, configFile), 'utf8'));\n bundle = await download(c, { id: source.id, remote: remoteBundle }, session.temp);\n }\n let restoreStore = bundle;\n if ('id' in destination) {\n restoreStore = path.posix.join(await session.remoteRoot(destination.id), 'bundle');\n await session.guard({ id: destination.id, remote: restoreStore }, { missing: true, directories: entries.filter((e) => e.type === 'directory') });\n await upload(c, { id: destination.id, remote: restoreStore }, bundle, entries, session.temp);\n }\n const current = await session.scan(destination, true);\n if (JSON.stringify(current.entries) !== JSON.stringify(dst.entries)) throw new Error('Destination changed during sync; rerun to try again.');\n await session.guard(destination, { missing: true, directories: plan.copy.filter((e) => e.type === 'directory') });\n const restored = await session.operation<{ failures: unknown[] }>('id' in destination ? destination.id : undefined, 'restore', {\n checkpointId: 'selected', manifestUrl: undefined,\n // The engine reads the selected manifest from its fs object store.\n store: { kind: 'fs', root: restoreStore }, destDir: endpointRoot(destination), strictArch: false,\n });\n if (restored.failures.length) throw new Error('Snapshot restore was incomplete.');\n }\n if (plan.remove.length) {\n // Delete only after successful capture, transfer and integrity-checked restore.\n await session.guard(destination, { remove: plan.remove });\n }\n return plan;\n } finally { await session.close(); }\n}\n\nexport function printSync(plan: SyncPlan, opts: SyncOptions): void {\n const result = { dryRun: !!opts.dryRun, copied: plan.copy.map((e) => e.path), deleted: plan.remove.map((e) => e.path), ...(plan.snapshot ? { snapshot: plan.snapshot } : {}) };\n if (opts.json) { console.log(JSON.stringify(result)); return; }\n output(opts, result, () => {\n if (opts.dryRun) {\n for (const entry of plan.copy) console.log(`copy ${safeTerm(entry.path)}`);\n for (const entry of plan.remove) console.log(`delete ${safeTerm(entry.path)}`);\n }\n if (plan.snapshot) console.log(`Snapshot ${plan.snapshot.id} retained until ${plan.snapshot.expiresAt}.`);\n console.log(`${opts.dryRun ? 'Would sync' : 'Synced'} ${plan.copy.length} entries; ${plan.remove.length} deleted${opts.dryRun ? ' (dry run)' : ''}.`);\n });\n}\nexport function registerSyncCommand(program: Command): void {\n program.command('sync <source> <destination>')\n .description('One-way directory sync: local paths or [sandbox-id]:/path (empty ID selects the current sandbox)')\n .option('--delete', 'delete destination-only entries, preserving .git and ignored local source paths')\n .option('--dry-run', 'show changes without modifying the destination')\n .option('--watch', 'repeat one-way sync every 2 seconds until interrupted')\n .option('--api-key <key>').option('--base-url <url>').option('--org <slug>').option('--allow-untrusted-host')\n .option('--json', 'print a JSON result per sync pass (JSON Lines with --watch)')\n .action(async (src: string, dst: string, opts: SyncOptions) => {\n const stop = new AbortController();\n const interrupt = () => stop.abort();\n try {\n if (opts.watch && opts.dryRun) throw new Error('--watch and --dry-run cannot be combined.');\n const source = syncEndpoint(src, opts);\n const destination = syncEndpoint(dst, opts);\n const c = await client(opts);\n if (opts.watch && !opts.json) console.error('Watching for changes (one-way sync, every 2 seconds). Press Ctrl-C to stop.');\n if (opts.watch) { process.on('SIGINT', interrupt); process.on('SIGTERM', interrupt); }\n do {\n const plan = await syncOnce(c, source, destination, opts);\n if (!opts.watch || plan.copy.length || plan.remove.length) printSync(plan, opts);\n if (!opts.watch || stop.signal.aborted) break;\n try { await delay(2000, undefined, { signal: stop.signal }); } catch { break; }\n } while (!stop.signal.aborted);\n } catch (error) { fail(error, opts); }\n finally { process.removeListener('SIGINT', interrupt); process.removeListener('SIGTERM', interrupt); }\n });\n}\n","/** Retain full project captures before applying a selected view to the destination. */\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport type { ActionsClient } from './actions-client.js';\nimport type { SnapshotSession, EngineEndpoint } from './snapshot-engine.js';\nexport interface RetainedSnapshot { id: string; expiresAt: string }\ninterface Upload { objects: { key: string; url: string }[]; manifestPutUrl: string; manifestJson: string }\n\n/** Self-contained so remote sources upload directly from their private scratch. */\nasync function publish(input: { store: string; upload: Upload; manifest: unknown }, requireModule: NodeRequire): Promise<void> {\n const fs = requireModule('node:fs') as typeof import('node:fs');\n const path = requireModule('node:path') as typeof import('node:path');\n const crypto = requireModule('node:crypto') as typeof import('node:crypto');\n const checkUrl = (value: string) => {\n const url = new URL(value);\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) throw new Error('Insecure retained snapshot upload URL.');\n };\n for (const object of input.upload.objects) {\n if (!/^blobs\\/[a-f0-9]{64}$/.test(object.key)) throw new Error('Invalid retained snapshot object key.');\n checkUrl(object.url);\n const file = path.join(input.store, object.key);\n const hash = crypto.createHash('sha256');\n for await (const chunk of fs.createReadStream(file)) hash.update(chunk);\n if (hash.digest('hex') !== object.key.slice(6)) throw new Error('Retained snapshot blob digest mismatch.');\n const response = await fetch(object.url, {\n method: 'PUT', redirect: 'error', signal: AbortSignal.timeout(290_000),\n headers: { 'content-length': String(fs.statSync(file).size) },\n // @ts-expect-error Node streams require duplex, which DOM fetch types omit.\n body: fs.createReadStream(file), duplex: 'half',\n });\n if (!response.ok) throw new Error(`Retained snapshot upload failed (${response.status}).`);\n await response.body?.cancel();\n }\n checkUrl(input.upload.manifestPutUrl);\n const response = await fetch(input.upload.manifestPutUrl, {\n method: 'PUT', redirect: 'error', signal: AbortSignal.timeout(290_000),\n headers: { 'content-type': 'application/json' }, body: input.upload.manifestJson,\n });\n if (!response.ok) throw new Error(`Retained snapshot manifest upload failed (${response.status}).`);\n await response.body?.cancel();\n}\n\nexport async function retainCapture(c: ActionsClient, session: SnapshotSession, source: EngineEndpoint, sourceStore: string, metadataStore: string, manifestKey: string, anchorId: string, paths: string[]): Promise<RetainedSnapshot> {\n const manifest = JSON.parse(fs.readFileSync(path.join(metadataStore, manifestKey), 'utf8'));\n const registered = await c.post<{ snapshot: RetainedSnapshot; upload: Upload }>(`/api/v1/sandboxes/${anchorId}/sync-snapshots`, { manifest, paths });\n const input = { store: sourceStore, upload: registered.upload, manifest };\n if ('local' in source) await publish(input, createRequire(import.meta.url));\n else {\n const payload = path.posix.join(await session.remoteRoot(source.id), 'retained-upload.json');\n await session.write(source.id, payload, JSON.stringify(input));\n await session.command(source.id, `(${publish.toString()})(JSON.parse(require('node:fs').readFileSync(${JSON.stringify(payload)},'utf8')),require).catch(e=>{console.error(e.message);process.exitCode=1})`);\n }\n const completed = await c.post<{ snapshot: RetainedSnapshot }>(`/api/v1/snapshots/${registered.snapshot.id}/sync`, {});\n return { id: completed.snapshot.id, expiresAt: completed.snapshot.expiresAt };\n}\n","import { loadCredentials } from '@benchsdk/cli';\nimport { ActionsCliError } from './actions-client.js';\nimport { client, type CommonOpts } from './actions.js';\nimport { login } from './login.js';\n\n/** Only creation may initiate login, and only before any provision request. */\nexport async function creationClient(opts: CommonOpts & { quiet?: boolean; browser?: boolean }) {\n const interactive = process.stdin.isTTY && process.stderr.isTTY && !process.env.CI && !opts.json && !opts.quiet &&\n !opts.apiKey && !process.env.COMPUTE_API_KEY && !process.env.BENCHMARKS_PLATFORM_API_KEY &&\n !process.env.BENCHMARKS_PLATFORM_TOKEN;\n // Snapshot before resolution: a legacy session resolver may clear its\n // rejected credentials. That must not turn it into a first-run login.\n const credentials = interactive ? await loadCredentials() : undefined;\n try {\n return await client(opts);\n } catch (error) {\n if (!(error instanceof ActionsCliError) || error.code !== 'no_credentials' || !interactive ||\n credentials?.token || credentials?.apiKey || credentials?.refreshToken) throw error;\n await login({ baseUrl: opts.baseUrl, browser: opts.browser, org: opts.org });\n return client(opts);\n }\n}\n","/** Browser-assisted RFC 8628 login, using the shared compute/bench session. */\nimport { createHash } from 'node:crypto';\nimport { mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, readdirSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport {\n BENCH_OAUTH_CLIENT_ID,\n BENCH_OAUTH_SCOPE,\n getMe,\n saveCredentials,\n setActiveOrganization,\n type CliAuth,\n} from '@benchsdk/cli';\nimport { DEFAULT_BASE_URL, isSecurePlatformTransport, isTrustedPlatformHost } from '@computesdk/platform';\nimport { envBaseUrl } from './session.js';\n\n/** No shell: a verification URL must never be interpreted as a command. */\nexport function openBrowser(url: string): Promise<boolean> {\n const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32' : 'xdg-open';\n const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url];\n return new Promise((resolve) => {\n const child = spawn(command, args, { stdio: 'ignore', timeout: 5000 });\n child.once('error', () => resolve(false));\n child.once('close', (code) => resolve(code === 0));\n });\n}\n\ninterface OAuthResponse {\n device_code?: string;\n user_code?: string;\n verification_uri?: string;\n verification_uri_complete?: string;\n expires_in?: number;\n interval?: number;\n access_token?: string;\n refresh_token?: string;\n error?: string;\n error_description?: string;\n}\n\nasync function postForm(url: string, params: Record<string, string>, timeoutMs = 30_000): Promise<OAuthResponse> {\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(params),\n signal: AbortSignal.timeout(Math.max(1, Math.min(30_000, timeoutMs))),\n redirect: 'error',\n });\n const body = await response.json() as OAuthResponse;\n if (!response.ok && !body.error) throw new Error(`Sign-in failed (${response.status}). Run compute login to retry.`);\n return body;\n}\n\ninterface PendingLogin {\n baseUrl: string;\n device: OAuthResponse;\n expiresAt: number;\n}\nfunction stateDir(): string {\n return process.env.BENCHSDK_STATE_DIR ?? join(homedir(), '.benchsdk');\n}\nfunction pendingPath(baseUrl: string): string {\n return join(stateDir(), `compute-login-${createHash('sha256').update(baseUrl).digest('hex')}.json`);\n}\nfunction readPending(baseUrl: string, includeExpired = false): PendingLogin | undefined {\n try {\n const pending = JSON.parse(readFileSync(pendingPath(baseUrl), 'utf8')) as PendingLogin;\n if (pending.baseUrl === baseUrl && pending.device && Number.isFinite(pending.expiresAt) && (includeExpired || pending.expiresAt > Date.now())) return pending;\n } catch { /* no pending login */ }\n return undefined;\n}\nfunction savePending(pending: PendingLogin): void {\n mkdirSync(stateDir(), { recursive: true });\n const file = pendingPath(pending.baseUrl);\n const tmp = `${file}.${process.pid}.tmp`;\n writeFileSync(tmp, JSON.stringify(pending), { mode: 0o600 });\n renameSync(tmp, file);\n}\nfunction removePending(baseUrl: string, deviceCode: string): void {\n // A completed/denied attempt must not erase a newer login.\n if (readPending(baseUrl, true)?.device.device_code === deviceCode) rmSync(pendingPath(baseUrl), { force: true });\n}\nexport function clearPendingLogins(): void {\n let files: string[];\n try { files = readdirSync(stateDir()); } catch { return; }\n for (const file of files) {\n if (/^compute-login-[a-f0-9]{64}\\.json$/.test(file)) rmSync(join(stateDir(), file), { force: true });\n }\n}\n\nexport interface LoginOptions {\n baseUrl?: string;\n browser?: boolean;\n org?: string;\n json?: boolean;\n wait?: boolean;\n new?: boolean;\n}\n\nexport async function login(options: LoginOptions = {}): Promise<void> {\n const baseUrl = (options.baseUrl || envBaseUrl() || DEFAULT_BASE_URL).replace(/\\/+$/, '').replace(/\\/api\\/v1$/, '');\n if (!isTrustedPlatformHost(baseUrl) || !isSecurePlatformTransport(baseUrl)) {\n throw new Error('Sign in against a trusted ComputeSDK HTTPS host (or localhost for development).');\n }\n const resource = `${baseUrl}/api/v1`;\n const authUrl = `${baseUrl}/api/auth`;\n const pending = options.new ? undefined : readPending(baseUrl);\n if (options.json && options.wait && !pending) {\n throw new Error('No pending sign-in. Run compute login --json first to get the sign-in URL.');\n }\n const device = pending?.device ?? await postForm(`${authUrl}/device/code`, {\n client_id: BENCH_OAUTH_CLIENT_ID, scope: BENCH_OAUTH_SCOPE, resource,\n });\n if (device.error) throw new Error(device.error_description || device.error);\n const verificationUrl = device.verification_uri_complete || device.verification_uri;\n if (!device.device_code || !device.user_code || !verificationUrl ||\n !Number.isFinite(device.expires_in) || device.expires_in! <= 0 ||\n (device.interval !== undefined && (!Number.isFinite(device.interval) || device.interval <= 0))) {\n throw new Error('Invalid sign-in response. Run compute login to retry.');\n }\n const parsedUrl = new URL(verificationUrl);\n if (parsedUrl.origin !== new URL(baseUrl).origin || parsedUrl.username || parsedUrl.password) {\n throw new Error('The sign-in server returned an unexpected verification URL.');\n }\n const expiresAt = pending?.expiresAt ?? Date.now() + device.expires_in! * 1000;\n savePending({ baseUrl, device, expiresAt });\n if (options.json && !options.wait) {\n console.log(JSON.stringify({ verificationUrl, code: device.user_code, expiresAt: new Date(expiresAt).toISOString() }));\n return;\n }\n if (!options.json) {\n console.error(`Sign in to ComputeSDK: ${verificationUrl}`);\n console.error(`Confirm code: ${device.user_code}`);\n console.error('Waiting for approval. Press Ctrl-C to cancel.');\n if (options.browser !== false && !(await openBrowser(verificationUrl))) {\n console.error('Could not open a browser. Open the sign-in URL above to continue.');\n }\n }\n\n let intervalMs = (device.interval ?? 5) * 1000;\n while (Date.now() + intervalMs < expiresAt) {\n await delay(intervalMs);\n const token = await postForm(`${authUrl}/oauth2/token`, {\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n device_code: device.device_code, client_id: BENCH_OAUTH_CLIENT_ID, resource,\n }, expiresAt - Date.now());\n if (token.error === 'authorization_pending') continue;\n if (token.error === 'slow_down') {\n intervalMs += 5000;\n device.interval = intervalMs / 1000;\n savePending({ baseUrl, device, expiresAt });\n continue;\n }\n if (token.error === 'access_denied') {\n removePending(baseUrl, device.device_code);\n throw new Error('Sign-in was denied. Run compute login to try again.');\n }\n if (token.error === 'expired_token') break;\n if (token.error) throw new Error(token.error_description || token.error);\n if (!token.access_token || !Number.isFinite(token.expires_in) || token.expires_in! <= 0) {\n throw new Error('Invalid sign-in token response. Run compute login to retry.');\n }\n const credentials = {\n baseUrl, token: token.access_token, refreshToken: token.refresh_token,\n tokenExpiresAt: Date.now() + token.expires_in! * 1000,\n kind: 'oauth' as const, clientId: BENCH_OAUTH_CLIENT_ID,\n };\n await saveCredentials(credentials);\n removePending(baseUrl, device.device_code);\n // Approval normally binds the org server-side. Keep the shared store's\n // org cache current too, so directory-scoped sandbox selection is correct.\n // Use the token just issued, regardless of API keys in the environment.\n const auth: CliAuth = { ...credentials, apiBaseUrl: resource, authBaseUrl: authUrl };\n const me = await getMe(auth);\n const requestedOrg = options.org || process.env.COMPUTE_ORG;\n const override = requestedOrg ? me.organizations.find((o) => o.slug === requestedOrg) : undefined;\n if (requestedOrg && !override) {\n throw new Error(`Signed in, but not a member of organization ${requestedOrg}. Run compute org list.`);\n }\n let active = me.organizations.find((o) => o.id === me.activeOrganizationId);\n if (!me.activeOrganizationId && me.organizations.length === 1) {\n active = (await setActiveOrganization(auth, me.organizations[0].slug)).organization ?? undefined;\n }\n const effective = override ?? active;\n if (!effective) throw new Error('Signed in, but no active organization. Run compute org list, then compute org use <slug>.');\n // A one-off override must not change the server's shared active org or\n // cache it as the default for subsequent commands on this machine.\n await saveCredentials({\n ...credentials, ...(active ? { orgSlug: active.slug, orgId: active.id } : {}),\n });\n if (options.json) console.log(JSON.stringify({ signedIn: true, organization: effective.slug }));\n else console.error(`Signed in. ${override ? 'Using' : 'Active'} organization: ${effective.slug}.`);\n return;\n }\n removePending(baseUrl, device.device_code);\n throw new Error('Sign-in code expired. Run compute login to get a new code.');\n}\n","/**\n * The stored-login session behind `compute login`, `whoami` and `org …`,\n * resolved through `@benchsdk/cli` (shared `~/.benchsdk/credentials.json`).\n * That package reads only bench's env names, so compute's are passed in as\n * explicit overrides here.\n */\n\nimport type { CliAuth } from '@benchsdk/cli';\nimport { DEFAULT_BASE_URL, isSecurePlatformTransport, isTrustedPlatformHost } from '@computesdk/platform';\nimport { describeFetchFailure, isFetchFailure } from './net.js';\n\nexport function envBaseUrl(env: NodeJS.ProcessEnv = process.env): string | undefined {\n return env.COMPUTE_PLATFORM_URL || env.BENCHMARKS_PLATFORM_URL || undefined;\n}\n\n/**\n * `@benchsdk/cli` doesn't check where it sends a key, so compute applies its\n * own rule before handing COMPUTE_API_KEY over (as `resolvePlatformAuth`\n * does for every other command): a computesdk.com or loopback host, over\n * HTTPS off loopback. A key the user gives bench directly\n * (BENCHMARKS_PLATFORM_API_KEY) is bench's business and isn't checked here.\n */\nexport function assertComputeKeyDestination(baseUrl: string): void {\n const url = baseUrl.replace(/\\/+$/, '');\n if (!isTrustedPlatformHost(url)) {\n throw new Error(\n `Refusing to send COMPUTE_API_KEY to ${url}: it is not a computesdk.com or localhost host. ` +\n 'To use a key with a host you trust, set BENCHMARKS_PLATFORM_API_KEY for it instead.',\n );\n }\n if (!isSecurePlatformTransport(url)) {\n throw new Error(`Refusing to send COMPUTE_API_KEY over plaintext HTTP to ${url}; use https://.`);\n }\n}\n\n/**\n * `@benchsdk/cli` `resolveAuth` overrides. COMPUTE_API_KEY goes in as an\n * explicit key, so it wins over the stored login (as for every other compute\n * command), but only to a host compute itself would send it to;\n * BENCHMARKS_PLATFORM_API_KEY still works through bench's own env.\n */\nexport function benchAuthOverrides(\n opts: { baseUrl?: string } = {},\n env: NodeJS.ProcessEnv = process.env,\n): { baseUrl?: string; apiKey?: string } {\n const baseUrl = opts.baseUrl ?? envBaseUrl(env);\n const apiKey = env.COMPUTE_API_KEY || undefined;\n if (apiKey) assertComputeKeyDestination(baseUrl ?? DEFAULT_BASE_URL);\n return { baseUrl, apiKey };\n}\n\nexport async function benchAuth(opts: { baseUrl?: string } = {}): Promise<CliAuth> {\n const { resolveAuth } = await import('@benchsdk/cli');\n return resolveAuth(benchAuthOverrides(opts));\n}\n\nexport interface Organization {\n id: string;\n name: string;\n slug: string;\n}\n\n/** `GET /api/v1/me`, or for an org API key (no user) the key's org. */\nexport interface Whoami {\n user: { id: string; name?: string | null; email?: string | null } | null;\n activeOrganizationId: string | null;\n organizations: Organization[];\n credential?: 'api_key';\n}\n\nfunction errorReason(body: unknown): string | undefined {\n if (typeof body !== 'string' || body === '') return undefined;\n try {\n const parsed = JSON.parse(body) as { message?: unknown; error?: unknown };\n const reason = parsed.message ?? parsed.error;\n return typeof reason === 'string' ? reason : undefined;\n } catch {\n return body.slice(0, 200);\n }\n}\n\nfunction httpStatus(error: unknown): number | undefined {\n const status = (error as { status?: unknown } | null)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n/**\n * Org API keys carry no user, so `/api/v1/me` answers them 401 \"User\n * credential required\"; `/api/v1/actions/org` is the v1 route that names the\n * org a key belongs to.\n */\nasync function apiKeyOrganization(auth: CliAuth, apiKey: string): Promise<Organization> {\n const url = `${auth.apiBaseUrl}/actions/org`;\n let response: Response;\n try {\n response = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` } });\n } catch (error) {\n throw isFetchFailure(error) ? describeFetchFailure(error, url) : error;\n }\n const text = await response.text();\n if (!response.ok) {\n const reason = errorReason(text);\n throw new Error(\n `This API key has no user identity, and its organization could not be read (${response.status}${reason ? `: ${reason}` : ''}).`,\n );\n }\n const org = JSON.parse(text) as { organizationId: string; name: string; slug: string };\n return { id: org.organizationId, name: org.name, slug: org.slug };\n}\n\nexport async function fetchWhoami(auth: CliAuth): Promise<Whoami> {\n const { getMe } = await import('@benchsdk/cli');\n try {\n return await getMe(auth);\n } catch (error) {\n if (isFetchFailure(error)) throw describeFetchFailure(error, `${auth.apiBaseUrl}/me`);\n if (httpStatus(error) !== 401) throw error;\n const reason = errorReason((error as { body?: unknown }).body);\n if (auth.apiKey && !auth.token && reason === 'User credential required') {\n const org = await apiKeyOrganization(auth, auth.apiKey);\n return { user: null, activeOrganizationId: org.id, organizations: [org], credential: 'api_key' };\n }\n throw new Error(\n `Authentication failed (401 Unauthorized)${reason ? `: ${reason}` : ''}. ` +\n 'Check COMPUTE_API_KEY / the stored login, or run `compute login`.',\n );\n }\n}\n\nexport function formatWhoami(me: Whoami): string[] {\n const active = me.organizations.find((o) => o.id === me.activeOrganizationId);\n const who = me.user ? (me.user.email ?? me.user.name ?? me.user.id) : 'API key (no user identity)';\n return [\n who,\n `active org: ${active ? `${active.slug} (${active.id})` : '—'}${me.organizations.length > 1 ? ' — change with `compute org use <slug>`' : ''}`,\n ];\n}\n","/**\n * Node's fetch rejects a refused or unresolvable connection with a bare\n * `TypeError: fetch failed` (the socket error is only on `cause`), which\n * `@benchsdk/cli` prints as-is. These helpers name the URL and the cause.\n */\n\nexport function isFetchFailure(error: unknown): error is TypeError {\n return error instanceof TypeError && /fetch failed/i.test(error.message);\n}\n\nexport function describeFetchFailure(error: TypeError, url: string): TypeError {\n let target = url;\n try {\n const parsed = new URL(url);\n target = `${parsed.origin}${parsed.pathname}`;\n } catch {\n // keep the raw string\n }\n const cause = (error as { cause?: unknown }).cause;\n const described = new TypeError(`fetch failed (${target})${cause instanceof Error ? `: ${cause.message}` : ''}`);\n (described as { cause?: unknown }).cause = cause;\n return described;\n}\n\nfunction requestUrl(input: Parameters<typeof fetch>[0]): string {\n if (typeof input === 'string') return input;\n if (input instanceof URL) return input.href;\n return input.url;\n}\n\nexport function withFetchFailureContext(fetchImpl: typeof fetch): typeof fetch {\n return async (input, init) => {\n try {\n return await fetchImpl(input, init);\n } catch (error) {\n if (isFetchFailure(error)) throw describeFetchFailure(error, requestUrl(input));\n throw error;\n }\n };\n}\n","/**\n * `compute agents` — managed agents on the platform's `/api/v1/agents` API:\n * an agent is a durable config (name, prompt, harness, model, secrets,\n * provider order, volume); a session is one routed sandbox running it.\n *\n * Auth: identical to `compute actions`/`compute sandboxes` — --api-key /\n * COMPUTE_API_KEY / the stored `compute login` session. Types mirror the wire\n * shapes in benchmarks-platform `lib/agents/types.ts` — keep them in sync by\n * hand; the API is the contract.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { readFileSync } from 'node:fs';\nimport { client, fail, output, safeTerm, usageErrorOutput, type CommonOpts } from './actions.js';\n\n// ─── Wire types (mirror benchmarks-platform lib/agents/types.ts) ────────────\n\nexport type AgentHarness = 'pi' | 'opencode';\nexport type AgentSessionStatus = 'starting' | 'running' | 'stopped' | 'failed';\nexport type AgentEventKind = 'user' | 'turn' | 'status' | 'error';\n\nexport interface AgentVolume {\n diskId?: string;\n path?: string;\n bucket?: string;\n prefix?: string;\n region?: string;\n managed?: boolean;\n}\n\nexport interface AgentSummary {\n id: string;\n name: string;\n harness: AgentHarness;\n model: string | null;\n secrets: string[];\n providerOrder: string[] | null;\n volume: AgentVolume | null;\n sessionCount: number;\n createdAt: string;\n}\n\nexport interface AgentSessionSummary {\n id: string;\n agentId: string;\n status: AgentSessionStatus;\n sandboxId: string | null;\n error: string | null;\n createdAt: string;\n stoppedAt: string | null;\n}\n\nexport interface AgentEventView {\n seq: number;\n kind: AgentEventKind;\n payload: unknown;\n createdAt: string;\n}\n\n// ─── Rendering ───────────────────────────────────────────────────────────────\n\nfunction formatLocalTime(iso: string | null): string {\n if (iso === null) return '—';\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n const p = (n: number) => String(n).padStart(2, '0');\n return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;\n}\n\nfunction printAgent(a: AgentSummary): void {\n console.log(\n `${pc.cyan(safeTerm(a.name))} ${a.id.slice(0, 8)} ${a.harness}${a.model ? ` ${safeTerm(a.model)}` : ''} sessions: ${a.sessionCount} created: ${formatLocalTime(a.createdAt)}`,\n );\n}\n\nfunction printAgentDetail(a: AgentSummary): void {\n printAgent(a);\n if (a.providerOrder) console.log(` order: ${safeTerm(a.providerOrder.join(', '))}`);\n if (a.secrets.length > 0) console.log(` secrets: ${safeTerm(a.secrets.join(', '))}`);\n if (a.volume) console.log(` volume: ${a.volume.diskId ?? '—'} at ${a.volume.path ?? '—'}`);\n}\n\nfunction printSession(s: AgentSessionSummary): void {\n // Full session id — `send`, `events` and `stop` all take it as an argument.\n console.log(\n `${pc.cyan(s.id)} ${s.status} sandbox: ${s.sandboxId ?? '—'} ${formatLocalTime(s.createdAt)}${s.error ? ` ${pc.red(safeTerm(s.error))}` : ''}`,\n );\n}\n\n/** One journal line: who spoke and what the turn produced. */\nfunction printEvent(e: AgentEventView): void {\n const payload = (e.payload ?? {}) as Record<string, unknown>;\n if (e.kind === 'user') {\n console.log(`${pc.green('you')} #${e.seq} ${safeTerm(String(payload.message ?? ''))}`);\n return;\n }\n if (e.kind === 'turn') {\n const events = Array.isArray(payload.events) ? payload.events : [payload];\n for (const ev of events) {\n const o = ev as Record<string, unknown>;\n const text = o.text ?? o.message ?? o.content;\n if (typeof text === 'string') console.log(pc.dim(`#${e.seq}`) + ` ${safeTerm(text)}`);\n else console.log(pc.dim(`#${e.seq} ${safeTerm(JSON.stringify(o))}`));\n }\n return;\n }\n console.log(pc.dim(`#${e.seq} ${e.kind} ${safeTerm(JSON.stringify(payload))}`));\n}\n\nfunction authOpts(cmd: Command): Command {\n return cmd\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('--org <slug>', 'organization slug (or COMPUTE_ORG)')\n .option('--json', 'print the raw response');\n}\n\n// ─── Commands ────────────────────────────────────────────────────────────────\n\nexport function registerAgentsCommands(program: Command): void {\n const cmd = program\n .command('agents')\n .alias('ag')\n .description('Managed agents: durable agent configs running sessions in routed sandboxes')\n .enablePositionalOptions()\n .configureOutput({ outputError: usageErrorOutput });\n\n authOpts(cmd.command('list').alias('ls').description('List agents')).action(\n async (opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const agents: AgentSummary[] = [];\n let cursor: string | undefined;\n for (;;) {\n const res = await c.get<{ agents: AgentSummary[]; nextCursor: string | null }>(\n '/api/v1/agents',\n { cursor },\n );\n agents.push(...res.agents);\n if (res.nextCursor === null) break;\n cursor = res.nextCursor;\n }\n output(opts, { agents }, (r) => {\n if (r.agents.length === 0) console.log('No agents yet — `compute agents create`.');\n for (const a of r.agents) printAgent(a);\n });\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd\n .command('create <name>')\n .description('Create an agent (prompt via --prompt or --prompt-file)')\n .option('--prompt <text>', 'the agent\\'s mission / system prompt')\n .option('--prompt-file <path>', 'read the prompt from a file')\n .option('--harness <harness>', 'pi or opencode (default pi)')\n .option('--model <model>', 'model id passed to the harness')\n .option('--secret <name...>', 'vault secret names to inject')\n .option('--order <providers>', 'provider order, comma-separated')\n .option('--volume-disk <diskId>', 'Archil disk id to mount at --volume-path')\n .option('--volume-path <path>', 'volume mount path (default /agent)'),\n ).action(\n async (\n name: string,\n opts: CommonOpts & {\n prompt?: string;\n promptFile?: string;\n harness?: string;\n model?: string;\n secret?: string[];\n order?: string;\n volumeDisk?: string;\n volumePath?: string;\n },\n ) => {\n try {\n const prompt = opts.prompt ?? (opts.promptFile ? readFileSync(opts.promptFile, 'utf8') : undefined);\n if (!prompt?.trim()) fail(new Error('--prompt or --prompt-file is required'), opts);\n const volume =\n opts.volumeDisk !== undefined || opts.volumePath !== undefined\n ? { diskId: opts.volumeDisk, path: opts.volumePath }\n : undefined;\n const c = await client(opts);\n const res = await c.post<{ agent: AgentSummary }>('/api/v1/agents', {\n name,\n prompt,\n harness: opts.harness,\n model: opts.model,\n secrets: opts.secret,\n providerOrder: opts.order?.split(',').map((s) => s.trim()).filter(Boolean),\n volume,\n });\n output(opts, res, (r) => {\n printAgentDetail(r.agent);\n console.error(pc.dim(`agent ${r.agent.name} created — run it with \\`compute agents run ${r.agent.name} \"…\"\\``));\n });\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(cmd.command('describe <ref>').alias('get').description('Show one agent (id or name)')).action(\n async (ref: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ agent: AgentSummary }>(`/api/v1/agents/${encodeURIComponent(ref)}`);\n output(opts, res, (r) => printAgentDetail(r.agent));\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd\n .command('update <ref>')\n .description('Update an agent\\'s config')\n .option('--name <name>')\n .option('--prompt <text>')\n .option('--prompt-file <path>')\n .option('--harness <harness>')\n .option('--model <model>')\n .option('--secret <name...>')\n .option('--clear-secrets', 'remove all declared vault secrets')\n .option('--order <providers>')\n .option('--volume-disk <diskId>')\n .option('--volume-path <path>'),\n ).action(\n async (\n ref: string,\n opts: CommonOpts & {\n name?: string;\n prompt?: string;\n promptFile?: string;\n harness?: string;\n model?: string;\n secret?: string[];\n clearSecrets?: boolean;\n order?: string;\n volumeDisk?: string;\n volumePath?: string;\n },\n ) => {\n try {\n const prompt = opts.prompt ?? (opts.promptFile ? readFileSync(opts.promptFile, 'utf8') : undefined);\n const body: Record<string, unknown> = {\n name: opts.name,\n prompt,\n harness: opts.harness,\n model: opts.model,\n secrets: opts.clearSecrets ? [] : opts.secret,\n providerOrder: opts.order?.split(',').map((s) => s.trim()).filter(Boolean),\n };\n if (opts.volumeDisk !== undefined || opts.volumePath !== undefined) {\n body.volume = { diskId: opts.volumeDisk, path: opts.volumePath };\n }\n for (const k of Object.keys(body)) if (body[k] === undefined) delete body[k];\n const c = await client(opts);\n const res = await c.patch<{ agent: AgentSummary }>(\n `/api/v1/agents/${encodeURIComponent(ref)}`,\n body,\n );\n output(opts, res, (r) => printAgentDetail(r.agent));\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd\n .command('delete <ref>')\n .alias('rm')\n .description('Delete an agent and stop its live sessions')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (ref: string, opts: CommonOpts & { yes?: boolean }) => {\n try {\n const c = await client(opts);\n if (!opts.yes) {\n const res = await c.get<{ agent: AgentSummary }>(`/api/v1/agents/${encodeURIComponent(ref)}`);\n console.error(`Deleting agent ${pc.cyan(res.agent.name)} (${res.agent.id}). Pass -y to confirm.`);\n process.exit(1);\n }\n await c.del(`/api/v1/agents/${encodeURIComponent(ref)}`);\n output(opts, { deleted: ref }, () => console.log(`deleted ${ref}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n authOpts(cmd.command('sessions <ref>').description('List an agent\\'s sessions')).action(\n async (ref: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ sessions: AgentSessionSummary[] }>(\n `/api/v1/agents/${encodeURIComponent(ref)}/sessions`,\n );\n output(opts, res, (r) => {\n if (r.sessions.length === 0) console.log('No sessions yet.');\n for (const s of r.sessions) printSession(s);\n });\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd\n .command('run <ref> [message]')\n .description('Start a session on a routed sandbox and optionally send a first message')\n .option('--resume <sessionId>', 'resume a stopped conversation on a new sandbox using its persistent disk')\n .option('--size <size>', 'platform size for the session\\'s sandbox'),\n ).action(async (ref: string, message: string | undefined, opts: CommonOpts & { size?: string; resume?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ session: AgentSessionSummary; events: AgentEventView[] }>(\n `/api/v1/agents/${encodeURIComponent(ref)}/sessions`,\n { message, size: opts.size, resumeSessionId: opts.resume },\n );\n output(opts, res, (r) => {\n printSession(r.session);\n for (const e of r.events) printEvent(e);\n console.error(pc.dim(`session ${r.session.id} — continue with \\`compute agents send ${r.session.id} \"…\"\\``));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n authOpts(cmd.command('session <sessionId>').description('Show one session')).action(\n async (sessionId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ session: AgentSessionSummary }>(\n `/api/v1/agent-sessions/${encodeURIComponent(sessionId)}`,\n );\n output(opts, res, (r) => printSession(r.session));\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd.command('send <sessionId> <message>').description('Send a message; the agent runs a turn'),\n ).action(async (sessionId: string, message: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ events: AgentEventView[] }>(\n `/api/v1/agent-sessions/${encodeURIComponent(sessionId)}/events`,\n { message },\n );\n output(opts, res, (r) => {\n for (const e of r.events) printEvent(e);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n authOpts(\n cmd\n .command('events <sessionId>')\n .description('Show the session event journal; --follow polls for new events')\n .option('--after <seq>', 'only events above this seq')\n .option('--follow', 'poll every 2s until the session settles or Ctrl-C'),\n ).action(\n async (sessionId: string, opts: CommonOpts & { after?: string; follow?: boolean }) => {\n try {\n const c = await client(opts);\n let after = opts.after !== undefined ? Number(opts.after) : undefined;\n const once = async (): Promise<number> => {\n const res = await c.get<{ events: AgentEventView[]; latestSeq: number }>(\n `/api/v1/agent-sessions/${encodeURIComponent(sessionId)}/events`,\n { after: after !== undefined ? String(after) : undefined },\n );\n if (opts.json) {\n output(opts, res, () => {});\n } else {\n for (const e of res.events) printEvent(e);\n }\n after = res.latestSeq;\n return res.events.length;\n };\n if (!opts.follow) {\n await once();\n return;\n }\n // Polling for v1 — SSE replaces this when the API grows a stream.\n for (;;) {\n const status = (\n await c.get<{ session: AgentSessionSummary }>(\n `/api/v1/agent-sessions/${encodeURIComponent(sessionId)}`,\n )\n ).session.status;\n await once();\n if (status !== 'running' && status !== 'starting') break;\n await new Promise((r) => setTimeout(r, 2000));\n }\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd.command('stop <sessionId>').description('Stop a session and release its sandbox'),\n ).action(async (sessionId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n await c.del(`/api/v1/agent-sessions/${encodeURIComponent(sessionId)}`);\n output(opts, { stopped: sessionId }, () => console.log(`stopped ${sessionId}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/** Read-only diagnostics using the same credentials and org routing as commands. */\nimport { Command } from 'commander';\nimport type { SandboxSummary } from '@computesdk/platform';\nimport { client, output, safeTerm, type CommonOpts } from './actions.js';\nimport { resolveInstanceId } from './current-instance.js';\nimport type { ActionsOrg } from './actions-client.js';\nimport type { MarketCreditBalance } from './market.js';\n\nexport interface ComputeStatus {\n authenticated: boolean;\n ready: boolean;\n organization: ActionsOrg | null;\n credits: { balanceUsd: number; heldUsd: number } | null;\n sandbox: { id: string; status: string; provider: string | null } | null;\n routing: { ready: boolean; reason?: string } | null;\n issues: string[];\n}\nconst message = (error: unknown) => error instanceof Error ? error.message : String(error);\n\nexport async function getStatus(opts: CommonOpts): Promise<ComputeStatus> {\n const status: ComputeStatus = {\n authenticated: false, ready: false, organization: null, credits: null,\n sandbox: null, routing: null, issues: [],\n };\n try {\n const c = await client(opts);\n const selected = resolveInstanceId(undefined, opts);\n // Partial service failures should leave the other diagnostics visible.\n const [org, balance, route, sandbox] = await Promise.allSettled([\n c.org(),\n c.get<MarketCreditBalance>('/api/v1/billing/balance'),\n c.get<{ quote: { ok: boolean; reason?: string } }>('/api/v1/sandboxes/quote'),\n selected ? c.get<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${selected.id}`) : Promise.resolve(null),\n ]);\n if (org.status === 'fulfilled') {\n status.authenticated = true;\n status.organization = org.value;\n } else status.issues.push(`Authentication / organization: ${message(org.reason)}`);\n if (balance.status === 'fulfilled') {\n status.credits = { balanceUsd: balance.value.balanceMicroUsd / 1e6, heldUsd: balance.value.heldMicroUsd / 1e6 };\n } else status.issues.push(`Credits: ${message(balance.reason)}`);\n if (route.status === 'fulfilled') {\n status.routing = { ready: route.value.quote.ok, ...(route.value.quote.reason ? { reason: route.value.quote.reason } : {}) };\n } else status.issues.push(`Routing: ${message(route.reason)}`);\n if (sandbox.status === 'fulfilled' && sandbox.value) {\n const s = sandbox.value.sandbox;\n status.sandbox = { id: s.id, status: s.status, provider: s.provider };\n } else if (sandbox.status === 'rejected') {\n status.sandbox = { id: selected!.id, status: 'unknown', provider: null };\n status.issues.push(`Selected sandbox: ${message(sandbox.reason)}`);\n }\n status.ready = status.authenticated && status.routing?.ready === true;\n } catch (error) {\n status.issues.push(message(error));\n }\n return status;\n}\n\nexport function registerStatusCommand(program: Command): void {\n program.command('status')\n .description('Show authentication, effective organization, credits, selected sandbox and routing readiness')\n .option('--api-key <key>').option('--base-url <url>').option('--org <slug>')\n .option('--allow-untrusted-host')\n .option('--json', 'print machine-readable JSON')\n .option('--check', 'exit 1 unless authenticated and the default sandbox route is ready')\n .action(async (opts: CommonOpts & { check?: boolean }) => {\n const status = await getStatus(opts);\n output(opts, status, (s) => {\n console.log(`Authentication: ${s.authenticated ? 'verified' : 'not verified — run compute login'}`);\n console.log(`Organization: ${safeTerm(s.organization?.slug ?? 'unavailable')}`);\n console.log(`Credits: ${s.credits ? `$${s.credits.balanceUsd.toFixed(2)} ($${s.credits.heldUsd.toFixed(2)} held)` : 'unavailable'}`);\n console.log(`Sandbox: ${s.sandbox ? safeTerm(`${s.sandbox.id} · ${s.sandbox.status} · ${s.sandbox.provider ?? 'unknown provider'}`) : 'none selected — run compute new'}`);\n console.log(`Routing: ${s.routing ? s.routing.ready ? 'ready' : safeTerm(s.routing.reason ?? 'unavailable') : 'unavailable'}`);\n for (const issue of s.issues) console.log(safeTerm(issue));\n });\n if (opts.check && !status.ready) process.exitCode = 1;\n });\n}\n","/**\n * `compute bench …` — the benchmarks CLI (`@benchsdk/runner`'s `bench`\n * binary) run in-process. compute's env names and `--org` are mapped onto the\n * names bench reads, so `compute bench` talks to the same platform, with the\n * same key and org, as the rest of `compute`.\n */\n\nimport { DEFAULT_BASE_URL } from '@computesdk/platform';\nimport { withFetchFailureContext } from './net.js';\nimport { assertComputeKeyDestination } from './session.js';\n\n/** The canonical name first; the rest are dispatch aliases. */\nexport const BENCH_COMMANDS = new Set(['bench', 'benchmark']);\n\n/** Verbs `@benchsdk/runner` parses itself; its parser has no `--org`. */\nconst RUNNER_VERBS = new Set(['run', 'check', '__manifest']);\n\n/**\n * `args` is `process.argv.slice(2)`. Returns the bench argv when the\n * invocation is `compute [--org <slug>] bench …`; anything else is left to\n * commander.\n */\nexport function parseBenchDispatch(args: string[]): { argv: string[]; org?: string } | null {\n let org: string | undefined;\n let i = 0;\n while (i < args.length && !BENCH_COMMANDS.has(args[i])) {\n const arg = args[i];\n if (arg === '--org' && i + 1 < args.length) {\n org = args[i + 1];\n i += 2;\n } else if (arg.startsWith('--org=')) {\n org = arg.slice('--org='.length);\n i += 1;\n } else {\n return null;\n }\n }\n if (i >= args.length) return null;\n const argv = args.slice(i + 1);\n return org ? { argv, org } : { argv };\n}\n\n/** bench's own `--base-url <url>` / `--base-url=<url>`, which wins over its env. */\nfunction baseUrlFlag(argv: string[]): string | undefined {\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i];\n if (arg === '--') return undefined;\n if (arg === '--base-url') return argv[i + 1];\n if (arg.startsWith('--base-url=')) return arg.slice('--base-url='.length);\n }\n return undefined;\n}\n\nfunction hasOrgFlag(argv: string[]): boolean {\n for (const arg of argv) {\n if (arg === '--') return false;\n if (arg === '--org' || arg.startsWith('--org=')) return true;\n }\n return false;\n}\n\n/**\n * Maps compute's env names onto bench's without overriding settings bench\n * already has: COMPUTE_PLATFORM_URL → BENCHMARKS_PLATFORM_URL,\n * COMPUTE_API_KEY → BENCHMARKS_PLATFORM_API_KEY, and the org (compute's\n * leading `--org`, else COMPUTE_ORG) → a leading `--org` unless bench's argv\n * already has one. Empty variables count as unset. COMPUTE_API_KEY is only\n * handed over for a host compute would send it to (bench checks none): the\n * URL bench will use — its `--base-url`, else BENCHMARKS_PLATFORM_URL, else\n * COMPUTE_PLATFORM_URL — must be computesdk.com or loopback, over HTTPS.\n */\nexport function benchInvocation(\n argv: string[],\n env: NodeJS.ProcessEnv,\n computeOrg?: string,\n): { argv: string[]; env: Record<string, string> } {\n const out: Record<string, string> = {};\n if (env.COMPUTE_PLATFORM_URL && !env.BENCHMARKS_PLATFORM_URL) {\n out.BENCHMARKS_PLATFORM_URL = env.COMPUTE_PLATFORM_URL;\n }\n if (env.COMPUTE_API_KEY && !env.BENCHMARKS_PLATFORM_API_KEY) {\n assertComputeKeyDestination(\n baseUrlFlag(argv) || env.BENCHMARKS_PLATFORM_URL || env.COMPUTE_PLATFORM_URL || DEFAULT_BASE_URL,\n );\n out.BENCHMARKS_PLATFORM_API_KEY = env.COMPUTE_API_KEY;\n }\n const org = computeOrg || env.COMPUTE_ORG;\n if (!org || RUNNER_VERBS.has(argv[0]) || hasOrgFlag(argv)) return { argv, env: out };\n return { argv: ['--org', org, ...argv], env: out };\n}\n\n/** Runs bench; the runner exits the process itself once the command is done. */\nexport async function runBench(dispatch: { argv: string[]; org?: string }): Promise<void> {\n const inv = benchInvocation(dispatch.argv, process.env, dispatch.org);\n Object.assign(process.env, inv.env);\n globalThis.fetch = withFetchFailureContext(globalThis.fetch);\n const { run } = await import('@benchsdk/runner');\n await run(inv.argv);\n}\n","/**\n * `compute __manifest` — the command tree of the `compute` binary as JSON, in\n * the schema shared with `bench __manifest`. The benchmarks platform vendors\n * it to check that the commands its API surface map names really exist.\n * `bench …` is recorded as a passthrough by the bench versions compute\n * bundles; the bench manifest describes those commands.\n */\n\nimport type { Command, Option } from 'commander';\nimport { createRequire } from 'module';\nimport { existsSync, readFileSync, realpathSync } from 'fs';\nimport { dirname, join, sep } from 'path';\nimport { BENCH_COMMANDS } from './bench.js';\n\nexport const MANIFEST_COMMAND = '__manifest';\n\nexport interface ManifestCommand {\n path: string[];\n /** Every other spelling of `path` that commander accepts (aliases at any level). */\n aliases: string[][];\n args: string[];\n flags: string[];\n summary: string;\n}\n\nexport interface PackageVersion {\n package: string;\n version: string;\n /**\n * Set when the package resolves to a checkout (a `link:` override to a\n * branch build) rather than an npm install: its version number may not be\n * published, or may predate the commands it carries.\n */\n linked?: true;\n released?: false;\n}\n\nexport interface CliManifest {\n schemaVersion: 1;\n bin: 'compute';\n package: '@computesdk/cli';\n version: string;\n source: { repo: 'computesdk/computesdk'; released: boolean };\n globalFlags: string[];\n commands: ManifestCommand[];\n passthrough: {\n bench: { path: string[]; aliases: string[][]; runner: PackageVersion; cli: PackageVersion };\n };\n}\n\n/**\n * Version of `name` as resolved from `fromDir`. Walks up from the resolved\n * entry because the bench packages' `exports` maps hide `./package.json`.\n */\nexport function resolvedPackage(name: string, fromDir: string): { dir: string; version: string } {\n const require = createRequire(join(fromDir, 'noop.js'));\n let dir = dirname(require.resolve(name));\n for (;;) {\n const file = join(dir, 'package.json');\n if (existsSync(file)) {\n const pkg = JSON.parse(readFileSync(file, 'utf-8')) as { name?: string; version: string };\n if (pkg.name === name) return { dir, version: pkg.version };\n }\n const parent = dirname(dir);\n if (parent === dir) throw new Error(`package.json for ${name} not found from ${fromDir}`);\n dir = parent;\n }\n}\n\n/** An installed package's real path always runs through node_modules; a linked checkout's does not. */\nexport function isLinkedPackage(realDir: string): boolean {\n return !realDir.split(sep).includes('node_modules');\n}\n\nfunction packageVersion(name: string, resolved: { dir: string; version: string }): PackageVersion {\n const entry: PackageVersion = { package: name, version: resolved.version };\n if (isLinkedPackage(realpathSync(resolved.dir))) {\n entry.linked = true;\n entry.released = false;\n }\n return entry;\n}\n\n/** The bench versions `compute bench` runs: the runner, and the @benchsdk/cli the runner itself loads. */\nexport function bundledBench(fromDir: string): { runner: PackageVersion; cli: PackageVersion } {\n const runner = resolvedPackage('@benchsdk/runner', fromDir);\n const cli = resolvedPackage('@benchsdk/cli', runner.dir);\n return {\n runner: packageVersion('@benchsdk/runner', runner),\n cli: packageVersion('@benchsdk/cli', cli),\n };\n}\n\n// commander 11 has no public accessor for `{ hidden: true }` on commands.\nfunction isHidden(cmd: Command): boolean {\n return (cmd as unknown as { _hidden?: boolean })._hidden === true;\n}\n\nfunction flagsOf(cmd: Command): string[] {\n const flags = cmd\n .createHelp()\n .visibleOptions(cmd)\n .map((o: Option) => o.long ?? o.short)\n .filter((f): f is string => Boolean(f));\n return [...new Set(flags)];\n}\n\nfunction argsOf(cmd: Command): string[] {\n return cmd.registeredArguments.map((a) => {\n const name = `${a.name()}${a.variadic ? '...' : ''}`;\n return a.required ? `<${name}>` : `[${name}]`;\n });\n}\n\nfunction summaryOf(cmd: Command): string {\n return (cmd.summary() || cmd.description()).split('\\n')[0].trim();\n}\n\n/** Every combination of names along the path, minus the canonical one. */\nfunction aliasPaths(names: string[][]): string[][] {\n let paths: string[][] = [[]];\n for (const choices of names) paths = paths.flatMap((p) => choices.map((c) => [...p, c]));\n return paths.slice(1);\n}\n\nfunction walk(cmd: Command, ancestors: string[][], skip: Set<string>, out: ManifestCommand[]): void {\n for (const sub of cmd.commands) {\n if (isHidden(sub) || (ancestors.length === 0 && skip.has(sub.name()))) continue;\n const names = [...ancestors, [sub.name(), ...sub.aliases()]];\n out.push({\n path: names.map((n) => n[0]),\n aliases: aliasPaths(names),\n args: argsOf(sub),\n flags: flagsOf(sub),\n summary: summaryOf(sub),\n });\n walk(sub, names, skip, out);\n }\n}\n\nexport function buildCliManifest(\n program: Command,\n options: { version: string; released: boolean; packageDir: string },\n): CliManifest {\n const [benchName, ...benchAliases] = [...BENCH_COMMANDS];\n const commands: ManifestCommand[] = [];\n walk(program, [], new Set([benchName]), commands);\n return {\n schemaVersion: 1,\n bin: 'compute',\n package: '@computesdk/cli',\n version: options.version,\n source: { repo: 'computesdk/computesdk', released: options.released },\n globalFlags: flagsOf(program),\n commands,\n passthrough: {\n bench: {\n path: [benchName],\n aliases: benchAliases.map((a) => [a]),\n ...bundledBench(options.packageDir),\n },\n },\n };\n}\n\nexport function manifestJson(manifest: CliManifest): string {\n return `${JSON.stringify(manifest, null, 2)}\\n`;\n}\n\n/**\n * Compares a manifest file with the generated one. A `source.ref` stamped by\n * whoever vendored the file is ignored.\n */\nexport function manifestMatches(fileContent: string, generated: CliManifest): boolean {\n let committed: { source?: Record<string, unknown> };\n try {\n committed = JSON.parse(fileContent);\n } catch {\n return false;\n }\n if (committed.source) delete committed.source.ref;\n return JSON.stringify(committed) === JSON.stringify(generated);\n}\n\n/** Registers the hidden `compute __manifest [--released] [--check <file>]`. */\nexport function registerManifestCommand(\n program: Command,\n options: { version: string; packageDir: string },\n): void {\n program\n .command(MANIFEST_COMMAND, { hidden: true })\n .description('Print the command tree as JSON (for the benchmarks platform surface map)')\n .option('--released', 'mark the manifest as describing a version published to npm')\n .option('--check <file>', 'exit 1 unless <file> equals the generated manifest (ignoring source.ref)')\n .action((opts: { released?: boolean; check?: string }) => {\n const manifest = buildCliManifest(program, {\n version: options.version,\n released: Boolean(opts.released),\n packageDir: options.packageDir,\n });\n if (opts.check) {\n if (!manifestMatches(readFileSync(opts.check, 'utf-8'), manifest)) {\n console.error(\n `${opts.check} is out of date. Regenerate it with \\`pnpm --filter @computesdk/cli run manifest\\`.`,\n );\n process.exit(1);\n }\n console.log(`${opts.check} matches the ${manifest.commands.length}-command manifest.`);\n return;\n }\n process.stdout.write(manifestJson(manifest));\n });\n}\n","/**\n * `compute org members|invitations|invite|member set-role|member remove|leave`\n * and `compute invitations [show|accept|decline]` — the org's members and\n * invitations over the v1 organization routes, and the signed-in user's own\n * invitations.\n *\n * Org routes are called with the `current` org alias: the server resolves the\n * credential's org (an org API key's own org, or for a user login the org\n * `--org`/`COMPUTE_ORG` names through X-Org-Slug, else the active org).\n *\n * Writes that change who is in the org (invite, cancel, role change, remove,\n * leave, decline) ask for confirmation on a terminal and need `-y` elsewhere.\n * Accept has no confirmation: it is the invitee's own answer. Leave, accept,\n * decline and the user's own invitations need a user login; an org API key is\n * refused locally, and the server's `user_credential_required` is rendered\n * with the same hint for keys this CLI cannot recognise.\n */\n\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport {\n ActionsApiError,\n ActionsCliError,\n ActionsClient,\n codeForStatus,\n resolveActionsAuth,\n toErrorEnvelope,\n} from './actions-client.js';\nimport { output, usageErrorOutput, type CommonOpts } from './actions.js';\nimport { confirmWrite } from './confirm.js';\nimport { safeTerm } from './term.js';\n\n// Wire shapes: benchmarks-platform v1 organization member/invitation routes\n// (research design F-ORG-2 / F-ORG-3).\n\nexport interface OrgMember {\n id: string;\n userId: string;\n name: string | null;\n email: string;\n role: string;\n createdAt: string;\n}\n\nexport interface OrgInvitation {\n id: string;\n email: string;\n role: string;\n status: 'pending' | 'accepted' | 'rejected' | 'canceled' | (string & {});\n expiresAt: string;\n createdAt: string;\n inviterId: string;\n url: string;\n}\n\nexport interface UserInvitation extends OrgInvitation {\n organization: { id: string; name: string; slug: string };\n}\n\nexport interface InviteResponse {\n invitation: OrgInvitation;\n emailSent: boolean;\n emailError?: string;\n}\n\nexport interface AcceptResponse {\n member: OrgMember;\n organization: { id: string; name: string; slug: string };\n}\n\ntype WriteOpts = CommonOpts & { yes?: boolean };\n\nconst ORG_PATH = '/api/v1/organizations/current';\nconst MEMBER_ROLES = ['member', 'admin'] as const;\ntype MemberRole = (typeof MEMBER_ROLES)[number];\n\nconst USER_LOGIN_HINT =\n 'This needs a user login, and org API keys have no user: run `compute login`, and drop --api-key / unset COMPUTE_API_KEY.';\n\n/** Org API keys carry these prefixes; OAuth and session tokens do not. */\nexport function isOrgApiKey(key: string): boolean {\n return /^(bp|csdk)_/.test(key);\n}\n\nconst segment = (id: string) => encodeURIComponent(id);\n\nfunction orgName(opts: CommonOpts): string | undefined {\n return opts.org || process.env.COMPUTE_ORG || undefined;\n}\n\nasync function orgClient(opts: CommonOpts): Promise<ActionsClient> {\n return new ActionsClient(await resolveActionsAuth(opts));\n}\n\nasync function userClient(opts: CommonOpts, what: string): Promise<ActionsClient> {\n const auth = await resolveActionsAuth(opts);\n if (isOrgApiKey(auth.apiKey)) {\n throw new ActionsCliError(\n 'user_credential_required',\n `${what} needs a user login, and org API keys have no user. Run \\`compute login\\`, and drop --api-key / unset COMPUTE_API_KEY.`,\n );\n }\n return new ActionsClient(auth);\n}\n\nfunction apiHint(error: ActionsApiError): string | undefined {\n const body = error.body;\n if (body && typeof body === 'object' && typeof (body as { hint?: unknown }).hint === 'string') {\n return (body as { hint: string }).hint;\n }\n return error.code === 'user_credential_required' ? USER_LOGIN_HINT : undefined;\n}\n\n/**\n * Like `actions.ts` `fail`, plus the platform's `hint` (in the envelope and on\n * its own line) and the error code when the server sent one more specific\n * than the status implies.\n */\nfunction fail(error: unknown, opts: CommonOpts = {}): never {\n const hint = error instanceof ActionsApiError ? apiHint(error) : undefined;\n if (opts.json) {\n const envelope = toErrorEnvelope(error) as ReturnType<typeof toErrorEnvelope> & { error: { hint?: string } };\n if (hint) envelope.error.hint = hint;\n process.stderr.write(JSON.stringify(envelope) + '\\n');\n } else if (error instanceof ActionsApiError) {\n const code = error.code !== codeForStatus(error.status) ? ` ${error.code}` : '';\n console.error(pc.red(`Error (${error.status}${code}): ${error.message}`));\n if (hint) console.error(pc.dim(`hint: ${hint}`));\n } else {\n console.error(pc.red(`Error: ${error instanceof Error ? error.message : String(error)}`));\n }\n process.exit(1);\n}\n\nfunction memberRole(role: string, ownerMessage: string): MemberRole {\n if (role === 'owner') throw new ActionsCliError('invalid_argument', ownerMessage);\n if (!(MEMBER_ROLES as readonly string[]).includes(role)) {\n throw new ActionsCliError('invalid_argument', `Invalid role \"${role}\" — use member or admin.`);\n }\n return role as MemberRole;\n}\n\nfunction printTable(header: string[], rows: string[][]): void {\n const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));\n const line = (cells: string[]) => cells.map((c, i) => c.padEnd(widths[i])).join(' ').trimEnd();\n console.log(line(header));\n for (const row of rows) console.log(line(row));\n}\n\nexport function printMembers(res: { members: OrgMember[] }): void {\n if (res.members.length === 0) {\n console.log('No members.');\n return;\n }\n printTable(\n ['EMAIL', 'ROLE', 'NAME', 'MEMBER ID', 'JOINED'],\n res.members.map((m) => [safeTerm(m.email), safeTerm(m.role), safeTerm(m.name ?? '—'), safeTerm(m.id), safeTerm(m.createdAt)]),\n );\n}\n\nexport function printOrgInvitations(res: { invitations: OrgInvitation[] }): void {\n if (res.invitations.length === 0) {\n console.log('No pending invitations.');\n return;\n }\n printTable(\n ['ID', 'EMAIL', 'ROLE', 'EXPIRES', 'LINK'],\n res.invitations.map((i) => [safeTerm(i.id), safeTerm(i.email), safeTerm(i.role), safeTerm(i.expiresAt), safeTerm(i.url)]),\n );\n}\n\nexport function printUserInvitations(res: { invitations: UserInvitation[] }): void {\n if (res.invitations.length === 0) {\n console.log('No pending invitations.');\n return;\n }\n printTable(\n ['ID', 'ORG', 'ROLE', 'EXPIRES', 'ORG NAME'],\n res.invitations.map((i) => [\n safeTerm(i.id),\n safeTerm(i.organization.slug),\n safeTerm(i.role),\n safeTerm(i.expiresAt),\n safeTerm(i.organization.name),\n ]),\n );\n console.log(pc.dim('Accept with `compute invitations accept <id>`; decline with `compute invitations decline <id> -y`.'));\n}\n\nfunction printInvitationDetail(inv: UserInvitation): void {\n const rows: Array<[string, string]> = [\n ['invitation', safeTerm(inv.id)],\n ['org', `${safeTerm(inv.organization.slug)} (${safeTerm(inv.organization.name)})`],\n ['email', safeTerm(inv.email)],\n ['role', safeTerm(inv.role)],\n ['status', safeTerm(inv.status)],\n ['expires', safeTerm(inv.expiresAt)],\n ['link', safeTerm(inv.url)],\n ];\n for (const [k, v] of rows) console.log(`${k.padEnd(10)} ${v}`);\n}\n\nfunction printInvite(res: InviteResponse): void {\n const inv = res.invitation;\n console.log(`Invited ${safeTerm(inv.email)} as ${safeTerm(inv.role)} (invitation ${safeTerm(inv.id)}, expires ${safeTerm(inv.expiresAt)}).`);\n if (res.emailSent) {\n console.log(`Emailed ${safeTerm(inv.email)} the invitation link.`);\n } else {\n const reason = res.emailError ? ` (${safeTerm(res.emailError)})` : '';\n console.log(pc.yellow(`The invitation email was not sent${reason}; share the link instead.`));\n }\n console.log(`Link: ${safeTerm(inv.url)}`);\n}\n\n/** A member by id, user id or email (case-insensitive). */\nexport function findMember(members: OrgMember[], ref: string): OrgMember | undefined {\n const lower = ref.toLowerCase();\n return (\n members.find((m) => m.id === ref) ??\n members.find((m) => m.userId === ref) ??\n members.find((m) => m.email.toLowerCase() === lower)\n );\n}\n\nasync function resolveMember(c: ActionsClient, ref: string, opts: CommonOpts): Promise<OrgMember> {\n const { members } = await c.get<{ members: OrgMember[] }>(`${ORG_PATH}/members`);\n const member = findMember(members, ref);\n if (!member) {\n const org = orgName(opts);\n throw new ActionsCliError('not_found', `No member ${ref} in ${org ? `org ${org}` : 'this organization'}.`);\n }\n return member;\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+$/;\n\n/**\n * `common` adds the shared platform flags; every command here sends its usage\n * errors through the `--json` envelope.\n */\nfunction command(parent: Command, name: string): Command {\n return parent.command(name).configureOutput({ outputError: usageErrorOutput });\n}\n\nfunction common(cmd: Command): Command {\n return 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, for a user login (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\n/** Registers the member and invitation commands on the existing `compute org` group. */\nexport function registerOrgMemberCommands(org: Command): void {\n common(\n command(org, 'members').description(\"List the organization's members with their roles\"),\n ).action(async (opts: CommonOpts) => {\n try {\n const c = await orgClient(opts);\n output(opts, await c.get<{ members: OrgMember[] }>(`${ORG_PATH}/members`), printMembers);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const invitations = common(\n command(org, 'invitations')\n .description(\"List the organization's pending invitations with their links (owner/admin)\")\n .allowExcessArguments(false),\n ).action(async (opts: CommonOpts) => {\n try {\n const c = await orgClient(opts);\n output(opts, await c.get<{ invitations: OrgInvitation[] }>(`${ORG_PATH}/invitations`), printOrgInvitations);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(invitations, 'cancel')\n .description('Cancel a pending invitation; its link stops working (owner/admin)')\n .argument('<invitationId>', 'invitation id (see `compute org invitations`)')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (invitationId: string, opts: WriteOpts) => {\n try {\n await confirmWrite(`Cancel invitation ${invitationId}? Its link stops working.`, opts);\n const c = await orgClient(opts);\n const res = await c.del<{ invitation: OrgInvitation }>(`${ORG_PATH}/invitations/${segment(invitationId)}`);\n output(opts, res, (r) =>\n console.log(`Cancelled the invitation for ${safeTerm(r.invitation.email)} (${r.invitation.id}).`),\n );\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(org, 'invite')\n .description('Invite someone to the organization by email and print the invite link (owner/admin)')\n .argument('<email>', 'email address to invite')\n .option('--role <role>', 'member | admin (owners are invited in the web app)', 'member')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (email: string, opts: WriteOpts & { role: string }) => {\n try {\n const role = memberRole(opts.role, 'Owner invitations require the web app.');\n if (!EMAIL.test(email)) {\n throw new ActionsCliError('invalid_argument', `Invalid email \"${email}\".`);\n }\n const target = orgName(opts);\n await confirmWrite(`Invite ${email} as ${role}${target ? ` to ${target}` : ''}?`, opts);\n const c = await orgClient(opts);\n output(opts, await c.post<InviteResponse>(`${ORG_PATH}/invitations`, { email, role }), printInvite);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const member = command(org, 'member').description(\"Change a member's role or remove a member (owner/admin)\");\n\n common(\n command(member, 'set-role')\n .description(\"Change a member's role between member and admin (owner roles change in the web app)\")\n .argument('<member>', 'member id or email (see `compute org members`)')\n .argument('<role>', 'member | admin')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (ref: string, roleArg: string, opts: WriteOpts) => {\n try {\n const role = memberRole(roleArg, 'Owner role changes require the web app.');\n const c = await orgClient(opts);\n const target = await resolveMember(c, ref, opts);\n await confirmWrite(`Change ${target.email} from ${target.role} to ${role}?`, opts);\n const res = await c.patch<{ member: OrgMember }>(`${ORG_PATH}/members/${segment(target.id)}`, { role });\n output(opts, res, (r) => console.log(`${safeTerm(r.member.email)} is now ${safeTerm(r.member.role)}.`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(member, 'remove')\n .alias('rm')\n .description('Remove a member from the organization (owners are removed in the web app)')\n .argument('<member>', 'member id or email (see `compute org members`)')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (ref: string, opts: WriteOpts) => {\n try {\n const c = await orgClient(opts);\n const target = await resolveMember(c, ref, opts);\n const org = orgName(opts);\n await confirmWrite(\n `Remove ${target.email} (${target.role}) from ${org ?? 'the organization'}? They lose access at once.`,\n opts,\n );\n const res = await c.del<{ removed: OrgMember }>(`${ORG_PATH}/members/${segment(target.id)}`);\n output(opts, res, (r) =>\n console.log(`Removed ${safeTerm(r.removed.email)} (${safeTerm(r.removed.role)}) from ${org ?? 'the organization'}.`),\n );\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(org, 'leave')\n .description('Leave the organization (needs a user login; the last owner cannot leave)')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (opts: WriteOpts) => {\n try {\n const c = await userClient(opts, '`compute org leave`');\n const org = orgName(opts);\n await confirmWrite(`Leave ${org ?? 'the active organization'}? You lose access to it at once.`, opts);\n const res = await c.post<{ left: true }>(`${ORG_PATH}/leave`, {});\n output(opts, res, () => {\n console.log(`Left ${org ?? 'the organization'}.`);\n // Leaving revokes the user's OAuth grants for that org, so a login\n // granted through it stops working on the next call.\n console.log(\n pc.dim('If your login was granted for that organization, it no longer works: run `compute login` again.'),\n );\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n\n/** `compute invitations [show|accept|decline]` — the signed-in user's own invitations. */\nexport function registerInvitationsCommands(program: Command): void {\n const invitations = common(\n command(program, 'invitations')\n .description('Your pending invitations to other organizations (needs a user login)')\n .allowExcessArguments(false),\n ).action(async (opts: CommonOpts) => {\n try {\n const c = await userClient(opts, '`compute invitations`');\n output(opts, await c.get<{ invitations: UserInvitation[] }>('/api/v1/me/invitations'), printUserInvitations);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(invitations, 'show')\n .description('Show one of your invitations')\n .argument('<invitationId>', 'invitation id (see `compute invitations`)'),\n ).action(async (invitationId: string, opts: CommonOpts) => {\n try {\n const c = await userClient(opts, '`compute invitations show`');\n const res = await c.get<{ invitation: UserInvitation }>(`/api/v1/invitations/${segment(invitationId)}`);\n output(opts, res, (r) => printInvitationDetail(r.invitation));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(invitations, 'accept')\n .description('Accept an invitation and join its organization (no confirmation)')\n .argument('<invitationId>', 'invitation id (see `compute invitations`)')\n .option('-y, --yes', 'accepted for symmetry with decline; accept never asks'),\n ).action(async (invitationId: string, opts: WriteOpts) => {\n try {\n const c = await userClient(opts, '`compute invitations accept`');\n const res = await c.post<AcceptResponse>(`/api/v1/invitations/${segment(invitationId)}/accept`, {});\n output(opts, res, (r) => {\n const slug = safeTerm(r.organization.slug);\n console.log(`Joined ${slug} as ${safeTerm(r.member.role)}.`);\n console.log(pc.dim(`Switch to it with \\`compute org use ${slug}\\`, or pass --org ${slug}.`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(invitations, 'decline')\n .description('Decline an invitation')\n .argument('<invitationId>', 'invitation id (see `compute invitations`)')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (invitationId: string, opts: WriteOpts) => {\n try {\n const c = await userClient(opts, '`compute invitations decline`');\n await confirmWrite(`Decline invitation ${invitationId}? Its link stops working.`, opts);\n const res = await c.post<{ invitation: OrgInvitation & Partial<Pick<UserInvitation, 'organization'>> }>(\n `/api/v1/invitations/${segment(invitationId)}/decline`,\n {},\n );\n output(opts, res, (r) => {\n const org = r.invitation.organization?.slug;\n console.log(org ? `Declined the invitation to ${safeTerm(org)}.` : `Declined invitation ${r.invitation.id}.`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA0BA,SAAS,mBACd,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CAAC;AAMH,wBAAwB,SAAS;AAAA,EAC/B,SAAS,YAAY;AAAA,EACrB,YAAYP,MAAKH,YAAW,IAAI;AAClC,CAAC;AAOD,eAAe,OAAO;AACpB,QAAM,QAAQ,mBAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC;AACtD,MAAI,OAAO;AACT,UAAM,SAAS,KAAK;AACpB;AAAA,EACF;AACA,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAMO,KAAG,IAAI;AAAA,SAAY,MAAM,OAAO,EAAE,CAAC;AACjD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["pc","list","common","settings","pc","path","common","runs","p","list","pc","common","path","pc","plural","common","client","output","fail","pc","common","client","output","fail","Option","pc","readFileSync","message","p","client","path","program","common","org","p","requireModule","fs","path","relative","segment","scanLocalTree","path","fileURLToPath","createHash","relative","p","Command","Option","pc","readFileSync","fileURLToPath","dirname","join","pc","pc","p","program","common","list","pc","RATE_UNITS","formatRate","pc","p","program","common","pc","MICRO_USD","program","common","p","pc","program","fs","path","Readable","Command","Option","pc","tar","spawnSync","mkdirSync","readFileSync","writeFileSync","join","org","p","common","fs","path","spawnSync","randomUUID","fs","path","createRequire","requireModule","response","spawnSync","relative","ignoredPaths","p","randomUUID","program","createHash","mkdirSync","readFileSync","writeFileSync","renameSync","rmSync","readdirSync","homedir","join","delay","DEFAULT_BASE_URL","isSecurePlatformTransport","isTrustedPlatformHost","DEFAULT_BASE_URL","isSecurePlatformTransport","isTrustedPlatformHost","isTrustedPlatformHost","isSecurePlatformTransport","DEFAULT_BASE_URL","org","getMe","command","resolve","stateDir","join","homedir","createHash","readFileSync","mkdirSync","writeFileSync","renameSync","rmSync","readdirSync","DEFAULT_BASE_URL","isTrustedPlatformHost","isSecurePlatformTransport","delay","p","pc","org","Option","command","program","Command","list","resolve","path","Readable","pc","readFileSync","formatLocalTime","p","program","message","org","program","DEFAULT_BASE_URL","org","DEFAULT_BASE_URL","createRequire","existsSync","readFileSync","realpathSync","dirname","join","sep","require","createRequire","join","dirname","existsSync","readFileSync","sep","realpathSync","p","program","pc","fail","printTable","org","program","__filename","fileURLToPath","__dirname","dirname","readFileSync","join","Command","Option","getMe","pc","org","loadCredentials","saveCredentials","setActiveOrganization"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.pnpm/tsup@8.5.0_jiti@2.7.0_postcss@8.5.6_tsx@4.20.3_typescript@5.8.3_yaml@2.9.1/node_modules/tsup/assets/esm_shims.js","../src/actions-client.ts","../src/term.ts","../src/settings.ts","../src/confirm.ts","../src/actions-runs.ts","../src/actions-workflows.ts","../src/actions-repos.ts","../src/actions-integrations.ts","../src/actions.ts","../src/exec.ts","../src/sync-fs.ts","../src/snapshot-engine.ts","../src/index.ts","../src/providers.ts","../src/byok.ts","../src/rate-display.ts","../src/market.ts","../src/credits.ts","../src/option-inheritance.ts","../src/sandboxes.ts","../src/current-instance.ts","../src/sandbox-billing.ts","../src/sync.ts","../src/sync-retention.ts","../src/onboarding.ts","../src/login.ts","../src/session.ts","../src/net.ts","../src/agents.ts","../src/status.ts","../src/bench.ts","../src/manifest.ts","../src/org-members.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * The platform transport moved to `@computesdk/platform` in cli 2.x — this\n * file re-exports the moved names under their old `Actions*` names for one\n * release, keeps the Actions wire types, and defines `ActionsClient` as the\n * `PlatformClient` subclass with the Actions `org()` endpoint.\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 */\nimport {\n DEFAULT_BASE_URL,\n PlatformApiError,\n PlatformClient,\n PlatformClientError,\n codeForStatus,\n errorDetails,\n isSecurePlatformTransport,\n isTrustedPlatformHost,\n readSseEvents,\n readSseNamedEvents,\n resolvePlatformAuth,\n toErrorEnvelope,\n} from '@computesdk/platform';\nimport type {\n PlatformAuth,\n PlatformClientErrorCode,\n PlatformErrorEnvelope,\n StoredPlatformAuth,\n StoredPlatformAuthResolver,\n} from '@computesdk/platform';\n\nexport {\n DEFAULT_BASE_URL,\n PlatformApiError as ActionsApiError,\n PlatformClientError as ActionsCliError,\n codeForStatus,\n errorDetails,\n isSecurePlatformTransport as isSecureActionsTransport,\n isTrustedPlatformHost as isTrustedActionsHost,\n readSseEvents,\n readSseNamedEvents,\n toErrorEnvelope,\n};\n\nconst CLI_CREDENTIALS_HINT =\n 'Set COMPUTE_API_KEY, pass --api-key, or run `compute login`.';\n\n/** `resolvePlatformAuth` with the CLI's flag-style credentials hint. */\nexport function resolveActionsAuth(\n opts: Parameters<typeof resolvePlatformAuth>[0],\n resolveStored?: StoredPlatformAuthResolver,\n): Promise<PlatformAuth> {\n return resolvePlatformAuth(opts, resolveStored, CLI_CREDENTIALS_HINT);\n}\nexport type {\n PlatformAuth as ActionsAuth,\n PlatformClientErrorCode as ActionsCliErrorCode,\n PlatformErrorEnvelope as ActionsErrorEnvelope,\n StoredPlatformAuth,\n StoredPlatformAuthResolver,\n};\n\nexport interface ActionsOrg {\n organizationId: string;\n name: string;\n slug: string;\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\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\n/** A row of `GET /api/v1/actions/workflows`: the dispatch picker row plus its controls and latest run. */\nexport interface CiWorkflowListItem extends CiWorkflow {\n /** Runs at all: the repo is enabled and the workflow is not user-disabled. */\n enabled: boolean;\n repoEnabled: boolean;\n userDisabledAt: string | null;\n /** Per-workflow placement order; null inherits the org order. */\n providerOrder: string[] | null;\n /** Per-workflow snapshot cap; null is the dynamic pool, 0 is off. */\n snapshotCap: number | null;\n lastRun: { id: string; conclusion: CiConclusion; queuedAt: string } | null;\n}\n\n/** A workflow file only the listed ref has: dispatched by repo and path on that ref. */\nexport interface CiRefOnlyWorkflow {\n name: string;\n path: string;\n inputs: CiWorkflowInput[];\n dispatchable: boolean;\n}\n\nexport interface CiWorkflowsResponse {\n workflows: CiWorkflowListItem[];\n /** Present when the list was asked for with `ref`. */\n refOnly?: CiRefOnlyWorkflow[];\n}\n\n/** `PATCH /api/v1/actions/workflows`: a workflow's user-owned controls after the change. */\nexport interface CiWorkflowControls {\n repoFullName: string;\n path: string;\n enabled: boolean;\n userDisabledAt: string | null;\n providerOrder: string[] | null;\n snapshotCap: number | null;\n}\n\nexport type CiConclusion = 'passed' | 'failed' | 'running' | 'cancelled' | 'none';\n\nexport interface CiScheduleWorkflow {\n repoFullName: string;\n workflowName: string;\n workflowPath: string;\n}\n\nexport interface CiScheduleRun extends CiScheduleWorkflow {\n id: string;\n event: string;\n ref: string;\n status: 'queued' | 'running' | 'completed';\n conclusion: string;\n startedAt: string | null;\n createdAt: string;\n}\n\n/** `GET /api/v1/actions/schedule`: daily totals, paginated runs and capped fires. */\nexport interface CiSchedule {\n from: string;\n to: string;\n timeZone: string;\n countsTruncated: boolean;\n days: (CiScheduleWorkflow & {\n date: string;\n runs: { total: number; byConclusion: Record<string, number>; items: CiScheduleRun[] };\n upcoming: { total: number; items: string[] };\n })[];\n runs: CiScheduleRun[];\n nextCursor: string | null;\n upcoming: (CiScheduleWorkflow & {\n scheduleId: string;\n cron: string;\n description: string;\n occurrences: string[];\n occurrenceCount: number;\n truncated: boolean;\n countTruncated: boolean;\n })[];\n}\n\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 /** When the run was archived (hidden from the default lists), else null. */\n archivedAt?: string | null;\n jobs: CiJob[];\n logTail: string[];\n /**\n * Benchmark runs this run produced (linked by `benchmark_run_executions.ci_run_id`).\n * `[]` when the workflow ran no benchmark; a benchmark still running is listed\n * with `providers: []` until its summary is uploaded.\n */\n benchmarks?: CiRunBenchmarkResult[];\n}\n\n/** The `(startedAt, id)` position after a day page's last row. */\nexport interface CiRunsCursor {\n startedAt: string;\n id: string;\n}\n\n/** `GET /api/v1/actions/runs/day/{day}`: one page; `nextCursor` is null on the last. */\nexport interface CiRunsPage {\n runs: CiRun[];\n nextCursor?: CiRunsCursor | null;\n}\n\n/** One row of `GET /api/v1/actions/run-days`. */\nexport interface CiRunDay {\n day: string;\n count: number;\n}\n\n/** `POST /api/v1/actions/runs/archive`: how many runs changed, and the stamp (null when unarchiving). */\nexport interface CiRunArchiveResponse {\n archived: number;\n archivedAt: string | null;\n}\n\n/** One benchmark run linked to an Actions run, from `GET /api/v1/actions/runs/{id}`. */\nexport interface CiRunBenchmarkResult {\n benchmarkSlug: string;\n benchmarkName: string;\n benchmarkRunId: string;\n status: string;\n dashboardUrl: string;\n startedAt: string | null;\n endedAt: string | null;\n providers: CiRunBenchmarkProvider[];\n}\n\n/** One provider row of a benchmark result; `dimensions: {}` is the provider's overall row. */\nexport interface CiRunBenchmarkProvider {\n provider: string;\n dimensions: Record<string, unknown>;\n compositeScore: number | null;\n scoringVersion: string | null;\n successRate: number | null;\n skipped: boolean;\n skipReason: string | null;\n metrics: Record<string, { median: number; p95: number; p99: number; unit: string }>;\n scalars: Record<string, number>;\n scalarUnits: Record<string, 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 /** The stored key's last verification; absent from servers that predate it. */\n status?: 'connected' | 'error' | 'unconfigured';\n statusDetail?: string | null;\n /** The stored key's masked hint — never the key. */\n keyHint?: string | null;\n lastCheckedAt?: string | null;\n}\n\n/** A GitHub App installation on `GET /api/v1/actions/installations` — never a token. */\nexport interface CiInstallation {\n githubInstallationId: number;\n account: string;\n accountType: string | null;\n accountAvatarUrl: string | null;\n appSlug: string;\n repoSelection: 'all' | 'selected';\n suspended: boolean;\n suspendedAt: string | null;\n installedAt: string;\n configureUrl: string | null;\n repos: { granted: number; enabled: number };\n}\n\nexport interface CiInstallationsResponse {\n installations: CiInstallation[];\n}\n\n/**\n * Where a signed-in owner/admin starts an install in their browser. The\n * platform never mints the signed install link for an API credential.\n */\nexport interface CiInstallLink {\n configured: boolean;\n url: string | null;\n /** GitHub only. */\n appSlug?: string | null;\n}\n\n/** The org's Slack connection on `GET /api/v1/actions/slack` — never the bot token. */\nexport interface CiSlackConnection {\n installed: boolean;\n teamName: string | null;\n channelId: string | null;\n channelName: string | null;\n notifyOn: 'all' | 'failure';\n brief: { enabled: boolean; times: string[]; timeZone: string; categories: string[] };\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\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: CiApiRepo[];\n}\n\nexport type CiPollSchedule = 'disabled' | 'never' | 'scheduled';\n\n/**\n * A repo on `GET /api/v1/actions/repos` since the platform added poll state\n * and run counts. Older deployments send only the `CiRepo` fields.\n */\nexport interface CiApiRepo extends CiRepo {\n pollIntervalSeconds: number;\n /** `disabled`: repo off; `never`: enabled but not polled yet; `scheduled`: `nextPollDueAt` is set. */\n pollSchedule: CiPollSchedule;\n nextPollDueAt: string | null;\n lastPollErrorAt: string | null;\n lastPollSucceededAt: string | null;\n lastChangeAt: string | null;\n /** Unarchived runs (reliability runs included), as the repository index counts them. */\n runs: { total: number; lastRunState: CiConclusion | null; lastRunQueuedAt: string | null };\n}\n\n/** `POST /api/v1/actions/repos/poll`: a poll that failed against the remote still answers with `error` set. */\nexport interface CiRepoPollResponse {\n fullName: string;\n repoId: string;\n polled: true;\n error: string | null;\n createdRunIds: string[];\n repo: CiApiRepo;\n}\n\n/** One ref of `GET /api/v1/actions/repos/branches`: a watched cursor, or run history alone. */\nexport interface CiBranch {\n /** Fully qualified: refs/heads/…, refs/pull/<n>/head, refs/tags/… */\n ref: string;\n prNumber: number | null;\n /** True while a live ref cursor polls the ref; false: run history only. */\n watched: boolean;\n runCount: number;\n /** \"\" when the ref has no run in view. */\n latestRunId: string;\n lastRunAt: string;\n}\n\nexport interface CiBranchesResponse {\n repo: string;\n defaultBranch: string;\n branches: CiBranch[];\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\n/** `POST /api/v1/actions/repos/sync`: per-account result plus the refreshed repo list. */\nexport interface CiRepoSyncResponse {\n accounts: Array<{ account: string; error: string | null }>;\n repos: Array<Pick<CiRepo, 'repoId' | 'fullName' | 'enabled' | 'private' | 'authType' | 'githubInstallationId'>>;\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\n/**\n * The CLI's platform client — `PlatformClient` plus the Actions-only\n * `org()` endpoint the dashboard URL builders need.\n */\nexport class ActionsClient extends PlatformClient {\n private orgPromise: Promise<ActionsOrg> | null = null;\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","/** Terminal-safe text and status labels shared by the `compute actions` modules. */\n\nimport pc from 'picocolors';\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\n/**\n * `safeTerm` for multi-line text (error messages, hints): newlines and tabs\n * stay, every other control character is replaced.\n */\nexport function safeTermText(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F]/g, '�');\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 // Anything else is the server's string verbatim.\n default: return safeTerm(conclusion);\n }\n}\n","/**\n * `compute sandboxes settings` / `compute actions settings` — one lane's\n * router. Routing is ComputeSDK's managed accounts: the default routing, or\n * the org's own managed order (`--routing`). BYOK is separate: whether the\n * org's own keys are used (`--byok off|first|fallback|only`) and in what\n * order (`--byok-order`), over `GET/PATCH /api/v1/{lane}/routing`. Sizes\n * and pools stay on `GET/PATCH /api/v1/{lane}/settings`. Keys themselves are\n * `compute byok`.\n *\n * `--cap`/`--general-cap` prices use the same parser as `--max-price` — a\n * unit is required (`0.12/hour`), so a bare dollar amount never silently\n * becomes per-second pricing.\n */\n\nimport { Command, Option } from 'commander';\nimport pc from 'picocolors';\nimport { ActionsApiError, ActionsCliError, type ActionsClient } from './actions-client.js';\n\nimport { safeTerm } from './term.js';\nimport type { CommonOpts } from './actions.js';\n\n/**\n * The helpers these commands need from `actions.js`, injected by the caller —\n * `actions.ts` imports this module, so a runtime import the other way would\n * create a cycle.\n */\nexport interface SettingsDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n usageErrorOutput: (str: string, write: (str: string) => void, argv?: string[]) => void;\n}\n\nexport const PLATFORM_SIZES = ['small', 'medium', 'large', 'xlarge', '2xlarge', '3xlarge'] as const;\n\ntype Rate = { usd: number; per: string };\n\n/** The settings GET/PATCH wire shape — fields shared by both lanes; the\n * `actions*` keys are the sandbox lane's inherit references. */\nexport interface LaneSettings {\n providerOrder: string[];\n actionsProviderOrder?: string[];\n marketCap?: Rate | null;\n actionsMarketCap?: Rate | null;\n marketOrderType?: 'market' | 'limit' | null;\n actionsMarketOrderType?: 'market' | 'limit';\n marketCaps?: Record<string, Rate | null>;\n referencePrices?: Record<string, Rate | null>;\n providerResources?: Record<\n string,\n { cpus?: number; memoryMb?: number; ephemeralDiskMb?: number }\n >;\n /** Preset name matching each providerResources entry, when one does. */\n providerResourcePresets?: Record<string, string | null>;\n warmPool?: Record<string, number>;\n snapshotPool?: Record<string, number>;\n /** Actions lane: the order an org with no providerOrder stored places on. */\n defaultProviderOrder?: string[];\n /** Actions lane: each provider's size presets, the names --resources takes. */\n sizePresets?: Record<string, { name: string; label: string }[]>;\n /** Actions lane: which workflows cap snapshots and which hold live ones. */\n snapshotSummary?: {\n workflows: { repoFullName: string; path: string; name: string; snapshotCap: number | null }[];\n live: { repoFullName: string; workflowPath: string | null; count: number }[];\n };\n}\n\n/**\n * `--max-price <usd>/<unit>` (and the `--cap`/`--general-cap` rates): the\n * unit is required — inline (`0.12/hour`) or via the `per` argument — so a\n * bare `--max-price 0.12` never silently defaults to per-second pricing.\n */\nexport function 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 'a unit is required — write it as <usd>/<unit> (e.g. 0.12/hour)',\n );\n }\n return { usd, per: unit };\n}\n\n/** One `<size>=<usd>/<unit>` or `<size>=none` `--cap` flag value. */\nfunction parseSizeCap(entry: string): { size: string; cap: Rate | null } {\n const eq = entry.indexOf('=');\n const size = eq === -1 ? entry : entry.slice(0, eq);\n if (!(PLATFORM_SIZES as readonly string[]).includes(size)) {\n throw new Error(\n `Invalid --cap \"${entry}\" — size must be one of ${PLATFORM_SIZES.join(', ')}.`,\n );\n }\n const value = eq === -1 ? '' : entry.slice(eq + 1);\n if (value === 'none') return { size, cap: null };\n const cap = parseMaxPrice(value, undefined);\n if (!cap) {\n throw new Error(\n `Invalid --cap \"${entry}\" — expected <size>=<usd>/<unit> (e.g. small=0.11/hour) or <size>=none.`,\n );\n }\n return { size, cap };\n}\n\n/** Mirrors MAX_WARM_POOL_SIZE in benchmarks-platform lib/providers/org-settings.ts. */\nexport const MAX_WARM_POOL_SIZE = 16;\n\n/** Mirrors MAX_SNAPSHOT_POOL_SIZE in benchmarks-platform lib/providers/org-settings.ts. */\nexport const MAX_SNAPSHOT_POOL_SIZE = 32;\n\n/** One `<provider>=<preset>` or `<provider>=none` `--resources` value; the server checks the names. */\nexport function parseResourcesFlag(entry: string): { provider: string; preset: string | null } {\n const eq = entry.indexOf('=');\n const provider = eq === -1 ? '' : entry.slice(0, eq).trim();\n const preset = eq === -1 ? '' : entry.slice(eq + 1).trim();\n if (provider === '' || preset === '') {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --resources \"${entry}\" — expected <provider>=<preset> (e.g. blaxel=large) or <provider>=none.`,\n );\n }\n return { provider, preset: preset === 'none' ? null : preset };\n}\n\n/** One `<provider[:region]>=<n>` pool-flag value, n in 0..max (0 clears the entry). */\nfunction parsePoolFlag(flag: string, entry: string, max: number): { key: string; size: number } {\n const eq = entry.indexOf('=');\n const key = eq === -1 ? '' : entry.slice(0, eq).trim();\n const value = eq === -1 ? '' : entry.slice(eq + 1).trim();\n const size = Number(value);\n if (key === '' || !/^\\d+$/.test(value) || size > max) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid ${flag} \"${entry}\" — expected <provider>[:<region>]=<n> with n in 0..${max} (0 clears it).`,\n );\n }\n return { key, size };\n}\n\n/** One `<provider[:region]>=<n>` `--warm-pool` value, n in 0..16 (0 clears the entry). */\nexport function parseWarmPoolFlag(entry: string): { key: string; size: number } {\n return parsePoolFlag('--warm-pool', entry, MAX_WARM_POOL_SIZE);\n}\n\n/** One `<provider[:region]>=<n>` `--snapshot-pool` value, n in 0..32 (0 clears the entry). */\nexport function parseSnapshotPoolFlag(entry: string): { key: string; size: number } {\n return parsePoolFlag('--snapshot-pool', entry, MAX_SNAPSHOT_POOL_SIZE);\n}\n\n/** Repeated pool flags as the settings patch: entry → size. */\nfunction poolPatch(entries: string[], parse: (entry: string) => { key: string; size: number }): Record<string, number> {\n const pool: Record<string, number> = {};\n for (const entry of entries) {\n const { key, size } = parse(entry);\n pool[key] = size;\n }\n return pool;\n}\n\nfunction formatResources(r: { cpus?: number; memoryMb?: number; ephemeralDiskMb?: number }): string {\n const parts: string[] = [];\n if (r.cpus !== undefined) parts.push(`${r.cpus} vCPU`);\n if (r.memoryMb !== undefined) parts.push(`${r.memoryMb} MB`);\n if (r.ephemeralDiskMb) parts.push(`${r.ephemeralDiskMb} MB disk`);\n return parts.join(' / ') || '—';\n}\n\nexport const BYOK_MODES = ['off', 'first', 'fallback', 'only'] as const;\nexport type ByokMode = (typeof BYOK_MODES)[number];\n\nconst BYOK_MODE_HELP: Record<ByokMode, string> = {\n off: \"not used: managed accounts only\",\n first: 'your keys first, then managed accounts',\n fallback: 'managed accounts first, then your keys',\n only: 'your keys only, never managed accounts',\n};\n\n/** How a router orders its managed accounts. */\nexport const MANAGED_STRATEGIES = ['computesdk', 'cheapest'] as const;\nexport type ManagedStrategy = (typeof MANAGED_STRATEGIES)[number] | 'custom';\n\nconst STRATEGY_LABEL: Record<ManagedStrategy, string> = {\n computesdk: 'ComputeSDK (recommended)',\n cheapest: 'Cheapest',\n custom: 'Custom',\n};\n\n/** `GET/PATCH /api/v1/{lane}/routing`. */\nexport interface LaneRouting {\n /** `computesdk` (the default), `cheapest` or `custom`; absent from older servers. */\n strategy?: ManagedStrategy;\n /** The org's own managed order when custom, else \"default\" (older servers: the only field). */\n routing: 'default' | string[];\n /** The managed accounts the router walks now, in order. */\n managed: string[];\n /** The size `managed` is ordered for (cheapest ranks by price at a size). */\n size?: string;\n /** Every live managed account a custom order may name. */\n available: string[];\n /** `order` is what placement uses; `inherits` (Sandboxes) says it comes from the Actions router. */\n byok: { mode: ByokMode; order: string[]; inherits?: boolean };\n}\n\nconst arrow = (list: string[]): string => list.join(' → ');\n\n/** The router: managed routing first (the default path), then BYOK. */\nexport function printLaneRouting(r: LaneRouting, lane: 'actions' | 'sandboxes'): void {\n const label = (text: string) => text.padEnd(12);\n const managed = r.managed.length > 0 ? arrow(r.managed) : pc.dim('no managed account is live');\n const strategy = r.strategy ?? (r.routing === 'default' ? 'computesdk' : 'custom');\n const size = r.size !== undefined && strategy === 'cheapest' ? pc.dim(` (priced at ${r.size})`) : '';\n console.log(`${label('Routing')}${STRATEGY_LABEL[strategy]}`);\n console.log(`${label('Order')}${managed}${size}`);\n console.log(`${label('BYOK')}${r.byok.mode} ${pc.dim(`(${BYOK_MODE_HELP[r.byok.mode]})`)}`);\n if (r.byok.mode !== 'off') {\n const list = r.byok.order.length > 0 ? arrow(r.byok.order) : '—';\n const order =\n lane === 'sandboxes' && r.byok.inherits === true\n ? `${list} ${pc.dim('(inherited from the Actions router)')}`\n : r.byok.order.length > 0\n ? list\n : pc.dim('none set — add keys with `compute byok configure`');\n console.log(`${label('BYOK order')}${order}`);\n }\n}\n\n/** Sizes and pools (the BYOK side's per-provider knobs). */\nexport function printLaneSettings(s: LaneSettings): void {\n const resources = Object.entries(s.providerResources ?? {});\n console.log('resources:');\n if (resources.length === 0) console.log(' —');\n for (const [provider, r] of resources) {\n const preset = s.providerResourcePresets?.[provider];\n console.log(preset ? ` ${provider} ${preset} (${formatResources(r)})` : ` ${provider} ${formatResources(r)}`);\n }\n const pool = Object.entries(s.warmPool ?? {});\n console.log('warm pool:');\n if (pool.length === 0) console.log(' —');\n for (const [entry, floor] of pool) console.log(` ${entry} ${floor}`);\n if (s.snapshotPool !== undefined) {\n const snap = Object.entries(s.snapshotPool);\n console.log('snapshot pool:');\n if (snap.length === 0) console.log(' —');\n for (const [entry, cap] of snap) console.log(` ${safeTerm(entry)} ${cap}`);\n }\n if (s.snapshotSummary !== undefined) printSnapshotSummary(s.snapshotSummary);\n}\n\n/** Workflows carrying their own snapshot cap, then the workflows holding live snapshots. */\nfunction printSnapshotSummary(summary: NonNullable<LaneSettings['snapshotSummary']>): void {\n const capped = summary.workflows.filter((w) => w.snapshotCap !== null);\n console.log('workflow snapshot caps:');\n if (capped.length === 0) console.log(` ${pc.dim('— (every workflow uses the dynamic pool)')}`);\n for (const w of capped) {\n const cap = w.snapshotCap === 0 ? 'off' : String(w.snapshotCap);\n console.log(` ${safeTerm(w.repoFullName)} ${safeTerm(w.path)} ${cap}`);\n }\n console.log('live snapshots:');\n if (summary.live.length === 0) console.log(' —');\n for (const row of summary.live) {\n console.log(` ${safeTerm(row.repoFullName)} ${row.workflowPath === null ? pc.dim('(no workflow)') : safeTerm(row.workflowPath)} ${row.count}`);\n }\n}\n\nfunction settingsFail(\n e: unknown,\n opts: CommonOpts,\n lane: string,\n verb: 'view' | 'change',\n deps: SettingsDeps,\n): never {\n if (e instanceof ActionsApiError && e.status === 403) {\n return deps.fail(\n new ActionsApiError(\n 403,\n `Only org owners/admins can ${verb} ${lane} settings`,\n e.body,\n ),\n opts,\n );\n }\n return deps.fail(e, opts);\n}\n\n/** A comma-separated provider list flag; empty is a usage error. */\nfunction providerList(flag: string, value: string): string[] {\n const list = value.split(',').map((entry) => entry.trim()).filter(Boolean);\n if (list.length === 0) throw new Error(`${flag} \"${value}\" names no providers — pass a comma-separated list.`);\n return list;\n}\n\n/**\n * Register `settings` / `settings set` on a lane's command group\n * (`compute sandboxes` or `compute actions`).\n */\nexport function registerSettingsCommands(\n group: Command,\n lane: 'actions' | 'sandboxes',\n common: (cmd: Command) => Command,\n deps: SettingsDeps,\n): void {\n const routerName = lane === 'sandboxes' ? 'Sandboxes' : 'Actions';\n const show = async (c: ActionsClient) => {\n const [routing, settings] = await Promise.all([\n c.get<LaneRouting>(`/api/v1/${lane}/routing`),\n c.get<LaneSettings>(`/api/v1/${lane}/settings`),\n ]);\n return { routing, settings };\n };\n const print = ({ routing, settings }: { routing: LaneRouting; settings: LaneSettings }) => {\n printLaneRouting(routing, lane);\n printLaneSettings(settings);\n };\n\n const settings = common(\n group\n .command('settings')\n .description(`Show the ${routerName} router: managed routing, BYOK use, sizes and pools`)\n .configureOutput({\n outputError: (str, write) => deps.usageErrorOutput(str, write),\n }),\n ).action(async (opts: CommonOpts) => {\n try {\n deps.output(opts, await show(await deps.client(opts)), print);\n } catch (e) {\n settingsFail(e, opts, lane, 'view', deps);\n }\n });\n\n const set = common(\n settings\n .command('set')\n .description(`Change the ${routerName} router (owner/admin)`)\n .option(\n '--routing <strategy|providers>',\n 'managed routing: computesdk (default) | cheapest | your own managed-account order (e.g. daytona,e2b)',\n )\n .option('--byok <mode>', `use your own keys: ${BYOK_MODES.join(' | ')}`)\n .option(\n '--byok-order <providers>',\n lane === 'sandboxes'\n ? 'your own providers in order (e.g. tensorlake,blaxel); \"inherit\" uses the Actions BYOK order'\n : 'your own providers in order (e.g. tensorlake,blaxel)',\n )\n // Pre-router spelling of --byok-order, kept for existing scripts.\n .addOption(new Option('--order <providers>').hideHelp()),\n );\n set\n .option(\n '--resources <provider=preset>',\n 'per-provider size preset (e.g. blaxel=large); <provider>=none clears it (repeatable)',\n (v, a: string[]) => a.concat(v),\n [] as string[],\n )\n .option(\n '--warm-pool <provider[:region]=n>',\n `warm pool size per BYOK entry, 0..${MAX_WARM_POOL_SIZE}; 0 clears it (repeatable)`,\n (v, a: string[]) => a.concat(v),\n [] as string[],\n );\n if (lane === 'actions') {\n set.option(\n '--snapshot-pool <provider[:region]=n>',\n `snapshot cap per BYOK entry, 0..${MAX_SNAPSHOT_POOL_SIZE}; 0 clears it (repeatable)`,\n (v, a: string[]) => a.concat(v),\n [] as string[],\n );\n }\n // Caps and order types price the compute market, which is not generally\n // available; accepted, but kept out of help.\n set\n .addOption(new Option('--cap <size=rate>').hideHelp().argParser((v, a: string[] = []) => a.concat(v)).default([]))\n .addOption(new Option('--general-cap <rate|none>').hideHelp())\n .addOption(new Option('--order-type <type>').hideHelp());\n\n set.action(async (opts: CommonOpts & {\n routing?: string;\n byok?: string;\n byokOrder?: string;\n order?: string;\n cap: string[];\n generalCap?: string;\n orderType?: string;\n resources?: string[];\n warmPool?: string[];\n snapshotPool?: string[];\n }) => {\n try {\n const routing: Record<string, unknown> = {};\n if (opts.routing !== undefined) {\n // \"default\" is the old name of computesdk; older servers only know it.\n routing.routing =\n opts.routing === 'default' || (MANAGED_STRATEGIES as readonly string[]).includes(opts.routing)\n ? opts.routing\n : providerList('--routing', opts.routing);\n }\n if (opts.byok !== undefined) {\n if (!(BYOK_MODES as readonly string[]).includes(opts.byok)) {\n throw new Error(`--byok must be one of ${BYOK_MODES.join(', ')}.`);\n }\n routing.byok = opts.byok;\n }\n if (opts.byokOrder !== undefined && opts.order !== undefined) {\n throw new Error('--order is the old name of --byok-order; pass one.');\n }\n const byokOrder = opts.byokOrder ?? opts.order;\n if (byokOrder !== undefined) {\n const flag = opts.byokOrder !== undefined ? '--byok-order' : '--order';\n routing.byokOrder =\n (byokOrder === 'inherit' && lane === 'sandboxes') || (byokOrder === 'default' && lane === 'actions')\n ? []\n : providerList(flag, byokOrder);\n }\n\n const settingsBody: Record<string, unknown> = {};\n if (opts.cap.length > 0) {\n const caps: Record<string, Rate | null> = {};\n for (const entry of opts.cap) {\n const { size, cap } = parseSizeCap(entry);\n caps[size] = cap;\n }\n settingsBody.marketCaps = caps;\n }\n if (opts.generalCap !== undefined) {\n settingsBody.marketCap = opts.generalCap === 'none' ? null : parseMaxPrice(opts.generalCap, undefined);\n }\n if (opts.orderType !== undefined) {\n if (lane === 'sandboxes' && opts.orderType === 'inherit') {\n settingsBody.marketOrderType = null;\n } else if (opts.orderType === 'limit' || opts.orderType === 'market') {\n settingsBody.marketOrderType = opts.orderType;\n } else {\n throw new Error('--order-type must be limit or market.');\n }\n }\n if (opts.resources && opts.resources.length > 0) {\n const resources: Record<string, string | null> = {};\n for (const entry of opts.resources) {\n const { provider, preset } = parseResourcesFlag(entry);\n resources[provider] = preset;\n }\n settingsBody.providerResources = resources;\n }\n if (opts.warmPool && opts.warmPool.length > 0) {\n settingsBody.warmPool = poolPatch(opts.warmPool, parseWarmPoolFlag);\n }\n if (opts.snapshotPool && opts.snapshotPool.length > 0) {\n settingsBody.snapshotPool = poolPatch(opts.snapshotPool, parseSnapshotPoolFlag);\n }\n // The router and the sizes/pools are two endpoints; one command never\n // half-applies, so it changes one or the other.\n if (Object.keys(routing).length > 0 && Object.keys(settingsBody).length > 0) {\n throw new Error(\n 'Change routing (--routing, --byok, --byok-order) and sizes or pools in separate commands.',\n );\n }\n if (Object.keys(routing).length === 0 && Object.keys(settingsBody).length === 0) {\n throw new Error(\n lane === 'sandboxes'\n ? 'Nothing to change — pass --routing, --byok, --byok-order, --resources, or --warm-pool.'\n : 'Nothing to change — pass --routing, --byok, --byok-order, --resources, --warm-pool, or --snapshot-pool.',\n );\n }\n const c = await deps.client(opts);\n if (Object.keys(routing).length > 0) await c.patch<LaneRouting>(`/api/v1/${lane}/routing`, routing);\n if (Object.keys(settingsBody).length > 0) await c.patch<LaneSettings>(`/api/v1/${lane}/settings`, settingsBody);\n deps.output(opts, await show(c), print);\n } catch (e) {\n settingsFail(e, opts, lane, 'change', deps);\n }\n });\n}\n","/**\n * Confirmation for CLI writes that hide, remove or change shared state.\n * `-y/--yes` skips it; an interactive terminal is asked; anything else\n * (scripts, agents, CI) is refused with a hint, so a write never happens\n * because nobody was there to say no.\n */\n\nimport { createInterface } from 'node:readline/promises';\nimport { ActionsCliError } from './actions-client.js';\n\n/**\n * Resolve when the write may go ahead. Throws `confirmation_required` when\n * stdin is not a TTY and `--yes` was not passed, and `cancelled` when the\n * prompt is answered with anything but y/yes.\n */\nexport async function confirmWrite(question: string, opts: { yes?: boolean }): Promise<void> {\n if (opts.yes) return;\n if (!process.stdin.isTTY) {\n throw new ActionsCliError('confirmation_required', `${question} Pass -y to confirm.`);\n }\n const rl = createInterface({ input: process.stdin, output: process.stderr });\n let answer: string;\n try {\n answer = await rl.question(`${question} [y/N] `);\n } finally {\n rl.close();\n }\n if (!/^y(es)?$/i.test(answer.trim())) {\n throw new ActionsCliError('cancelled', 'Cancelled; nothing was changed.');\n }\n}\n","/**\n * `compute actions runs …` — the run list and its views over the v1 run\n * routes: the newest-100 window (`GET /api/v1/actions/runs`), one day's runs\n * page by page (`/runs/day/{day}`), the per-day index (`/run-days`), and\n * archive/unarchive (`POST /runs/archive`). Every view takes the same\n * filters, which map one-to-one onto the v1 query.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport {\n ActionsApiError,\n ActionsCliError,\n type ActionsClient,\n type CiRun,\n type CiRunArchiveResponse,\n type CiRunDay,\n type CiRunsCursor,\n type CiRunsPage,\n type CiWorkflow,\n} from './actions-client.js';\nimport type { CommonOpts } from './actions.js';\nimport { confirmWrite } from './confirm.js';\nimport { safeTerm } from './term.js';\n\n/** Injected by `actions.ts`, which imports this module (a runtime import back would be a cycle). */\nexport interface RunsDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n formatRunRow: (run: CiRun) => string;\n}\n\nexport interface RunFilterOpts {\n status?: string[];\n branch?: string[];\n event?: string[];\n workflow?: string[];\n search?: string;\n archived?: boolean;\n reliability?: boolean;\n}\n\ntype RunsOpts = CommonOpts & RunFilterOpts & { day?: string; timeZone?: string; cursor?: string; all?: boolean };\ntype Query = Record<string, string | string[] | undefined>;\n\n/** Selectors starting here are workflow file paths and go to the API as is. */\nconst WORKFLOW_PATH_PREFIX = '.github/';\n\nfunction plural(n: number, noun: string): string {\n return `${n} ${noun}${n === 1 ? '' : 's'}`;\n}\n\n/**\n * `--workflow` selectors → workflow file paths, matched against the catalog\n * by path, then name, then file name (`ci.yml`), then id. A name can match\n * workflows in several repos; each distinct path is kept once.\n */\nexport function resolveWorkflowPaths(workflows: CiWorkflow[], selectors: string[]): string[] {\n const paths: string[] = [];\n for (const selector of selectors) {\n const matchers: ((w: CiWorkflow) => boolean)[] = [\n (w) => w.path === selector,\n (w) => w.name === selector,\n (w) => w.path.split('/').pop() === selector,\n (w) => w.id === selector,\n ];\n let found: CiWorkflow[] = [];\n for (const matches of matchers) {\n found = workflows.filter(matches);\n if (found.length > 0) break;\n }\n if (found.length === 0) {\n const choices = [...new Set(workflows.map((w) => `${w.path} (${w.name})`))].join(', ') || 'none';\n throw new ActionsCliError('workflow_not_found', `No workflow \"${selector}\". Available: ${choices}`);\n }\n for (const w of found) if (!paths.includes(w.path)) paths.push(w.path);\n }\n return paths;\n}\n\n/** The v1 run-filter query for the flags; reads the workflow catalog only to resolve names. */\nasync function runFilterQuery(c: ActionsClient, repo: string | undefined, opts: RunFilterOpts): Promise<Query> {\n let workflow: string[] | undefined;\n if (opts.workflow && opts.workflow.length > 0) {\n const lookups = opts.workflow.filter((s) => !s.startsWith(WORKFLOW_PATH_PREFIX));\n const catalog =\n lookups.length === 0\n ? []\n : (await c.get<{ workflows: CiWorkflow[] }>('/api/v1/actions/workflows', { repo, include: 'all' })).workflows;\n workflow = [];\n for (const selector of opts.workflow) {\n const paths = selector.startsWith(WORKFLOW_PATH_PREFIX) ? [selector] : resolveWorkflowPaths(catalog, [selector]);\n for (const path of paths) if (!workflow.includes(path)) workflow.push(path);\n }\n }\n return {\n repo,\n status: opts.status,\n branch: opts.branch,\n event: opts.event,\n workflow,\n q: opts.search,\n archived: opts.archived ? 'only' : undefined,\n reliability: opts.reliability ? '1' : undefined,\n };\n}\n\n/** `--cursor <startedAt>,<id>`, the form printed after a day page. */\nexport function parseDayCursor(value: string): CiRunsCursor {\n const comma = value.lastIndexOf(',');\n if (comma <= 0 || comma === value.length - 1) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --cursor \"${value}\". Expected <startedAt>,<id>, as printed after a page.`,\n );\n }\n return { startedAt: value.slice(0, comma), id: value.slice(comma + 1) };\n}\n\n/** One page of a day's runs, or with `all` every page from `cursor` on, merged. */\nasync function listDayRuns(\n c: ActionsClient,\n day: string,\n query: Query,\n { all, cursor }: { all: boolean; cursor?: CiRunsCursor },\n): Promise<CiRunsPage & { nextCursor: CiRunsCursor | null }> {\n const runs: CiRun[] = [];\n const seen = new Set<string>();\n let next: CiRunsCursor | null = cursor ?? null;\n for (;;) {\n const page: CiRunsPage = await c.get<CiRunsPage>(`/api/v1/actions/runs/day/${encodeURIComponent(day)}`, {\n ...query,\n cursorStartedAt: next?.startedAt,\n cursorId: next?.id,\n });\n runs.push(...page.runs);\n next = page.nextCursor ?? null;\n if (!all || next === null) return { runs, nextCursor: next };\n const key = `${next.startedAt},${next.id}`;\n if (seen.has(key)) throw new ActionsCliError('invalid_argument', `The platform repeated cursor ${key}; stopping.`);\n seen.add(key);\n }\n}\n\nexport function formatRunDays(days: CiRunDay[]): string {\n if (days.length === 0) return 'No runs found.';\n return days.map((d) => `${safeTerm(d.day)} ${plural(d.count, 'run')}`).join('\\n');\n}\n\n/** The hint after a day page: the `--cursor` that continues it. */\nexport function formatDayCursor(cursor: { startedAt: string; id: string }): string {\n return `more: --cursor ${safeTerm(cursor.startedAt)},${safeTerm(cursor.id)}`;\n}\n\nfunction archiveQuestion(count: number, archived: boolean): string {\n return archived\n ? `Archive ${plural(count, 'run')}? Archived runs leave the run lists and counts; \\`compute actions runs unarchive\\` restores them.`\n : `Unarchive ${plural(count, 'run')}? They return to the run lists and counts.`;\n}\n\n/** The ids a 400 from `POST /runs/archive` reported as unknown or another org's. */\nfunction notFoundIds(error: unknown): string[] {\n if (!(error instanceof ActionsApiError)) return [];\n const ids = error.details?.notFound;\n return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === 'string') : [];\n}\n\nexport function registerRunsCommands(\n actions: Command,\n common: (cmd: Command) => Command,\n deps: RunsDeps,\n): void {\n const withFilters = (cmd: Command) =>\n cmd\n .option('--status <status...>', 'filter by conclusion: passed, failed, running, cancelled, none')\n .option('--branch <branch...>', 'filter by branch/ref')\n .option('--event <event...>', 'filter by trigger: push, pull_request, schedule, workflow_dispatch')\n .option('--workflow <path|name...>', 'filter by workflow path, name or file name (e.g. ci.yml)')\n .option('--search <text>', 'search title, ref, SHA prefix, workflow, #run or #PR number')\n .option('--archived', 'archived runs only (hidden by default)')\n .option('--reliability', 'reliability runs only (hidden by default)');\n\n const printRuns = (runs: CiRun[]) => {\n if (runs.length === 0) {\n console.log('No runs found.');\n return;\n }\n for (const run of runs) console.log(deps.formatRunRow(run));\n };\n\n const runs = actions\n .command('runs')\n .description('List recent runs (every repo, or one), or one day\\'s runs with --day');\n common(\n withFilters(runs.argument('[repo]', 'repository in owner/repo format (default: every repo)'))\n .option('--day <YYYY-MM-DD>', 'list one day\\'s runs, page by page, instead of the newest 100')\n .option('--time-zone <iana>', 'with --day: the time zone the day is read in (default: UTC)')\n .option('--cursor <startedAt,id>', 'with --day: continue after this cursor (printed after a page)')\n .option('--all', 'with --day: follow every page'),\n ).action(async (repo: string | undefined, opts: RunsOpts) => {\n try {\n if (opts.day === undefined && (opts.all || opts.timeZone !== undefined || opts.cursor !== undefined)) {\n throw new ActionsCliError('invalid_argument', '--all, --time-zone and --cursor page one day\\'s runs: pass --day <YYYY-MM-DD>.');\n }\n const cursor = opts.cursor === undefined ? undefined : parseDayCursor(opts.cursor);\n const c = await deps.client(opts);\n const query = await runFilterQuery(c, repo, opts);\n if (opts.day !== undefined) {\n const page = await listDayRuns(c, opts.day, { ...query, timeZone: opts.timeZone }, { all: opts.all === true, cursor });\n deps.output(opts, page, (p) => {\n printRuns(p.runs);\n if (p.nextCursor) console.log(pc.dim(formatDayCursor(p.nextCursor)));\n });\n return;\n }\n const { runs: list } = await c.get<{ runs: CiRun[] }>('/api/v1/actions/runs', query);\n deps.output(opts, list, printRuns);\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n\n common(\n withFilters(\n runs\n .command('days')\n .description('How many runs each day holds, newest first (same filters as runs)')\n .argument('[repo]', 'repository in owner/repo format (default: every repo)'),\n ).option('--time-zone <iana>', 'the time zone days are read in (default: UTC)'),\n ).action(async (repo: string | undefined, opts: CommonOpts & RunFilterOpts & { timeZone?: string }) => {\n try {\n const c = await deps.client(opts);\n const query = await runFilterQuery(c, repo, opts);\n const data = await c.get<{ days: CiRunDay[] }>('/api/v1/actions/run-days', { ...query, timeZone: opts.timeZone });\n deps.output(opts, data, (d) => console.log(formatRunDays(d.days)));\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n\n for (const archived of [true, false]) {\n const verb = archived ? 'archive' : 'unarchive';\n common(\n runs\n .command(verb)\n .description(\n archived\n ? 'Archive runs: hide them from run lists and counts, still reachable by id (owner/admin)'\n : 'Restore archived runs to the run lists (owner/admin)',\n )\n .argument('<run-id...>', 'run IDs')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (runIds: string[], opts: CommonOpts & { yes?: boolean }) => {\n try {\n await confirmWrite(archiveQuestion(runIds.length, archived), opts);\n const result = await (await deps.client(opts)).post<CiRunArchiveResponse>('/api/v1/actions/runs/archive', {\n runIds,\n archived,\n });\n deps.output(opts, result, (r) => console.log(`${verb}d ${plural(r.archived, 'run')}`));\n } catch (e) {\n const missing = notFoundIds(e);\n if (!opts.json && missing.length > 0 && e instanceof ActionsApiError) {\n deps.fail(new ActionsApiError(e.status, `${e.message} — not found: ${missing.join(', ')}`, e.body), opts);\n }\n deps.fail(e, opts);\n }\n });\n }\n}\n","/**\n * `compute actions workflows …` — the workflow catalog and its per-workflow\n * controls over `GET`/`PATCH /api/v1/actions/workflows`: the runnable list,\n * every workflow with `--all` (user-disabled ones and those on disabled\n * repos), the files only a branch or tag has with `--ref`, and\n * enable/disable/set for the on/off switch, placement order and snapshot cap.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport {\n ActionsCliError,\n type ActionsClient,\n type CiRefOnlyWorkflow,\n type CiWorkflowControls,\n type CiWorkflowInput,\n type CiWorkflowListItem,\n type CiWorkflowsResponse,\n} from './actions-client.js';\nimport type { CommonOpts } from './actions.js';\nimport { resolveWorkflowPaths } from './actions-runs.js';\nimport { confirmWrite } from './confirm.js';\nimport { conclusionLabel, safeTerm } from './term.js';\n\n/** Injected by `actions.ts`, which imports this module (a runtime import back would be a cycle). */\nexport interface WorkflowsDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n}\n\ntype ListOpts = CommonOpts & { all?: boolean; ref?: string };\ntype WriteOpts = CommonOpts & { yes?: boolean };\ntype SetOpts = WriteOpts & {\n order?: string;\n inheritOrder?: boolean;\n snapshotCap?: string;\n dynamicSnapshots?: boolean;\n};\ntype Controls = { enabled?: boolean; providerOrder?: string[] | null; snapshotCap?: number | null };\n\nexport function formatAgo(iso: string, now: number = Date.now()): string {\n const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000));\n if (s < 60) return `${s}s ago`;\n const m = Math.floor(s / 60);\n if (m < 60) return `${m}m ago`;\n const h = Math.floor(m / 60);\n if (h < 48) return `${h}h ago`;\n return `${Math.floor(h / 24)}d ago`;\n}\n\nfunction orderText(order: string[] | null | undefined): string {\n return order && order.length > 0 ? order.map(safeTerm).join(',') : 'inherits';\n}\n\nfunction snapshotText(cap: number | null | undefined): string {\n if (cap === null || cap === undefined) return 'dynamic';\n return cap === 0 ? 'off' : String(cap);\n}\n\n/** `target* (required), suite default=dax` — dispatch inputs as `--inputs` needs them. */\nexport function formatWorkflowInputs(inputs: CiWorkflowInput[]): string {\n return inputs\n .map((i) => {\n const name = safeTerm(i.name);\n if (i.required) return `${name}* (required)`;\n return i.default !== '' ? `${name} default=${safeTerm(i.default)}` : name;\n })\n .join(', ');\n}\n\nfunction stateLabel(w: CiWorkflowListItem): string {\n if (w.repoEnabled === false) return pc.gray('○ repo disabled');\n if (w.enabled === false || w.userDisabledAt) return pc.gray('○ disabled (user)');\n return pc.green('● enabled');\n}\n\nexport function formatWorkflowRow(w: CiWorkflowListItem, now: number = Date.now()): string {\n const last = w.lastRun ? `${conclusionLabel(w.lastRun.conclusion)} ${formatAgo(w.lastRun.queuedAt, now)}` : 'never';\n const inputs = formatWorkflowInputs(w.inputs ?? []);\n return [\n stateLabel(w),\n pc.dim(safeTerm(w.repoFullName)),\n `${safeTerm(w.path)} (${safeTerm(w.name)})`,\n `order: ${orderText(w.providerOrder)}`,\n `snapshots: ${snapshotText(w.snapshotCap)}`,\n `last: ${last}`,\n ...(inputs ? [pc.dim(`inputs: ${inputs}`)] : []),\n ].join(' ');\n}\n\nexport function formatRefOnlyRow(w: CiRefOnlyWorkflow): string {\n const inputs = formatWorkflowInputs(w.inputs);\n return [\n pc.cyan('◇ ref-only'),\n `${safeTerm(w.path)} (${safeTerm(w.name)})`,\n w.dispatchable\n ? inputs\n ? `inputs: ${inputs}`\n : pc.dim('no inputs')\n : pc.dim('push-only: dispatch with --manual'),\n ].join(' ');\n}\n\n/**\n * Match a dispatch `--workflow` against the files only the ref has: an exact\n * path first, then the name. A name two files share is refused with their\n * paths rather than guessed, as the control commands do.\n */\nexport function matchRefOnly(refOnly: CiRefOnlyWorkflow[], selector: string): CiRefOnlyWorkflow | undefined {\n const byPath = refOnly.find((w) => w.path === selector);\n if (byPath) return byPath;\n const byName = refOnly.filter((w) => w.name === selector);\n if (byName.length > 1) {\n throw new ActionsCliError(\n 'invalid_argument',\n `\"${selector}\" matches ${byName.length} workflows only on this ref: ${byName.map((w) => safeTerm(w.path)).join(', ')}. Pass the path.`,\n );\n }\n return byName[0];\n}\n\n/** `path (name)` choices for a not-found message. */\nexport function workflowChoices(workflows: { path: string; name: string }[]): string {\n return [...new Set(workflows.map((w) => `${w.path} (${w.name})`))].join(', ') || 'none';\n}\n\n/**\n * The path a control command's `<workflow>` names in `repo`, matched against\n * the full catalog (disabled workflows included) by path, name, file name or\n * id. A name shared by two files is refused rather than guessed.\n */\nexport function resolveControlTarget(catalog: CiWorkflowListItem[], repo: string, selector: string): string {\n const inRepo = catalog.filter((w) => w.repoFullName === repo);\n let paths: string[];\n try {\n paths = resolveWorkflowPaths(inRepo, [selector]);\n } catch (e) {\n if (e instanceof ActionsCliError && e.code === 'workflow_not_found') {\n throw new ActionsCliError('workflow_not_found', `No workflow \"${selector}\" in ${repo}. Available: ${workflowChoices(inRepo)}`);\n }\n throw e;\n }\n if (paths.length > 1) {\n throw new ActionsCliError(\n 'invalid_argument',\n `\"${selector}\" matches ${paths.length} workflows in ${repo}: ${paths.join(', ')}. Pass the path.`,\n );\n }\n return paths[0];\n}\n\n/** `set`'s flags → the PATCH controls; refuses conflicting, malformed or empty input. */\nexport function setControls(opts: SetOpts): Controls {\n const controls: Controls = {};\n if (opts.order !== undefined && opts.inheritOrder) {\n throw new ActionsCliError('invalid_argument', 'Pass --order or --inherit-order, not both.');\n }\n if (opts.snapshotCap !== undefined && opts.dynamicSnapshots) {\n throw new ActionsCliError('invalid_argument', 'Pass --snapshot-cap or --dynamic-snapshots, not both.');\n }\n if (opts.inheritOrder) controls.providerOrder = null;\n if (opts.order !== undefined) {\n const order = opts.order.split(',').map((s) => s.trim()).filter(Boolean);\n if (order.length === 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--order \"${opts.order}\" names no providers — pass a comma-separated list, or --inherit-order.`,\n );\n }\n controls.providerOrder = order;\n }\n if (opts.dynamicSnapshots) controls.snapshotCap = null;\n if (opts.snapshotCap !== undefined) {\n if (!/^\\d+$/.test(opts.snapshotCap.trim())) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid --snapshot-cap \"${opts.snapshotCap}\". Expected a whole number (0 turns snapshots off), or --dynamic-snapshots.`,\n );\n }\n controls.snapshotCap = Number(opts.snapshotCap.trim());\n }\n if (Object.keys(controls).length === 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Nothing to change — pass --order, --inherit-order, --snapshot-cap or --dynamic-snapshots.',\n );\n }\n return controls;\n}\n\nfunction describeControls(c: Controls): string {\n const parts: string[] = [];\n if (c.providerOrder !== undefined) parts.push(`order: ${orderText(c.providerOrder)}`);\n if (c.snapshotCap !== undefined) parts.push(`snapshots: ${snapshotText(c.snapshotCap)}`);\n return parts.join(', ');\n}\n\nfunction formatControlsResult(verb: string, r: CiWorkflowControls): string {\n const detail =\n verb === 'set'\n ? ` order: ${orderText(r.providerOrder)} snapshots: ${snapshotText(r.snapshotCap)}`\n : '';\n return `${verb} ${pc.cyan(safeTerm(r.repoFullName))} ${safeTerm(r.path)}${detail}`;\n}\n\nexport function registerWorkflowsCommands(\n actions: Command,\n common: (cmd: Command) => Command,\n deps: WorkflowsDeps,\n): void {\n const workflows = actions\n .command('workflows')\n .description('List workflows with their controls (every repo, or one); --all adds disabled ones, --ref the files only a branch has');\n common(\n workflows\n .argument('[repo]', 'repository in owner/repo format (default: every repo)')\n .option('--all', 'include user-disabled workflows and workflows on disabled repos')\n .option('--ref <ref>', 'with a repo: also list the workflow files only this branch or tag has (dispatchable by path)'),\n ).action(async (repo: string | undefined, opts: ListOpts) => {\n try {\n if (opts.ref !== undefined && repo === undefined) {\n throw new ActionsCliError('invalid_argument', '--ref needs a repo: compute actions workflows <owner/repo> --ref <ref>.');\n }\n const c = await deps.client(opts);\n const data = await c.get<CiWorkflowsResponse>('/api/v1/actions/workflows', {\n repo,\n include: opts.all ? 'all' : undefined,\n ref: opts.ref,\n });\n deps.output(opts, data, (d) => {\n if (d.workflows.length === 0 && (d.refOnly ?? []).length === 0) {\n console.log('No workflows found.');\n return;\n }\n for (const w of d.workflows) console.log(formatWorkflowRow(w));\n if (opts.ref !== undefined) {\n const refOnly = d.refOnly ?? [];\n console.log(pc.dim(refOnly.length === 0 ? `only on ${safeTerm(opts.ref)}: none` : `only on ${safeTerm(opts.ref)}:`));\n for (const w of refOnly) console.log(formatRefOnlyRow(w));\n }\n });\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n\n /** Confirm, resolve `<workflow>` against `?include=all`, then PATCH repo + path with `controls`. */\n async function writeControls(\n repo: string,\n selector: string,\n controls: Controls,\n question: string,\n verb: string,\n opts: WriteOpts,\n ): Promise<void> {\n await confirmWrite(question, opts);\n const c = await deps.client(opts);\n const { workflows: catalog } = await c.get<CiWorkflowsResponse>('/api/v1/actions/workflows', {\n repo,\n include: 'all',\n });\n const path = resolveControlTarget(catalog, repo, selector);\n const result = await c.patch<CiWorkflowControls>('/api/v1/actions/workflows', {\n repoFullName: repo,\n path,\n ...controls,\n });\n deps.output(opts, result, (r) => console.log(formatControlsResult(verb, r)));\n }\n\n for (const enabled of [true, false]) {\n const verb = enabled ? 'enable' : 'disable';\n common(\n workflows\n .command(verb)\n .description(\n enabled\n ? 'Turn a workflow back on (owner/admin)'\n : 'Turn a workflow off: no pushes, schedules or dispatches run it until enabled (owner/admin)',\n )\n .argument('<repo>', 'repository in owner/repo format')\n .argument('<workflow>', 'workflow path, name, file name (ci.yml) or id')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (repo: string, selector: string, opts: WriteOpts) => {\n try {\n const question = enabled\n ? `Enable workflow \"${selector}\" in ${repo}? It runs again on its triggers.`\n : `Disable workflow \"${selector}\" in ${repo}? Pushes, schedules and dispatches stop running it until it is enabled.`;\n await writeControls(repo, selector, { enabled }, question, `${verb}d`, opts);\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n }\n\n common(\n workflows\n .command('set')\n .description('Set a workflow\\'s provider order and snapshot cap (owner/admin)')\n .argument('<repo>', 'repository in owner/repo format')\n .argument('<workflow>', 'workflow path, name, file name (ci.yml) or id')\n .option('--order <providers>', 'this workflow walks exactly these BYOK providers instead of the Actions router (e.g. e2b,blaxel)')\n .option('--inherit-order', 'drop the workflow\\'s order: it follows the Actions router')\n .option('--snapshot-cap <n>', 'most snapshots this workflow keeps (0 turns them off)')\n .option('--dynamic-snapshots', 'drop the cap: the workflow uses the dynamic snapshot pool')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (repo: string, selector: string, opts: SetOpts) => {\n try {\n const controls = setControls(opts);\n await writeControls(\n repo,\n selector,\n controls,\n `Change workflow \"${selector}\" in ${repo} (${describeControls(controls)})?`,\n 'set',\n opts,\n );\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n}\n","/**\n * `compute actions repos …` and `compute actions branches` — the org's\n * repositories over `/api/v1/actions/repos*`: the list with run counts and\n * poll state, connect/sync/enable/disable, poll-now (`/repos/poll`, at most\n * every 30 s, shared with the dashboard), the fork pull request setting, and\n * a repo's refs (`/repos/branches`).\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { readFileSync } from 'fs';\nimport {\n ActionsApiError,\n ActionsCliError,\n type ActionsClient,\n type CiApiRepo,\n type CiBranch,\n type CiBranchesResponse,\n type CiRepoConnectResponse,\n type CiRepoPatchResponse,\n type CiRepoPollResponse,\n type CiRepoSyncResponse,\n type CiReposResponse,\n} from './actions-client.js';\nimport type { CommonOpts } from './actions.js';\nimport { formatAgo } from './actions-workflows.js';\nimport { confirmWrite } from './confirm.js';\nimport { conclusionLabel, safeTerm } from './term.js';\n\n/** Injected by `actions.ts`, which imports this module (a runtime import back would be a cycle). */\nexport interface ReposDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n}\n\ntype RepoIdOpts = CommonOpts & { repoId?: string };\ntype WriteOpts = RepoIdOpts & { yes?: boolean };\n\nconst FORK_PRS: Record<string, boolean> = { allow: true, refuse: false };\n\nfunction plural(n: number, noun: string): string {\n return `${n} ${noun}${n === 1 ? '' : 's'}`;\n}\n\n/** `in 25s` / `in 2m` / `in 3h` / `in 2d` — the countdown twin of `formatAgo`. */\nexport function formatIn(iso: string, now: number = Date.now()): string {\n const s = Math.max(0, Math.round((Date.parse(iso) - now) / 1000));\n if (s < 60) return `in ${s}s`;\n const m = Math.round(s / 60);\n if (m < 60) return `in ${m}m`;\n const h = Math.round(m / 60);\n if (h < 48) return `in ${h}h`;\n return `in ${Math.round(h / 24)}d`;\n}\n\n/** `not polled yet` / `next poll in 2m` / `poll due`; nothing for a disabled repo. */\nfunction pollText(r: Partial<CiApiRepo>, now: number): string | null {\n if (!r.enabled) return null;\n if (r.pollSchedule === 'never') return 'not polled yet';\n if (!r.nextPollDueAt) return null;\n return Date.parse(r.nextPollDueAt) <= now ? 'poll due' : `next poll ${formatIn(r.nextPollDueAt, now)}`;\n}\n\n/**\n * `enabled acme/widgets github-app · main · 2 workflows · 5 runs · last passed 3h ago · next poll in 2m`.\n * The run and poll parts are left out when the platform predates them.\n */\nexport function formatRepoRow(r: CiApiRepo, now: number = Date.now()): 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 parts = [\n safeTerm(via),\n safeTerm(r.defaultBranch),\n r.workflowPaths.length > 0 ? plural(r.workflowPaths.length, 'workflow') : 'no workflows yet',\n ];\n if (r.runs) {\n parts.push(plural(r.runs.total, 'run'));\n if (r.runs.lastRunState && r.runs.lastRunQueuedAt) {\n parts.push(`last ${conclusionLabel(r.runs.lastRunState)} ${formatAgo(r.runs.lastRunQueuedAt, now)}`);\n }\n }\n const poll = pollText(r, now);\n if (poll) parts.push(poll);\n if (r.forkPullRequests) parts.push('fork PRs on');\n const error = r.lastPollError ? pc.red(` poll error: ${safeTerm(r.lastPollError)}`) : '';\n return `${head} ${safeTerm(r.fullName)} ${pc.dim(parts.join(' · '))}${error}`;\n}\n\n/** `refs/pull/482/head PR #482 watched 3 runs last 2h ago <run-id>`. */\nexport function formatBranchRow(b: CiBranch, now: number = Date.now(), defaultBranch?: string): string {\n const isDefault = defaultBranch !== undefined && b.ref === `refs/heads/${defaultBranch}`;\n const at = Number.isNaN(Date.parse(b.lastRunAt)) ? null : formatAgo(b.lastRunAt, now);\n return [\n safeTerm(b.ref) + (isDefault ? pc.dim(' (default)') : ''),\n ...(b.prNumber !== null ? [`PR #${b.prNumber}`] : []),\n b.watched ? pc.green('watched') : pc.dim('history only'),\n plural(b.runCount, 'run'),\n ...(at ? [b.runCount > 0 ? `last ${at}` : pc.dim(`moved ${at}`)] : []),\n ...(b.latestRunId ? [pc.dim(safeTerm(b.latestRunId))] : []),\n ].join(' ');\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/** A 429 from `/repos/poll` with its `nextAllowedAt` folded into the message. */\nfunction withRetryAfter(error: unknown): unknown {\n if (!(error instanceof ActionsApiError) || error.status !== 429) return error;\n const next = error.details?.nextAllowedAt;\n if (typeof next !== 'string') return error;\n const rewritten = new ActionsApiError(error.status, `${error.message}; retry after ${next} (${formatIn(next)})`, error.body);\n rewritten.retryAfterMs = error.retryAfterMs;\n return rewritten;\n}\n\n/** `--fork-prs` → `forkPullRequests`; anything but allow/refuse is refused before any request. */\nexport function parseForkPrs(value: string): boolean {\n if (!Object.prototype.hasOwnProperty.call(FORK_PRS, value)) {\n throw new ActionsCliError('invalid_argument', `Invalid --fork-prs \"${value}\". Expected allow or refuse.`);\n }\n return FORK_PRS[value];\n}\n\nconst repoIdBody = (opts: RepoIdOpts) => (opts.repoId !== undefined ? { repoId: opts.repoId } : {});\nconst REPO_ID_HELP = 'scope to one row when two installations grant the same name';\n\nexport function registerReposCommands(\n actions: Command,\n common: (cmd: Command) => Command,\n deps: ReposDeps,\n): void {\n const { client, output, fail } = deps;\n\n const repos = actions\n .command('repos')\n .description('List the org\\'s connected repositories: run counts, last run and next poll');\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 if (d.repos.length === 0) {\n console.log('No repositories connected.');\n return;\n }\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('sync')\n .description('Re-read the GitHub App installation so repos granted after install show up (owner/admin key)'),\n ).action(async (opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<CiRepoSyncResponse>('/api/v1/actions/repos/sync', {});\n output(opts, result, (r) => {\n for (const a of r.accounts) {\n console.log(a.error === null ? `synced ${pc.cyan(safeTerm(a.account))}` : `failed ${pc.cyan(safeTerm(a.account))} ${pc.red(safeTerm(a.error))}`);\n }\n console.log(pc.dim(`${r.repos.length} repos visible`));\n });\n if (result.accounts.some((a) => a.error !== null)) process.exitCode = 1;\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>', REPO_ID_HELP),\n ).action(async (repo: string, opts: RepoIdOpts) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: true,\n ...repoIdBody(opts),\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>', REPO_ID_HELP),\n ).action(async (repo: string, opts: RepoIdOpts) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: false,\n ...repoIdBody(opts),\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 common(\n repos\n .command('poll')\n .description('Poll a repo now: fetch its refs and start the runs new commits call for (owner/admin; at most every 30 s)')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--repo-id <id>', REPO_ID_HELP)\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (repo: string, opts: WriteOpts) => {\n try {\n await confirmWrite(`Poll ${repo} now? New commits on its watched refs start the runs their workflows call for.`, opts);\n const c = await client(opts);\n let result: CiRepoPollResponse;\n try {\n result = await c.post<CiRepoPollResponse>('/api/v1/actions/repos/poll', { fullName: repo, ...repoIdBody(opts) });\n } catch (e) {\n throw withRetryAfter(e);\n }\n output(opts, result, (r) => {\n console.log(`polled ${pc.cyan(safeTerm(r.fullName))} ${plural(r.createdRunIds.length, 'run')} started`);\n if (r.error) console.log(pc.red(`poll error: ${safeTerm(r.error)}`));\n });\n // The platform answers 200 for a poll the remote refused; the error is the outcome.\n if (result.error) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('set')\n .description('Change a repo\\'s settings: whether pull requests from forks run CI (owner/admin)')\n .argument('<repo>', 'repository in owner/repo format')\n .requiredOption('--fork-prs <allow|refuse>', 'run pull requests from forks (isolated: no org secrets, no GitHub token), or refuse them')\n .option('--repo-id <id>', REPO_ID_HELP)\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (repo: string, opts: WriteOpts & { forkPrs: string }) => {\n try {\n const forkPullRequests = parseForkPrs(opts.forkPrs);\n await confirmWrite(\n forkPullRequests\n ? `Run pull requests from forks on ${repo}? They run isolated: no org secrets, no GitHub token, and the base branch's workflow definition.`\n : `Refuse pull requests from forks on ${repo}? Fork pull requests stop running CI.`,\n opts,\n );\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n forkPullRequests,\n ...repoIdBody(opts),\n });\n output(opts, result, (r) =>\n console.log(`fork PRs ${r.forkPullRequests === false ? 'refused' : 'allowed'} ${pc.cyan(safeTerm(r.fullName))}`),\n );\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('branches')\n .description('List a repo\\'s refs: watched branches and pull requests, then refs with run history only')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--search <text>', 'only refs containing this text (case-insensitive)')\n .option('--archived', 'count archived runs instead of active ones')\n .option('--repo-id <id>', REPO_ID_HELP),\n ).action(async (repo: string, opts: RepoIdOpts & { search?: string; archived?: boolean }) => {\n try {\n const data = await (await client(opts)).get<CiBranchesResponse>('/api/v1/actions/repos/branches', {\n repo,\n repoId: opts.repoId,\n q: opts.search,\n archived: opts.archived ? '1' : undefined,\n });\n output(opts, data, (d) => {\n console.log(`${pc.bold(safeTerm(d.repo))} ${pc.dim(`default: ${safeTerm(d.defaultBranch)}`)}`);\n if (d.branches.length === 0) {\n console.log('No branches found.');\n return;\n }\n const now = Date.now();\n for (const b of d.branches) console.log(formatBranchRow(b, now, d.defaultBranch));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * `compute actions installations …` and `compute actions slack …` — the org's\n * connected integrations over `/api/v1/actions/installations*` and\n * `/api/v1/actions/slack*`: the GitHub App installations (account, repo\n * selection and counts, suspension) and the Slack connection (workspace,\n * channel, notify rule, daily brief), plus where an owner/admin starts a new\n * install. Reads only: installing is a browser step the platform signs for\n * the signed-in user, so `install-url` prints the page to open, never a\n * signed install link.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport type {\n ActionsClient,\n CiInstallation,\n CiInstallationsResponse,\n CiInstallLink,\n CiSlackConnection,\n} from './actions-client.js';\nimport type { CommonOpts } from './actions.js';\nimport { safeTerm } from './term.js';\n\n/** Injected by `actions.ts`, which imports this module (a runtime import back would be a cycle). */\nexport interface IntegrationsDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n}\n\nexport function formatInstallationRow(i: CiInstallation): string {\n const head = i.suspended ? pc.yellow(safeTerm(i.account)) : pc.cyan(safeTerm(i.account));\n const parts = [\n i.accountType ? safeTerm(i.accountType) : 'account',\n i.repoSelection === 'all' ? 'all repos' : 'selected repos',\n `${i.repos.granted} granted, ${i.repos.enabled} enabled`,\n ...(i.suspended ? [pc.yellow(`suspended ${safeTerm(i.suspendedAt ?? '')}`.trim())] : []),\n pc.dim(`installed ${safeTerm(i.installedAt)}`),\n ];\n return `${head} ${parts.join(' ')}`;\n}\n\nexport function formatInstallations(data: CiInstallationsResponse): string[] {\n if (data.installations.length === 0) {\n return ['No GitHub App installations. Run `compute actions installations install-url` for where to install it.'];\n }\n const lines: string[] = [];\n for (const i of data.installations) {\n lines.push(formatInstallationRow(i));\n if (i.configureUrl) lines.push(` ${pc.dim(`configure: ${safeTerm(i.configureUrl)}`)}`);\n }\n return lines;\n}\n\nexport function formatSlack(s: CiSlackConnection): string[] {\n if (!s.installed) {\n return ['Slack is not connected. Run `compute actions slack install-url` for where to connect it.'];\n }\n const channel = s.channelId\n ? `${s.channelName ? `#${safeTerm(s.channelName)} ` : ''}${pc.dim(safeTerm(s.channelId))}`\n : pc.gray('no channel picked');\n const brief = s.brief.enabled\n ? `${s.brief.times.map(safeTerm).join(', ')} ${safeTerm(s.brief.timeZone)}${s.brief.categories.length > 0 ? ` categories: ${s.brief.categories.map(safeTerm).join(', ')}` : ''}`\n : pc.gray('off');\n return [\n `workspace: ${s.teamName ? safeTerm(s.teamName) : pc.gray('(unnamed)')}`,\n `channel: ${channel}`,\n `notify on: ${s.notifyOn === 'failure' ? 'failures and cancels' : 'every conclusion'}`,\n `daily brief: ${brief}`,\n ];\n}\n\nexport function formatInstallLink(link: CiInstallLink, what: 'github' | 'slack'): string[] {\n if (!link.configured || link.url === null) {\n return [what === 'github' ? 'This deployment has no GitHub App configured.' : 'This deployment has no Slack app configured.'];\n }\n return [\n safeTerm(link.url),\n pc.dim(\n what === 'github'\n ? 'Open it signed in as an org owner/admin and press Install GitHub App.'\n : 'Open it in a browser signed in as an org owner/admin; it continues to Slack.',\n ),\n ];\n}\n\nexport function registerIntegrationsCommands(\n actions: Command,\n common: (cmd: Command) => Command,\n deps: IntegrationsDeps,\n): void {\n const { client, output, fail } = deps;\n const print = (lines: string[]) => {\n for (const line of lines) console.log(line);\n };\n\n const installations = common(\n actions\n .command('installations')\n .description('List the org\\'s GitHub App installations (account, repo selection and counts, suspension)'),\n ).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiInstallationsResponse>('/api/v1/actions/installations');\n output(opts, data, (d) => print(formatInstallations(d)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n installations\n .command('install-url')\n .description('Print where an owner/admin installs the GitHub App into another account'),\n ).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiInstallLink>('/api/v1/actions/installations/install-url');\n output(opts, data, (d) => print(formatInstallLink(d, 'github')));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const slack = common(\n actions\n .command('slack')\n .description('Show the org\\'s Slack connection (workspace, channel, notify rule, daily brief; owner/admin)'),\n ).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiSlackConnection>('/api/v1/actions/slack');\n output(opts, data, (d) => print(formatSlack(d)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n slack\n .command('install-url')\n .description('Print where an owner/admin connects a Slack workspace'),\n ).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiInstallLink>('/api/v1/actions/slack/install-url');\n output(opts, data, (d) => print(formatInstallLink(d, 'slack')));\n } catch (e) {\n fail(e, opts);\n }\n });\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, Option } from 'commander';\nimport pc from 'picocolors';\nimport { mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { spawnSync } from 'child_process';\nimport { registerSettingsCommands } from './settings.js';\nimport { registerReposCommands } from './actions-repos.js';\nimport { registerIntegrationsCommands } from './actions-integrations.js';\nimport { registerRunsCommands } from './actions-runs.js';\nimport { matchRefOnly, registerWorkflowsCommands, workflowChoices } from './actions-workflows.js';\nimport { conclusionLabel, safeTerm, safeTermText } from './term.js';\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 CiRun,\n type CiRunBenchmarkProvider,\n type CiRunBenchmarkResult,\n type CiRunHistory,\n type CiRunInspection,\n type CiRunSummary,\n type CiSchedule,\n type CiVaultDeleteResponse,\n type CiVaultItem,\n type CiVaultKind,\n type CiVaultListResponse,\n type CiVaultRevealResponse,\n type CiVaultSaveResponse,\n type CiRefOnlyWorkflow,\n type CiWorkflow,\n type CiWorkflowsResponse,\n} from './actions-client.js';\n\nexport { conclusionLabel, safeTerm };\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\ninterface ScheduleOpts extends CommonOpts {\n reliability?: boolean;\n from?: string;\n to?: string;\n repo?: string;\n workflow?: string[];\n event?: string[];\n status?: string[];\n tz?: string;\n limit?: string;\n cursor?: string;\n}\n\nfunction scheduleQuery(opts: ScheduleOpts): Record<string, string | string[] | undefined> {\n const from = opts.from === undefined ? new Date() : new Date(opts.from);\n const to = opts.to === undefined ? new Date(from.getTime() + 7 * 86_400_000) : new Date(opts.to);\n if (!Number.isFinite(from.getTime()) || !Number.isFinite(to.getTime())) {\n throw new ActionsCliError('invalid_argument', '--from and --to must be valid timestamps.');\n }\n return {\n from: from.toISOString(), to: to.toISOString(),\n repo: opts.repo, workflow: opts.workflow, event: opts.event, status: opts.status,\n reliability: opts.reliability ? '1' : undefined,\n timeZone: opts.tz ?? Intl.DateTimeFormat().resolvedOptions().timeZone,\n limit: opts.limit, cursor: opts.cursor,\n };\n}\n\nfunction nextScheduleCommand(data: CiSchedule, opts: ScheduleOpts): string {\n const args = ['compute', 'actions', 'schedule', '--from', data.from, '--to', data.to, '--tz', data.timeZone];\n for (const key of ['repo', 'workflow', 'event', 'status', 'limit', 'org', 'baseUrl'] as const) {\n const value = opts[key];\n if (value === undefined) continue;\n for (const item of Array.isArray(value) ? value : [value]) args.push(`--${key === 'baseUrl' ? 'base-url' : key}`, item);\n }\n if (opts.reliability) args.push('--reliability');\n if (opts.allowUntrustedHost) args.push('--allow-untrusted-host');\n args.push('--cursor', data.nextCursor!);\n return args.map((value) => /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replace(/'/g, \"'\\\\''\")}'`).join(' ');\n}\n\nexport function formatSchedule(data: CiSchedule, nextCommand?: string): string {\n const time = new Intl.DateTimeFormat('en-CA', {\n timeZone: data.timeZone, year: 'numeric', month: '2-digit', day: '2-digit',\n hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23', timeZoneName: 'short',\n });\n const lines = [pc.bold(`Upcoming fires (${safeTerm(data.timeZone)})`)];\n const fires = data.upcoming.flatMap((schedule) => schedule.occurrences.map((at) => ({ at, schedule })))\n .sort((a, b) => a.at.localeCompare(b.at));\n if (fires.length === 0) lines.push('No upcoming fires.');\n for (const { at, schedule } of fires) {\n lines.push([time.format(new Date(at)), safeTerm(schedule.workflowName || schedule.workflowPath), safeTerm(schedule.repoFullName), safeTerm(schedule.description)].join(' '));\n }\n for (const schedule of data.upcoming) {\n const remaining = schedule.occurrenceCount - schedule.occurrences.length;\n if (remaining > 0) lines.push(`+${remaining.toLocaleString('en-US')} more scheduled for ${safeTerm(schedule.workflowName || schedule.workflowPath)} ${safeTerm(schedule.repoFullName)} ${safeTerm(schedule.description)}`);\n }\n lines.push('', pc.bold(`Past runs (${safeTerm(data.timeZone)})`));\n if (data.runs.length === 0) lines.push('No past runs found.');\n for (const run of data.runs) {\n lines.push([\n time.format(new Date(run.startedAt ?? run.createdAt)), safeTerm(run.workflowName || run.workflowPath),\n safeTerm(run.repoFullName), safeTerm(run.event), conclusionLabel(safeTerm(run.status === 'completed' ? run.conclusion : run.status)),\n ].join(' '));\n }\n if (data.countsTruncated) lines.push('Warning: some schedule totals reached the safety limit; use a smaller window for exact counts.');\n if (nextCommand) lines.push('', `Next page (reuse the same credentials):\\n${safeTerm(nextCommand)}`);\n return lines.join('\\n');\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 // The message is the server's, or quotes server values: no control sequences.\n console.error(pc.red(`Error (${error.status}): ${safeTermText(error.message)}`));\n } else {\n console.error(pc.red(`Error: ${safeTermText(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 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 ...(run.archivedAt ? [pc.dim('archived')] : []),\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.benchmarks && run.benchmarks.length > 0) lines.push(`benchmarks: ${resultsSummary(run.benchmarks)}`);\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/** One-line digest: `sandbox-cpu · 26 providers · 13 failed`. */\nexport function resultsSummary(results: CiRunBenchmarkResult[]): string {\n return results\n .map((r) => {\n const rows = overallRows(r);\n if (rows.length === 0) return `${safeTerm(r.benchmarkSlug)} (${safeTerm(r.status)}, no results yet)`;\n const failed = rows.filter((p) => !p.skipped && p.successRate !== null && p.successRate < 1).length;\n return `${safeTerm(r.benchmarkSlug)} · ${rows.length} providers${failed > 0 ? ` · ${failed} failed` : ''}`;\n })\n .join('; ');\n}\n\n/**\n * The runner reports one overall row per provider (`dimensions: {}`) plus one\n * per dimension (e.g. phase). The table shows one row per provider — its\n * overall row, or its best dimension row when it has no overall; `--json` has all.\n */\nfunction overallRows(result: CiRunBenchmarkResult): CiRunBenchmarkProvider[] {\n const byProvider = new Map<string, CiRunBenchmarkProvider>();\n for (const p of result.providers) {\n const cur = byProvider.get(p.provider);\n const isOverall = Object.keys(p.dimensions).length === 0;\n const curIsOverall = cur ? Object.keys(cur.dimensions).length === 0 : false;\n if (!cur || (isOverall && !curIsOverall) || (!curIsOverall && (p.compositeScore ?? -1) > (cur.compositeScore ?? -1))) {\n byProvider.set(p.provider, p);\n }\n }\n return Array.from(byProvider.values());\n}\n\nfunction formatScore(n: number | null): string {\n return n === null ? '-' : n.toFixed(2);\n}\n\nfunction formatMetric(n: number): string {\n return Number.isInteger(n) ? String(n) : n.toFixed(Math.abs(n) >= 100 ? 1 : 2);\n}\n\nfunction formatRate(n: number | null): string {\n return n === null ? '-' : `${Math.round(n * 100)}%`;\n}\n\n/** `compute actions benchmarks` — per-provider score table for each linked benchmark run. */\nexport function formatRunResults(results: CiRunBenchmarkResult[]): string {\n if (results.length === 0) return pc.dim('no benchmark results on this run');\n const lines: string[] = [];\n for (const [i, result] of results.entries()) {\n if (i > 0) lines.push('');\n lines.push(`${pc.bold(safeTerm(result.benchmarkName))} ${safeTerm(result.status)}`);\n lines.push(pc.dim(`${safeTerm(result.benchmarkRunId)} ${safeTerm(result.dashboardUrl)}`));\n const rows = [...overallRows(result)].sort((a, b) => (b.compositeScore ?? -1) - (a.compositeScore ?? -1));\n if (rows.length === 0) {\n lines.push(pc.dim(result.status === 'failed' ? ' failed before reporting results' : ' no results yet'));\n continue;\n }\n const width = Math.max(8, ...rows.map((p) => p.provider.length));\n lines.push(pc.dim(` ${'provider'.padEnd(width)} ${'score'.padStart(7)} ${'success'.padStart(7)} metrics`));\n for (const p of rows) {\n const metrics = Object.entries(p.metrics)\n .map(([name, m]) => `${safeTerm(name)} ${formatMetric(m.median)}${m.unit ? safeTerm(m.unit) : ''}`)\n .join(' ');\n const status = p.skipped ? pc.dim(`skipped${p.skipReason ? `: ${safeTerm(p.skipReason)}` : ''}`) : metrics;\n lines.push(` ${safeTerm(p.provider).padEnd(width)} ${formatScore(p.compositeScore).padStart(7)} ${formatRate(p.successRate).padStart(7)} ${status}`);\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\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\n/** A stored key's verification state: `connected …abcd`, `error (detail)`, `unconfigured`. */\nfunction keyStatusText(p: CiProviderInfo): string {\n const status = p.status === 'connected' ? pc.green('connected') : p.status === 'error' ? pc.red('error') : pc.gray('unconfigured');\n const hint = p.keyHint ? ` ${pc.dim(safeTerm(p.keyHint))}` : '';\n const detail = p.status === 'error' && p.statusDetail ? ` ${pc.dim(`(${safeTerm(p.statusDetail)})`)}` : '';\n return `${status}${hint}${detail}`;\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 ...(p.credential !== 'ambient' && p.status !== undefined ? [keyStatusText(p)] : []),\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\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 */\n/**\n * A workflow with no catalog row yet — a file the dispatched diff creates, or\n * one only the dispatched ref has — so it is addressed by path. `dispatchable`\n * is known only for a ref-only file; a diff's file is left to the platform.\n */\nexport type PatchedWorkflowTarget = { repoFullName: string; workflowPath: string; dispatchable?: boolean };\n\nexport function isPatchedWorkflowTarget(target: CiWorkflow | PatchedWorkflowTarget): target is PatchedWorkflowTarget {\n return 'workflowPath' in target;\n}\n\n/**\n * True when a unified diff creates or edits `path`: a `+++ b/<path>` header.\n * Git tab-terminates the header when the path contains whitespace and quotes\n * it (`+++ \"b/<path>\"`) for non-ASCII bytes under core.quotePath.\n */\nexport function patchTouches(patch: string, path: string): boolean {\n const plain = `+++ b/${path}`;\n const quoted = `+++ \"b/${path}\"`;\n return patch.split('\\n').some((line) => {\n const header = line.replace(/\\t.*$/, '');\n return header === plain || header === quoted;\n });\n}\n\nexport function dispatchBody(\n workflow: CiWorkflow | PatchedWorkflowTarget,\n opts: {\n ref?: string;\n inputs?: string[];\n manual?: boolean;\n provider?: string;\n providerRegion?: string;\n maxBid?: string;\n maxBidPer?: string;\n /** An uploaded diff (`POST /api/v1/actions/patches`) to run on top of the ref's head. */\n patchId?: string;\n },\n): Record<string, unknown> {\n const patched = isPatchedWorkflowTarget(workflow);\n const path = patched ? workflow.workflowPath : workflow.path;\n const pushOnly = workflow.dispatchable === false;\n if (pushOnly && !opts.manual) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${path}\" does not declare workflow_dispatch. Pass --manual to run it anyway (no inputs).`,\n );\n }\n if (pushOnly && opts.inputs !== undefined && opts.inputs.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${path}\" has no workflow_dispatch inputs; --manual runs of it take no --inputs.`,\n );\n }\n const ref = opts.ref ?? (patched ? undefined : 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 ...(patched ? { repoFullName: workflow.repoFullName, workflowPath: workflow.workflowPath } : { 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 ...(opts.patchId !== undefined && { patchId: opts.patchId }),\n };\n}\n\nexport type GitRunner = (args: string[]) => { status: number | null; stdout: string; stderr: string };\n\nconst runGit: GitRunner = (args) => {\n const r = spawnSync('git', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });\n return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };\n};\n\n/** True when a git remote URL (https or ssh, with or without `.git`) names `owner/repo`. */\nexport function remoteNamesRepo(remote: string, repo: string): boolean {\n const normalized = remote.trim().replace(/\\.git$/, '').replace(/\\/+$/, '');\n return normalized.toLowerCase().endsWith(`/${repo.toLowerCase()}`) || normalized.toLowerCase().endsWith(`:${repo.toLowerCase()}`);\n}\n\n/** The checked-out branch, or null outside a git repo / on a detached HEAD. */\nexport function currentBranch(git: GitRunner = runGit): string | null {\n const r = git(['rev-parse', '--abbrev-ref', 'HEAD']);\n if (r.status !== 0) return null;\n const name = r.stdout.trim();\n return name === '' || name === 'HEAD' ? null : name;\n}\n\n/** True when the working tree has uncommitted or untracked changes; false outside a repo. */\nexport function hasLocalChanges(git: GitRunner = runGit): boolean {\n const r = git(['status', '--porcelain', '--untracked-files=all']);\n return r.status === 0 && r.stdout.trim() !== '';\n}\n\n/**\n * `--with-changes`: everything the working tree has that the remote ref does\n * not — local commits past `origin/<ref>`, uncommitted edits, and untracked\n * files — as one unified diff against `origin/<ref>`. That is the commit the\n * platform resolves the ref to, so the diff applies exactly. Null when there\n * is nothing to send.\n */\nexport function localChangesPatch(\n ref: string,\n git: GitRunner = runGit,\n repo?: string,\n): { patch: string; files: number; base: string } | null {\n const branch = ref.replace(/^refs\\/heads\\//, '');\n const base = `origin/${branch}`;\n if (repo !== undefined) {\n const remote = git(['remote', 'get-url', 'origin']).stdout.trim();\n if (!remoteNamesRepo(remote, repo)) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--with-changes sends this checkout's changes, but its origin (${remote || 'none'}) is not ${repo}. Run it from a checkout of ${repo}.`,\n );\n }\n }\n // The platform resolves the ref on the remote, so the diff must be against\n // the remote's current head, not whatever origin/<branch> was last fetched as.\n const fetched = git(['fetch', '--quiet', 'origin', branch]);\n if (fetched.status !== 0) {\n throw new ActionsCliError('invalid_argument', `git fetch origin ${branch} failed: ${fetched.stderr.trim() || 'is the branch pushed?'}`);\n }\n if (git(['rev-parse', '--verify', '--quiet', `${base}^{commit}`]).status !== 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--with-changes diffs against ${base}, which does not exist locally. Push the branch (or run \\`git fetch origin ${branch}\\`), or pass --ref <branch that exists on origin>.`,\n );\n }\n const tracked = git(['diff', '--no-color', '--no-ext-diff', '--src-prefix=a/', '--dst-prefix=b/', base, '--']);\n if (tracked.status !== 0) {\n throw new ActionsCliError('invalid_argument', `git diff against ${base} failed: ${tracked.stderr.trim()}`);\n }\n const parts = [tracked.stdout];\n // Untracked files must be diffed from the repo root: `ls-files --others`\n // lists only the cwd's subtree and `diff --no-index` emits cwd-relative\n // paths, so from a subdirectory the patch would drop or misplace files.\n const topLevel = git(['rev-parse', '--show-toplevel']).stdout.replace(/\\r?\\n$/, '');\n const untracked = git(['-C', topLevel, 'ls-files', '--others', '--exclude-standard', '-z']);\n for (const file of untracked.stdout.split('\\0').filter((f) => f !== '')) {\n // --no-index exits 1 when the files differ, which is the expected case.\n const d = git(['-C', topLevel, 'diff', '--no-color', '--no-ext-diff', '--no-index', '--src-prefix=a/', '--dst-prefix=b/', '--', '/dev/null', file]);\n if (d.stdout !== '') parts.push(d.stdout);\n }\n const patch = parts.filter((p) => p !== '').join('');\n if (patch.trim() === '') return null;\n if (patch.includes('\\0') || /^Binary files .* differ$/m.test(patch)) {\n throw new ActionsCliError('invalid_argument', 'Local changes include a binary file; --with-changes sends text diffs only.');\n }\n const files = patch.match(/^\\+\\+\\+ /gm)?.length ?? 0;\n return { patch, files, base };\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\n/**\n * The label set a delivery choice becomes — `hosts:` rules for proxied,\n * `materialize` for injected. `vault set` and `vault delivery` share it so\n * both surfaces write identical labels.\n */\nexport function vaultDeliveryLabels(opts: {\n proxy?: boolean;\n inject?: boolean;\n hosts?: string[];\n}): string[] {\n if (opts.proxy && opts.inject) {\n throw new ActionsCliError('invalid_argument', '--proxy and --inject are mutually exclusive.');\n }\n const hosts = (opts.hosts ?? [])\n .flatMap((host) => host.split(/[\\s,]+/))\n .map((host) => host.trim().toLowerCase())\n .filter((host) => host !== '');\n if (opts.inject) {\n if (hosts.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n '--inject takes no --hosts — host rules only apply to --proxy.',\n );\n }\n return ['materialize'];\n }\n if (!opts.proxy) {\n throw new ActionsCliError('invalid_argument', 'Pick a delivery: --proxy (with --hosts) or --inject.');\n }\n if (hosts.length === 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n '--proxy needs --hosts — the hosts the real value may be attached to.',\n );\n }\n return [`hosts:${hosts.join(',')}`];\n}\n\n/** `vault set`'s labels: the delivery sugar, or raw --labels — never both. */\nexport function vaultSetLabels(opts: {\n labels?: string[];\n proxy?: boolean;\n inject?: boolean;\n hosts?: string[];\n}): string[] | undefined {\n const flagged = opts.proxy === true || opts.inject === true || (opts.hosts?.length ?? 0) > 0;\n if (flagged && (opts.labels?.length ?? 0) > 0) {\n throw new ActionsCliError('invalid_argument', 'Use --labels or --proxy/--inject --hosts, not both.');\n }\n if (!flagged) return opts.labels;\n return vaultDeliveryLabels(opts);\n}\n\nexport function formatVaultRow(item: CiVaultItem): string {\n const flags = [\n item.kind,\n ...(item.revealable && item.kind === 'secret' ? ['revealable'] : []),\n ...item.labels.map(safeTerm),\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); also finds a workflow file only this ref has')\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 Actions router')\n .option('--provider-region <region>', 'region for --provider (same as --provider <id>:<region>)')\n .addOption(new Option('--max-bid <usd>').hideHelp())\n .addOption(new Option('--max-bid-per <unit>').hideHelp())\n .option('--with-changes', 'run your local changes: everything the working tree has beyond origin/<ref> is sent as a diff and applied after checkout (default --ref: the current branch)'),\n ).action(async (repo: string, opts: CommonOpts & { workflow: string; ref?: string; inputs?: string[]; manual?: boolean; provider?: string; providerRegion?: string; maxBid?: string; maxBidPer?: string; withChanges?: boolean }) => {\n try {\n const c = await client(opts);\n let ref = opts.ref;\n let local: ReturnType<typeof localChangesPatch> = null;\n if (opts.withChanges) {\n ref ??= currentBranch() ?? undefined;\n if (!ref) throw new ActionsCliError('invalid_argument', '--with-changes needs a branch: check one out or pass --ref.');\n local = localChangesPatch(ref, undefined, repo);\n } else if (!opts.json && hasLocalChanges()) {\n console.error(pc.dim('You have uncommitted changes. Add --with-changes to run them.'));\n }\n const { workflows } = await c.get<{ workflows: CiWorkflow[] }>(\n '/api/v1/actions/workflows',\n { repo },\n );\n // A workflow file the diff creates has no catalog row yet; the platform\n // builds the run's definition from the diff when addressed by path.\n let workflow: CiWorkflow | PatchedWorkflowTarget | undefined =\n matchWorkflow(workflows, opts.workflow) ??\n (local && patchTouches(local.patch, opts.workflow) ? { repoFullName: repo, workflowPath: opts.workflow } : undefined);\n // A file only the ref has is not in the catalog either; it dispatches by path.\n let refOnly: CiRefOnlyWorkflow[] | undefined;\n if (!workflow && ref !== undefined) {\n refOnly = (await c.get<CiWorkflowsResponse>('/api/v1/actions/workflows', { repo, ref })).refOnly ?? [];\n const match = matchRefOnly(refOnly, opts.workflow);\n if (match) workflow = { repoFullName: repo, workflowPath: match.path, dispatchable: match.dispatchable };\n }\n if (!workflow) {\n const choices =\n workflowChoices(workflows) +\n (refOnly && refOnly.length > 0 ? `; only on ${ref}: ${workflowChoices(refOnly)}` : '');\n const hint =\n !opts.withChanges && hasLocalChanges() && /^\\.github\\/workflows\\//.test(opts.workflow)\n ? ' If it only exists in your working tree, add --with-changes.'\n : '';\n throw new ActionsCliError(\n 'workflow_not_found',\n `No workflow \"${opts.workflow}\" in ${repo}. Available: ${choices}${hint}`,\n );\n }\n let patch: { patchId: string; files: number; bytes: number } | undefined;\n if (local) {\n const uploaded = await c.postText<{ patchId: string; sha256: string; bytes: number; files: number }>(\n '/api/v1/actions/patches',\n local.patch,\n 'text/x-patch; charset=utf-8',\n );\n patch = { patchId: uploaded.patchId, files: uploaded.files, bytes: uploaded.bytes };\n } else if (opts.withChanges && !opts.json && ref) {\n console.error(pc.dim(`no local changes beyond origin/${ref.replace(/^refs\\/heads\\//, '')}; running the ref as is`));\n }\n const body = dispatchBody(workflow, { ...opts, ref, patchId: patch?.patchId });\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, ...(patch && { patch }) }, (r) => {\n console.log(`${r.created ? 'dispatched' : 'already running'} ${pc.cyan(r.runId)}`);\n console.log(`sha: ${r.headSha}${r.patch ? ` + ${r.patch.files} changed file${r.patch.files === 1 ? '' : 's'} (uncommitted)` : ''}`);\n console.log(`url: ${r.url}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n registerRunsCommands(actions, common, { client, fail, output, formatRunRow });\n registerWorkflowsCommands(actions, common, { client, fail, output });\n\n common(\n actions\n .command('schedule')\n .description('List upcoming scheduled fires and past runs in a time window')\n .option('--reliability', 'show only reliability runs and workflows (hidden by default)')\n .option('--from <timestamp>', 'inclusive start timestamp (default: now)')\n .option('--to <timestamp>', 'exclusive end timestamp (default: seven days after --from)')\n .option('--repo <repo>', 'repository in owner/repo format')\n .option('--workflow <path...>', 'workflow file paths; repeatable')\n .option('--event <event...>', 'trigger events: schedule, push, pull_request, workflow_dispatch')\n .option('--status <status...>', 'run conclusions: passed, failed, running, cancelled, none (excludes upcoming)')\n .option('--tz <zone>', 'IANA time zone (default: local)')\n .option('--limit <n>', 'past-run page size (default 100, max 500)')\n .option('--cursor <cursor>', 'nextCursor from a prior page; keep the window and filters unchanged'),\n ).action(async (opts: ScheduleOpts) => {\n opts.org ??= program.opts<CommonOpts>().org;\n try {\n const query = scheduleQuery(opts);\n const data = await (await client(opts)).get<CiSchedule>('/api/v1/actions/schedule', query);\n output(opts, data, (result) => console.log(formatSchedule(result, result.nextCursor ? nextScheduleCommand(result, opts) : undefined)));\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('benchmarks')\n .description('Show the benchmark runs this run produced: per-provider score and success rate')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const run = await (await client(opts)).get<CiRun>(`/api/v1/actions/runs/${runId}`);\n const benchmarks = run.benchmarks ?? [];\n output(opts, { runId: run.id, conclusion: run.conclusion, benchmarks }, () => console.log(formatRunResults(benchmarks)));\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 providers Actions can place on (order, act/usable, key status); keys and rates: compute byok');\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 // configure/verify/remove predate `compute byok` and stay on the\n // /api/v1/actions/providers aliases, which keep the actions OAuth scopes, so\n // logins made before the providers scopes existed keep working.\n common(\n providers\n .command('configure')\n .description('Deprecated: use `compute byok configure`. Save the org\\'s credential for a provider (owner/admin)')\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 // A provider key is a local secret: trusted hosts only, even with --allow-untrusted-host.\n const c = await secretValueClient(opts, 'provider keys');\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('Deprecated: use `compute byok verify`. Probe the stored provider key with a real sandbox')\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('Deprecated: use `compute byok remove`. 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 registerReposCommands(actions, common, { client, fail, output });\n registerIntegrationsCommands(actions, common, { client, fail, output });\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 .option('--proxy', 'hand the job a placeholder; the value is attached to requests for --hosts at egress')\n .option('--inject', 'inject the real value into the job environment (the default)')\n .option('--hosts <hosts...>', 'hosts the proxied value may be attached to (comma or space separated, *.example.com covers subdomains)'),\n ).action(async (name: string, opts: VaultOpts & { fromFile?: string; revealable?: boolean; description?: string; labels?: string[]; proxy?: boolean; inject?: boolean; hosts?: 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 labels = vaultSetLabels(opts);\n const body = vaultSetBody(name, value, { ...opts, kind, labels });\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('delivery')\n .description('Reclassify how a secret reaches a job — labels only, no value needed')\n .argument('<name>', 'item name')\n .option('--proxy', 'hand the job a placeholder; the value is attached to requests for --hosts at egress')\n .option('--inject', 'inject the real value into the job environment')\n .option('--hosts <hosts...>', 'hosts the proxied value may be attached to (comma or space separated, *.example.com covers subdomains)'),\n ).action(async (name: string, opts: VaultOpts & { proxy?: boolean; inject?: boolean; hosts?: string[] }) => {\n try {\n const kind = parseVaultKind(opts.kind);\n const labels = vaultDeliveryLabels(opts);\n const result = await (await client(opts)).patch<CiVaultSaveResponse>(\n vaultPath('/api/v1/vault', { repo: opts.repo }),\n { name, kind, labels },\n );\n output(opts, result, (r) => {\n const where = opts.repo ? safeTerm(opts.repo) : 'org';\n console.log(\n `reclassified ${pc.cyan(safeTerm(r.item.name))} ${pc.dim(`(labels: ${r.item.labels.join(', ') || 'none'}, v${r.item.version}, ${where})`)}`,\n );\n });\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 registerSettingsCommands(actions, 'actions', common, {\n client,\n fail,\n output,\n usageErrorOutput,\n });\n}\n","import { ActionsCliError, type ActionsClient } from './actions-client.js';\nimport { output, type CommonOpts } from './actions.js';\nimport type { CommandResult, SandboxProcess, SandboxProcessStatus } from '@computesdk/platform';\n\n/** A single argument is a shell program; multiple arguments preserve argv. */\nexport function execCommand(args: string[]): string {\n return args.length === 1 ? args[0] : args.map((arg) => `'${arg.replace(/'/g, `'\\\\''`)}'`).join(' ');\n}\n\nexport interface ExecOpts extends CommonOpts {\n cwd?: string;\n env?: string[];\n timeout?: string;\n timeoutMs?: string;\n detach?: boolean;\n stream?: boolean;\n}\n\n// The buffered command endpoint has a 300s route lifetime and reserves 10s.\nconst BUFFERED_MAX_MS = 290_000;\n\nexport function execTimeout(opts: ExecOpts): number | undefined {\n if (opts.detach && (opts.stream || opts.timeout !== undefined || opts.timeoutMs !== undefined)) {\n throw new ActionsCliError('invalid_argument', '--detach cannot be combined with --stream or a command timeout.');\n }\n if (opts.timeout !== undefined && opts.timeoutMs !== undefined) {\n throw new ActionsCliError('invalid_argument', 'Use --timeout (seconds) or --timeout-ms, not both.');\n }\n const raw = opts.timeout ?? opts.timeoutMs;\n if (raw === undefined) return undefined;\n const ms = Number(raw) * (opts.timeout !== undefined ? 1000 : 1);\n if (raw.trim() === '' || !Number.isSafeInteger(ms) || ms < 0 || ms > 2_147_483_647) {\n throw new ActionsCliError('invalid_argument', 'Timeout must be a non-negative duration up to 2147483647 ms (0 means no command time limit).');\n }\n return ms;\n}\n\n/** Execute against an existing sandbox; no provisioning or automatic retries. */\nexport async function execute(\n c: ActionsClient,\n sandboxId: string,\n body: { command: string; cwd?: string; env?: Record<string, string> },\n opts: ExecOpts,\n): Promise<void> {\n const timeoutMs = execTimeout(opts);\n if (!opts.detach && !opts.stream && timeoutMs !== 0 && (timeoutMs === undefined || timeoutMs <= BUFFERED_MAX_MS)) {\n const res = await c.post<{ commandId: string } & CommandResult>(\n `/api/v1/sandboxes/${sandboxId}/commands`,\n { ...body, ...(timeoutMs !== undefined ? { timeoutMs } : {}) },\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 if (res.exitCode !== 0) process.exitCode = res.exitCode;\n return;\n }\n const { process: job } = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${sandboxId}/processes`, body,\n );\n if (opts.detach) {\n output(opts, job, (p) => {\n console.log(p.jobId);\n console.error(`Follow: compute logs ${sandboxId} ${p.jobId} --follow`);\n });\n return;\n }\n // Use bounded waits and cumulative output so jobs can outlive a single\n // HTTP request, without replaying output or starting another process.\n await streamJob(c, sandboxId, job.jobId, timeoutMs ?? BUFFERED_MAX_MS, opts);\n}\n\nasync function streamJob(c: ActionsClient, sandboxId: string, jobId: string, timeoutMs: number, opts: ExecOpts): Promise<void> {\n const base = `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`;\n const controller = new AbortController();\n let stopCode: number | undefined;\n let stopping: Promise<void> | undefined;\n let killError: string | undefined;\n const stop = (code: number, signal: string) => {\n if (stopping) return;\n stopCode = code;\n stopping = c.post(`${base}/kill`, { signal }, { signal: AbortSignal.timeout(10_000) })\n .then(() => undefined)\n .catch(() => {\n killError = `Could not stop job ${jobId}; run compute instances kill ${sandboxId} ${jobId}.`;\n if (!opts.json) console.error(killError);\n })\n .finally(() => controller.abort());\n };\n const onInterrupt = () => stop(130, 'SIGINT');\n const onTerminate = () => stop(143, 'SIGTERM');\n process.on('SIGINT', onInterrupt);\n process.on('SIGTERM', onTerminate);\n const deadline = timeoutMs === 0 ? undefined : Date.now() + timeoutMs;\n const timer = timeoutMs === 0 ? undefined : setTimeout(() => stop(124, 'SIGKILL'), timeoutMs);\n let stdoutOffset = 0;\n let stderrOffset = 0;\n try {\n while (stopCode === undefined) {\n const remaining = deadline === undefined ? 1000 : deadline - Date.now();\n if (remaining <= 0) { stop(124, 'SIGKILL'); break; }\n const { process: status } = await c.post<{ process: SandboxProcessStatus }>(\n `${base}/wait`, { timeoutMs: Math.min(1000, remaining) },\n { signal: controller.signal },\n );\n const emit = (event: string, data: Record<string, unknown>) => {\n if (opts.json) process.stdout.write(JSON.stringify({ event, ...data }) + '\\n');\n else if (event === 'stdout') process.stdout.write(String(data.chunk));\n else if (event === 'stderr') process.stderr.write(String(data.chunk));\n };\n if (status.stdout.length > stdoutOffset) emit('stdout', { chunk: status.stdout.slice(stdoutOffset) });\n if (status.stderr.length > stderrOffset) emit('stderr', { chunk: status.stderr.slice(stderrOffset) });\n stdoutOffset = status.stdout.length;\n stderrOffset = status.stderr.length;\n if (status.status === 'exited') {\n const code = status.exitCode ?? 128;\n emit('exit', { exitCode: code });\n if (code !== 0) process.exitCode = code;\n return;\n }\n }\n } catch (error) {\n if (stopCode === undefined) {\n // The process may still be running. Do not replay the start request.\n const recovery = `Job ${jobId} remains available: compute logs ${sandboxId} ${jobId} --follow`;\n if (error instanceof Error) {\n error.message += `. ${recovery}`;\n throw error;\n }\n throw new Error(`${String(error)}. ${recovery}`);\n }\n } finally {\n clearTimeout(timer);\n process.removeListener('SIGINT', onInterrupt);\n process.removeListener('SIGTERM', onTerminate);\n await stopping;\n if (stopCode !== undefined) {\n process.exitCode = stopCode;\n if (opts.json) process.stdout.write(JSON.stringify({ event: 'exit', exitCode: stopCode, ...(killError ? { error: killError } : {}) }) + '\\n');\n }\n }\n}\n","\nexport interface SyncEntry {\n path: string;\n type: 'file' | 'directory' | 'symlink';\n mode: number;\n protected?: boolean;\n links?: number;\n hash?: string;\n link?: string;\n}\nexport interface TreeRequest {\n root: string;\n missing?: boolean;\n destination?: boolean;\n remove?: SyncEntry[];\n directories?: SyncEntry[];\n entries?: SyncEntry[];\n}\n\n/** Self-contained: the same function runs locally and in a sandbox's Node runtime. */\nexport async function treeOperation(input: TreeRequest, requireModule: NodeRequire, exclude?: (name: string, directory: boolean) => boolean): Promise<SyncEntry[]> {\n const fs = requireModule('node:fs') as typeof import('node:fs');\n const path = requireModule('node:path') as typeof import('node:path');\n const crypto = requireModule('node:crypto') as typeof import('node:crypto');\n const root = path.resolve(input.root);\n if (root.split(path.sep).includes('.git')) throw new Error('Sync cannot target .git.');\n if (root === path.parse(root).root) throw new Error('Sync requires a project directory, not a filesystem root.');\n // Never follow a destination symlink while applying changes.\n const checked = (relative: string): string => {\n if (path.isAbsolute(relative) || relative.split(/[\\\\/]/).some((s) => s === '..' || s === '.git') || relative.includes('\\0')) {\n throw new Error('Unsafe sync path: ' + relative);\n }\n const full = path.join(root, relative);\n let cursor = path.parse(full).root;\n const parts = full.slice(cursor.length).split(path.sep);\n for (const segment of parts.slice(0, -1)) {\n cursor = path.join(cursor, segment);\n try {\n if (fs.lstatSync(cursor).isSymbolicLink()) throw new Error('Sync cannot traverse symlink: ' + cursor);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n }\n return full;\n };\n checked('');\n try {\n const stat = fs.lstatSync(root);\n if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Sync requires a real directory: ' + root);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || !input.missing) throw error;\n if (!input.directories && !input.remove) return [];\n fs.mkdirSync(root, { recursive: true });\n }\n for (const expected of input.remove ?? []) {\n const relative = expected.path;\n const full = checked(relative);\n if (!relative) throw new Error('Cannot delete the sync root.');\n // Files first, directories last. rmdir refuses unexpected/new children.\n const stat = fs.lstatSync(full);\n const type = stat.isSymbolicLink() ? 'symlink' : stat.isDirectory() ? 'directory' : 'file';\n let hash: string | undefined;\n if (type === 'file') {\n const digest = crypto.createHash('sha256');\n for await (const chunk of fs.createReadStream(full)) digest.update(chunk);\n hash = digest.digest('hex');\n }\n if (type !== expected.type || type === 'file' && (hash !== expected.hash || (stat.mode & 0o777) !== expected.mode) ||\n type === 'symlink' && fs.readlinkSync(full) !== expected.link) throw new Error('Destination changed before deletion: ' + relative);\n if (stat.isDirectory()) fs.rmdirSync(full);\n else fs.unlinkSync(full);\n }\n for (const entry of input.directories ?? []) {\n const full = checked(entry.path);\n try {\n if (!fs.lstatSync(full).isDirectory()) throw new Error('Sync type conflict: ' + entry.path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n fs.mkdirSync(full, { mode: entry.mode | 0o700 });\n }\n }\n if (input.remove || input.directories) return [];\n const result: SyncEntry[] = [];\n // The checkpoint engine owns traversal and hashing. This pass only checks\n // planned paths against current filesystem metadata and sync's boundaries.\n for (const entry of input.entries ?? []) {\n const full = checked(entry.path);\n const stat = fs.lstatSync(full);\n const type = stat.isSymbolicLink() ? 'symlink' : stat.isDirectory() ? 'directory' : stat.isFile() ? 'file' : undefined;\n if (!type || type !== entry.type || (stat.mode & 0o777) !== entry.mode) throw new Error('Project changed during snapshot scan: ' + entry.path);\n if (exclude?.(entry.path, type === 'directory')) continue;\n if (type === 'symlink') {\n const link = fs.readlinkSync(full);\n const target = path.resolve(path.dirname(full), link);\n if (!input.destination && (path.isAbsolute(link) || target !== root && !target.startsWith(root + path.sep))) throw new Error('Symlink points outside sync root: ' + entry.path);\n if (link !== entry.link) throw new Error('Project changed during snapshot scan: ' + entry.path);\n }\n result.push({ ...entry,\n ...(input.destination && type === 'file' && stat.nlink > 1 ? { links: stat.nlink } : {}),\n ...(input.destination && type === 'directory' && fs.existsSync(path.join(full, '.git')) ? { protected: true } : {}),\n });\n }\n return result;\n}\nexport const localTree = async (input: TreeRequest, exclude?: (name: string, directory: boolean) => boolean): Promise<SyncEntry[]> => {\n const { scanLocalTree } = await import('./snapshot-engine.js');\n return scanLocalTree(input, exclude);\n};\n","/** Adapter around the exact OCI checkpoint engine shipped by the platform. */\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { tmpdir } from 'node:os';\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { randomUUID, createHash } from 'node:crypto';\nimport type { ActionsClient } from './actions-client.js';\nimport { execCommand } from './exec.js';\nimport { treeOperation, type SyncEntry, type TreeRequest } from './sync-fs.js';\nimport { createRequire } from 'node:module';\n\nconst executeFile = promisify(execFile);\nexport const ENGINE_FILE = fileURLToPath(new URL('../checkpoint.cjs', import.meta.url));\nconst RUNNER_FILE = fileURLToPath(new URL('../checkpoint-runner.cjs', import.meta.url));\nexport interface IndexEntry { type: 'dir' | 'file' | 'symlink'; mode: number; sha?: string; link?: string; layer: number; size?: number; mtime?: number }\nexport interface CheckpointConfig {\n kind: string; files: Record<string, IndexEntry>; capture: { paths: string[]; exclude: string[] };\n [key: string]: unknown;\n}\nexport interface CaptureResult { manifestKey: string; configDigest: string; layers: { root: string; digest: string }[] }\nexport interface EngineDiff { added: string[]; changed: { path: string }[]; deleted: string[] }\nexport type EngineEndpoint = { local: string } | { id: string; remote: string };\nexport const endpointRoot = (e: EngineEndpoint): string => 'local' in e ? e.local : e.remote;\nconst requireModule = createRequire(import.meta.url);\n\n/** Snapshot selectors are globs; fail rather than accidentally widen an exact path. */\nexport function exactSelector(value: string): string {\n if (/[*?]/.test(value)) throw new Error('Snapshot sync cannot address literal * or ? in a path: ' + value);\n return value.split(path.sep).join('/');\n}\nexport function ignoredPaths(root: string, exclude?: (name: string, directory: boolean) => boolean): string[] {\n const paths = ['**/.git', '**/.git/**'];\n if (!exclude || !fs.existsSync(root)) return paths;\n const visit = (dir: string) => {\n for (const entry of fs.readdirSync(path.join(root, dir), { withFileTypes: true })) {\n const name = dir ? dir + '/' + entry.name : entry.name;\n if (entry.name === '.git' || exclude(name, entry.isDirectory())) paths.push(exactSelector(path.join(root, name)));\n else if (entry.isDirectory()) visit(name);\n }\n };\n visit('');\n return paths;\n}\n\nexport function indexEntries(config: CheckpointConfig, root: string): SyncEntry[] {\n const result: SyncEntry[] = [];\n for (const [absolute, entry] of Object.entries(config.files)) {\n if (absolute === root) continue;\n const relative = path.posix.relative(root, absolute);\n if (!relative || relative.startsWith('/') || relative.includes('\\\\') || relative.split('/').some((p) => !p || p === '..' || p === '.' || p === '.git') || relative.includes('\\0')) throw new Error('Unsafe checkpoint file index.');\n if (!['dir', 'file', 'symlink'].includes(entry.type)) throw new Error('Unsupported checkpoint entry.');\n result.push({ path: relative, type: entry.type === 'dir' ? 'directory' : entry.type, mode: entry.mode & 0o777,\n ...(entry.sha ? { hash: entry.sha } : {}), ...(entry.link !== undefined ? { link: entry.link } : {}) });\n }\n return result.sort((a, b) => a.path.localeCompare(b.path));\n}\n\nexport class SnapshotSession {\n readonly temp = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'compute-sync-')));\n private remoteRoots = new Map<string, string>();\n constructor(private c?: ActionsClient) {}\n async command(id: string, script: string): Promise<string> {\n const result = await this.c!.post<{ exitCode: number; stdout: string; stderr: string }>(`/api/v1/sandboxes/${id}/commands`, {\n command: execCommand(['node', '--input-type=commonjs', '-e', script]), timeoutMs: 290_000,\n });\n if (result.exitCode !== 0) throw new Error(`Snapshot sync failed: ${result.stderr || result.stdout || 'Node.js is required in the sandbox.'}`);\n return result.stdout;\n }\n async remoteRoot(id: string): Promise<string> {\n const existing = this.remoteRoots.get(id);\n if (existing) return existing;\n const root = JSON.parse(await this.command(id, `const fs=require('node:fs');console.log(JSON.stringify(fs.mkdtempSync(require('node:path').join(require('node:os').tmpdir(),'compute-sync-'))))`));\n if (typeof root !== 'string' || !root.startsWith('/') || !path.posix.basename(root).startsWith('compute-sync-')) throw new Error('Invalid snapshot work directory.');\n this.remoteRoots.set(id, root);\n await this.write(id, path.posix.join(root, 'checkpoint.cjs'), fs.readFileSync(ENGINE_FILE, 'utf8'));\n await this.write(id, path.posix.join(root, 'runner.cjs'), fs.readFileSync(RUNNER_FILE, 'utf8'));\n return root;\n }\n async write(id: string, file: string, content: string): Promise<void> {\n await this.c!.post(`/api/v1/sandboxes/${id}/files`, { path: file, content });\n }\n async read(id: string, file: string): Promise<string> {\n const response = await this.c!.get<{ type: string; content?: string }>(`/api/v1/sandboxes/${id}/files`, { path: file });\n if (response.type !== 'file' || response.content === undefined) throw new Error('Snapshot result file is unavailable.');\n return response.content;\n }\n async operation<T>(id: string | undefined, operation: string, args: Record<string, unknown>): Promise<T> {\n const root = id ? await this.remoteRoot(id) : this.temp;\n const payload = path.join(root, randomUUID() + '.args.json');\n const resultPath = path.join(root, randomUUID() + '.result.json');\n const json = JSON.stringify({ ...args, resultPath });\n if (id) {\n await this.write(id, payload, json);\n const res = await this.c!.post<{ exitCode: number; stderr: string; stdout: string }>(`/api/v1/sandboxes/${id}/commands`, {\n command: execCommand(['node', path.posix.join(root, 'runner.cjs'), path.posix.join(root, 'checkpoint.cjs'), operation, payload]), timeoutMs: 290_000,\n });\n if (res.exitCode !== 0) {\n let detail = res.stderr || res.stdout;\n try { detail = await this.read(id, resultPath); } catch { /* no result if startup failed */ }\n throw new Error(`Snapshot ${operation} failed: ${detail}`);\n }\n return JSON.parse(await this.read(id, resultPath));\n }\n fs.writeFileSync(payload, json, { mode: 0o600 });\n try { await executeFile(process.execPath, [RUNNER_FILE, ENGINE_FILE, operation, payload], { timeout: 300_000, maxBuffer: 1024 * 1024 }); }\n catch (error) {\n const detail = fs.existsSync(resultPath) ? fs.readFileSync(resultPath, 'utf8') : (error as Error).message;\n throw new Error(`Snapshot ${operation} failed: ${detail}`);\n }\n return JSON.parse(fs.readFileSync(resultPath, 'utf8'));\n }\n async guard(endpoint: EngineEndpoint, request: Omit<TreeRequest, 'root'>): Promise<SyncEntry[]> {\n const input = { root: endpointRoot(endpoint), ...request };\n if ('local' in endpoint) return treeOperation(input, requireModule);\n const root = await this.remoteRoot(endpoint.id);\n const payload = path.posix.join(root, randomUUID() + '.guard.json');\n const resultPath = payload + '.result';\n await this.write(endpoint.id, payload, JSON.stringify(input));\n await this.command(endpoint.id, `const fs=require('node:fs');(${treeOperation.toString()})(JSON.parse(fs.readFileSync(${JSON.stringify(payload)},'utf8')),require).then(entries=>fs.writeFileSync(${JSON.stringify(resultPath)},JSON.stringify(entries))).catch(e=>{console.error(e.message);process.exitCode=1})`);\n return JSON.parse(await this.read(endpoint.id, resultPath));\n }\n async scan(endpoint: EngineEndpoint, destination = false, exclude?: (name: string, directory: boolean) => boolean): Promise<{ config: CheckpointConfig; entries: SyncEntry[] }> {\n const root = endpointRoot(endpoint);\n await this.guard(endpoint, { missing: destination });\n const result = await this.operation<{ config: CheckpointConfig; missing: string[] }>('id' in endpoint ? endpoint.id : undefined, 'scan', {\n paths: [root], exclude: 'local' in endpoint ? ignoredPaths(root, exclude) : ['**/.git', '**/.git/**'],\n });\n if (result.missing.length && !(destination && result.missing.length === 1 && result.missing[0] === root)) throw new Error('Snapshot scan could not read all project paths: ' + result.missing.join(', '));\n const entries = await this.guard(endpoint, { missing: destination, destination, entries: indexEntries(result.config, root) });\n return { config: result.config, entries };\n }\n async diff(source: SyncEntry[], destination: SyncEntry[]): Promise<EngineDiff> {\n const toConfig = (entries: SyncEntry[]) => ({ files: Object.fromEntries(entries.map((e) => [e.path, { type: e.type === 'directory' ? 'dir' : e.type, mode: e.mode, sha: e.hash, link: e.link }])) });\n const a = path.join(this.temp, randomUUID() + '.json'), b = path.join(this.temp, randomUUID() + '.json');\n fs.writeFileSync(a, JSON.stringify(toConfig(destination)), { mode: 0o600 });\n fs.writeFileSync(b, JSON.stringify(toConfig(source)), { mode: 0o600 });\n return (await this.operation<{ diff: EngineDiff }>(undefined, 'diff', { a: { configPath: a }, b: { configPath: b } })).diff;\n }\n async close(): Promise<void> {\n try {\n for (const [id, root] of this.remoteRoots) {\n try { await this.command(id, `require('node:fs').rmSync(${JSON.stringify(root)},{recursive:true,force:true})`); } catch { /* private scratch only; do not mask a transfer failure */ }\n }\n } finally { fs.rmSync(this.temp, { recursive: true, force: true }); }\n }\n}\n\n/** Build a valid, content-addressed OCI view containing only the planned writes. */\nexport function selectSnapshot(store: string, manifestKey: string, root: string, copy: SyncEntry[], destination: { config: CheckpointConfig; entries: SyncEntry[] }, destinationRoot: string): string {\n if (!/^manifests\\/[a-f0-9-]+\\.json$/.test(manifestKey)) throw new Error('Invalid snapshot manifest key.');\n const manifest = JSON.parse(fs.readFileSync(path.join(store, manifestKey), 'utf8'));\n if (!/^sha256:[a-f0-9]{64}$/.test(manifest.config?.digest)) throw new Error('Invalid snapshot config digest.');\n const configHex = manifest.config.digest.slice(7);\n const bytes = fs.readFileSync(path.join(store, 'blobs', configHex));\n if (createHash('sha256').update(bytes).digest('hex') !== configHex) throw new Error('Snapshot config digest mismatch.');\n const raw = JSON.parse(bytes.toString('utf8'));\n const config: CheckpointConfig = raw.computesdk?.kind === 'sandbox-checkpoint' ? raw.computesdk : raw;\n const files: Record<string, IndexEntry> = {};\n const wantedLayers = new Set<number>();\n const dest = new Map(destination.entries.map((e) => [e.path, e]));\n for (const entry of copy) {\n const absolute = path.posix.join(root, entry.path);\n const captured = config.files[absolute];\n if (!captured || captured.type !== (entry.type === 'directory' ? 'dir' : entry.type) || captured.sha !== entry.hash || captured.link !== entry.link || (captured.mode & 0o777) !== entry.mode) throw new Error('Source changed during snapshot capture; rerun sync.');\n files[absolute] = { ...captured, mode: entry.mode };\n if (entry.type !== 'directory') wantedLayers.add(captured.layer);\n let parent = path.posix.dirname(absolute);\n while (parent === root || parent.startsWith(root + '/')) {\n const index = config.files[parent];\n if (!index || index.type !== 'dir') throw new Error('Snapshot is missing a parent directory.');\n const relative = path.posix.relative(root, parent);\n const mode = relative ? dest.get(relative)?.mode : destination.config.files[destinationRoot]?.mode;\n files[parent] ??= { ...index, mode: (mode ?? index.mode) & 0o777 };\n if (parent === root) break;\n parent = path.posix.dirname(parent);\n }\n }\n config.files = files;\n const allLayers = manifest.layers as { annotations: Record<string, string> }[];\n const indexes = allLayers.map((layer, index) => wantedLayers.has(config.capture.paths.indexOf(layer.annotations['com.computesdk.checkpoint.root'])) ? index : -1).filter((index) => index >= 0);\n manifest.layers = indexes.map((index) => allLayers[index]);\n if (raw.rootfs) raw.rootfs.diff_ids = indexes.map((index) => raw.rootfs.diff_ids[index]);\n const selected = Buffer.from(JSON.stringify(raw));\n const hex = createHash('sha256').update(selected).digest('hex');\n fs.writeFileSync(path.join(store, 'blobs', hex), selected, { mode: 0o600 });\n manifest.config = { ...manifest.config, digest: 'sha256:' + hex, size: selected.length };\n const key = 'manifests/selected.json';\n fs.writeFileSync(path.join(store, key), JSON.stringify(manifest), { mode: 0o600 });\n return key;\n}\n\nexport async function scanLocalTree(input: TreeRequest, exclude?: (name: string, directory: boolean) => boolean): Promise<SyncEntry[]> {\n const session = new SnapshotSession();\n try {\n if (input.remove || input.directories) return session.guard({ local: input.root }, input);\n return (await session.scan({ local: input.root }, !!input.missing, exclude)).entries;\n } finally { await session.close(); }\n}\n","/**\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 # SDK provider credentials in this environment\n * compute byok … # the org's BYOK provider keys and custom rates\n * compute org … # active org, members, invitations\n * compute invitations … # your own invitations (show/accept/decline)\n * compute actions … # Actions API\n * compute credits [ledger | topup <usd>] # prepaid credit, which managed accounts bill from\n * compute market … # not generally available (hidden from help)\n * compute new [vercel | --vercel] # create a sandbox (short for `compute sandboxes create`)\n * compute instances … # platform compute-instance control plane\n * (alias: compute sandboxes, compute sbx)\n * compute bench … # benchmarks platform CLI (runs, results, fork, …)\n */\n\nimport 'dotenv/config';\nimport { Command, Option } 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 { registerByokCommands } from './byok.js';\nimport { registerMarketCommands } from './market.js';\nimport { registerCreditsCommands } from './credits.js';\nimport { inheritParentOptions } from './option-inheritance.js';\nimport { registerSandboxesCommands } from './sandboxes.js';\nimport { registerAgentsCommands } from './agents.js';\nimport { fail } from './actions.js';\nimport { registerSyncCommand } from './sync.js';\nimport { registerStatusCommand } from './status.js';\nimport { login, clearPendingLogins, type LoginOptions } from './login.js';\nimport { parseBenchDispatch, runBench } from './bench.js';\nimport { registerManifestCommand } from './manifest.js';\nimport { registerInvitationsCommands, registerOrgMemberCommands } from './org-members.js';\nimport { benchAuth, envBaseUrl, fetchWhoami, formatWhoami } from './session.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// `compute credits --org x topup 50`: a parent's flags reach the subcommand.\ninheritParentOptions(program);\n\nprogram\n .name('compute')\n .description('ComputeSDK CLI')\n .version(VERSION, '-v, --version', 'print the CLI version')\n .enablePositionalOptions()\n .passThroughOptions();\n\n// Keep the previous uppercase shorthand compatible as well.\nprogram.addOption(new Option('-V', 'print the CLI version').hideHelp());\nprogram.on('option:V', () => { console.log(VERSION); process.exit(0); });\nprogram.addHelpText('before', 'Run code on a cloud sandbox:\\n compute new\\n compute exec echo hello\\n compute destroy\\n');\n\n// Reports the OAuth login just made, so it reads the stored login rather\n// than COMPUTE_API_KEY.\nasync function printSessionLine(options?: { baseUrl?: string }): Promise<void> {\n try {\n const { getMe, resolveAuth } = await import('@benchsdk/cli');\n const me = await getMe(await resolveAuth({ baseUrl: options?.baseUrl ?? envBaseUrl() }));\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?: LoginOptions): Promise<void> {\n await login(options);\n}\n\nasync function runLogout(): Promise<void> {\n const { clearCredentials } = await import('@benchsdk/cli');\n await clearCredentials();\n clearPendingLogins();\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 .option('--no-browser', 'print the sign-in URL instead of opening a browser')\n .option('--json', 'return a sign-in URL and code immediately; use --wait to complete login')\n .option('--wait', 'wait for approval (default without --json)')\n .option('--new', 'replace the pending sign-in with a new code')\n .action(async (opts) => {\n try { await runLogin(opts); } catch (error) { fail(error, opts); return; }\n if (opts.json) return;\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 me = await fetchWhoami(await benchAuth({ baseUrl: options.baseUrl }));\n if (options.json) {\n console.log(JSON.stringify(me, null, 2));\n return;\n }\n for (const line of formatWhoami(me)) console.log(line);\n}\n\nconst org = program.command('org').description('Manage the active organization, its members and invitations');\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 // The switch belongs to the stored user login: COMPUTE_API_KEY (an org\n // key, no user) must not stand in for it, so only the URL is overridden.\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\n// members / invitations / invite / member set-role|remove / leave, over the\n// v1 organization routes with the `current` org alias (src/org-members.ts).\nregisterOrgMemberCommands(org);\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// ─── invitations ─────────────────────────────────────────────────────────────\n// The signed-in user's own invitations: list, show, accept, decline.\n\nregisterInvitationsCommands(program);\n\n// ─── actions ─────────────────────────────────────────────────────────────────\n\nregisterActionsCommands(program);\n\n// ─── byok ────────────────────────────────────────────────────────────────────\n// `compute byok` drives /api/v1/providers — the org's BYOK provider keys and\n// custom rates, shared by Actions and sandboxes (src/byok.ts).\n\nregisterByokCommands(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// ─── credits ─────────────────────────────────────────────────────────────────\n// `compute credits` — prepaid credit (balance, ledger, top-ups), which managed\n// accounts bill from (src/credits.ts).\nregisterCreditsCommands(program);\nregisterStatusCommand(program);\n\n// ─── sandboxes ───────────────────────────────────────────────────────────────\n// `compute instances` (alias `compute sandboxes`/`sbx`) drives\n// /api/v1/sandboxes — the customer-facing compute control plane\n// (create/exec/processes/files/urls). Same auth as actions.\n\nregisterSandboxesCommands(program);\nregisterSyncCommand(program);\n\n// ─── agents ──────────────────────────────────────────────────────────────────\n// `compute agents` (alias `ag`) drives /api/v1/agents — managed agents:\n// durable configs whose sessions run inside routed sandboxes. Same auth.\n\nregisterAgentsCommands(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// fork/iterations/artifacts/logs/export all dispatch through it,\n// with COMPUTE_PLATFORM_URL, COMPUTE_API_KEY and COMPUTE_ORG/--org forwarded\n// (src/bench.ts).\n\nprogram\n .command('bench')\n .description('Benchmarks platform CLI (run, auth, org, benchmarks, runs, results, fork, artifacts, export, ...)')\n .allowUnknownOption()\n .helpOption(false)\n .action(() => {\n // Never reached: bench args are dispatched pre-parse below.\n });\n\n// ─── __manifest (hidden) ─────────────────────────────────────────────────────\n// Regenerate the committed cli-manifest.json with\n// `pnpm --filter @computesdk/cli run manifest` after changing commands.\n\nregisterManifestCommand(program, {\n version: packageJson.version,\n packageDir: join(__dirname, '..'),\n});\n\n// ─── Run ─────────────────────────────────────────────────────────────────────\n\n// Bench args are opaque to commander (its own --flags, `--` separators, file\n// paths), so they dispatch before parsing — including `compute --org x bench`.\n// `@benchsdk/runner`'s run() owns the process — it exits itself after dispatch.\nasync function main() {\n const bench = parseBenchDispatch(process.argv.slice(2));\n if (bench) {\n await runBench(bench);\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","/**\n * `compute byok` — the org's BYOK providers over `/api/v1/providers`: the\n * providers it brings its own key for, each key's state, and the org's custom\n * rate. Keys and custom rates serve every product that places sandboxes\n * (Actions jobs and sandbox creates alike), which is why they live here and\n * not under `compute actions` or `compute instances`.\n *\n * A custom rate is the org's own number for cost reporting (typically what it\n * pays the provider). Sandbox costs on that provider are reported at it\n * instead of the platform rate; it never changes what the org is billed.\n *\n * `compute providers` is a different thing: the provider credentials in the\n * local environment that the SDK would use.\n */\n\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport { output, client, fail, parseInputs, secretValueClient, usageErrorOutput, type CommonOpts } from './actions.js';\nimport { confirmWrite } from './confirm.js';\nimport { formatRateAllUnits, type RateAllUnits, type RatePer } from './rate-display.js';\nimport { safeTerm } from './term.js';\n\n// Wire shapes: benchmarks-platform lib/providers/byok-wire.ts.\n\nexport interface ProviderRate {\n usd: number;\n per: RatePer;\n rateUsd: RateAllUnits;\n}\n\nexport interface ByokKey {\n provider: string;\n /** Masked tail of the stored key; null when none is stored. Never the key. */\n keyHint: string | null;\n lastCheckedAt: string | null;\n status: 'connected' | 'unconfigured' | 'error';\n statusDetail: string | null;\n actCapable: boolean;\n credential: 'key';\n fields: Array<{ name: string; label: string; placeholder?: string; secret: boolean; required?: boolean }>;\n /** Region-keyed credentials (archil): each region's masked hint. */\n pairs?: Array<{ region: string; keyHint: string | null }>;\n}\n\nexport interface ByokProvider {\n provider: string;\n regions: string[];\n key: ByokKey;\n /** What costs are reported at: `customRate` when set, else `platformRate`. */\n rate: ProviderRate;\n customRate: ProviderRate | null;\n platformRate: ProviderRate;\n}\n\nexport interface ByokKeyResponse {\n key: ByokKey;\n /** Present on the verify response. */\n verified?: boolean;\n}\n\nconst RATE_UNITS: RatePer[] = ['second', 'minute', 'hour'];\nconst MAX_RATE_USD = 1_000;\n\nfunction providerPath(provider: string, rest = ''): string {\n return `/api/v1/providers/${encodeURIComponent(provider)}${rest}`;\n}\n\nfunction keyText(key: ByokKey): string {\n if (key.keyHint === null) return pc.gray('no key');\n const status =\n key.status === 'connected' ? pc.green('connected') : key.status === 'error' ? pc.red('error') : pc.yellow('untested');\n const hints = key.pairs?.length\n ? key.pairs.map((p) => `${safeTerm(p.keyHint ?? '—')}@${safeTerm(p.region)}`).join(',')\n : safeTerm(key.keyHint);\n return `${status} ${pc.dim(hints)}`;\n}\n\nfunction rateText(p: ByokProvider): string {\n return p.customRate\n ? `${formatRateAllUnits(p.customRate.rateUsd)} ${pc.cyan('custom')}`\n : `${formatRateAllUnits(p.platformRate.rateUsd)} ${pc.dim('platform')}`;\n}\n\n/** `● blaxel connected …abcd $0.1008/hr · … platform`. */\nexport function formatByokRow(p: ByokProvider): string {\n const ready = p.key.status === 'connected';\n const icon = ready ? pc.green('●') : pc.gray('○');\n const name = ready ? pc.white(safeTerm(p.provider)) : pc.gray(safeTerm(p.provider));\n return ` ${icon} ${name} ${keyText(p.key)} ${rateText(p)}`;\n}\n\nexport function formatByokDetail(p: ByokProvider): string {\n const lines = [\n `${pc.white(safeTerm(p.provider))} ${keyText(p.key)}`,\n ` regions ${p.regions.length > 0 ? p.regions.map(safeTerm).join(', ') : 'account default'}`,\n ` last tested ${p.key.lastCheckedAt === null ? '—' : safeTerm(p.key.lastCheckedAt)}`,\n ` platform rate ${formatRateAllUnits(p.platformRate.rateUsd)}`,\n ` custom rate ${p.customRate ? formatRateAllUnits(p.customRate.rateUsd) : pc.dim('none (costs report at the platform rate)')}`,\n ];\n if (p.key.status === 'error' && p.key.statusDetail) lines.push(` last error ${pc.dim(safeTerm(p.key.statusDetail))}`);\n return lines.join('\\n');\n}\n\nexport function formatByokVerify(r: ByokKeyResponse): string {\n const head = r.verified === true ? pc.green('verified') : pc.red('not verified');\n const detail = r.key.statusDetail ? pc.dim(` ${safeTerm(r.key.statusDetail)}`) : '';\n const act = r.key.actCapable ? pc.green(' act-capable') : '';\n return `${head} ${safeTerm(r.key.provider)}${act}${detail}`;\n}\n\n/** `<usd>` and `--per` as the rate route takes them; refuses what the server would. */\nexport function parseRateArgs(usd: string, per: string | undefined): { usd: number; per: RatePer } {\n const amount = Number(usd);\n if (usd.trim() === '' || !Number.isFinite(amount) || amount < 0 || amount > MAX_RATE_USD) {\n throw new Error(`<usd> must be a number from 0 to ${MAX_RATE_USD}`);\n }\n const unit = (per ?? 'hour') as RatePer;\n if (!RATE_UNITS.includes(unit)) throw new Error('--per must be second, minute or hour');\n return { usd: amount, per: unit };\n}\n\n/** The `PUT …/key` body from `--key` or `--field name=value`. */\nexport function keyBody(opts: { key?: string; field?: string[] }): Record<string, unknown> {\n if (opts.field !== undefined) {\n if (opts.key !== undefined) throw new Error('Pass either --key or --field, not both.');\n return { fields: parseInputs(opts.field) };\n }\n if (opts.key !== undefined) return { key: opts.key };\n throw new Error('Pass --key <key> or --field name=value.');\n}\n\nexport function registerByokCommands(program: Command): void {\n const byok = program\n .command('byok')\n .description(\"The org's BYOK providers: their keys and custom rates, shared by Actions and sandboxes\")\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 const list = async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<{ providers: ByokProvider[] }>('/api/v1/providers');\n output(opts, data, (d) => {\n for (const p of d.providers) console.log(formatByokRow(p));\n });\n } catch (e) {\n fail(e, opts);\n }\n };\n common(byok).action(list);\n common(byok.command('list').alias('ls').description('Every provider the org may bring a key for, with key state and rate')).action(list);\n\n common(\n byok\n .command('show')\n .description(\"One provider's key state, platform rate and custom rate\")\n .argument('<provider>', 'provider id (e.g. tensorlake, blaxel)'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<{ provider: ByokProvider }>(providerPath(provider));\n output(opts, data, (d) => console.log(formatByokDetail(d.provider)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n byok\n .command('configure')\n .description(\"Save the org's key for a provider; untested until verified (owner/admin)\")\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', 'test the key with a real sandbox after saving'),\n ).action(async (provider: string, opts: CommonOpts & { key?: string; field?: string[]; verify?: boolean }) => {\n try {\n // A provider key is a local secret: trusted hosts only, even with --allow-untrusted-host.\n const c = await secretValueClient(opts, 'provider keys');\n const saved = await c.put<ByokKeyResponse>(providerPath(provider, '/key'), keyBody(opts));\n const verification = opts.verify ? await c.post<ByokKeyResponse>(providerPath(provider, '/verify')) : undefined;\n output(opts, verification ? { key: saved.key, verification } : saved, () => {\n console.log(`saved ${safeTerm(saved.key.provider)} ${pc.dim(safeTerm(saved.key.keyHint ?? ''))} ${safeTerm(saved.key.status)}`);\n if (verification) console.log(formatByokVerify(verification));\n });\n if (verification?.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n byok\n .command('verify')\n .description('Test the stored key by placing a real sandbox with it (\"Test\" in Settings; owner/admin)')\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<ByokKeyResponse>(providerPath(provider, '/verify'));\n output(opts, result, (r) => console.log(formatByokVerify(r)));\n if (result.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n byok\n .command('remove')\n .alias('rm')\n .description(\"Delete the org's stored key for a provider; nothing places on it until a new key passes (owner/admin)\")\n .argument('<provider>', 'provider id')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (provider: string, opts: CommonOpts & { yes?: boolean }) => {\n try {\n await confirmWrite(`Remove the ${provider} key? Sandboxes and Actions jobs stop placing on ${provider}.`, opts);\n const result = await (await client(opts)).del<{ provider: string; deleted: boolean }>(providerPath(provider, '/key'));\n output(opts, result, (r) => console.log(`deleted ${safeTerm(r.provider)}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const rate = byok\n .command('rate')\n .description('Custom rates: report sandbox costs at your own price. Reporting only; billing is unchanged');\n\n common(\n rate\n .command('set')\n .description(\"Report a provider's sandbox costs at your own rate, e.g. what you pay it (owner/admin). Doesn't change what you're billed\")\n .argument('<provider>', 'provider id')\n .argument('<usd>', 'the rate in USD')\n .option('--per <unit>', 'second, minute or hour', 'hour'),\n ).action(async (provider: string, usd: string, opts: CommonOpts & { per?: string }) => {\n try {\n const body = parseRateArgs(usd, opts.per);\n const data = await (await client(opts)).put<{ provider: ByokProvider }>(providerPath(provider, '/rate'), body);\n output(opts, data, (d) => {\n console.log(`${safeTerm(d.provider.provider)} costs now report at ${formatRateAllUnits(d.provider.rate.rateUsd)}`);\n console.log(pc.dim('Reporting only: billing is unchanged. Applies to sandboxes created from now on.'));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n rate\n .command('clear')\n .description(\"Drop a provider's custom rate; its costs report at the platform rate again (owner/admin)\")\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).del<{ provider: ByokProvider }>(providerPath(provider, '/rate'));\n output(opts, data, (d) =>\n console.log(`${safeTerm(d.provider.provider)} costs now report at the platform rate, ${formatRateAllUnits(d.provider.platformRate.rateUsd)}`),\n );\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * Shared display helpers for money and rates.\n *\n * Every human-readable rate the CLI prints shows all three units — per hour\n * first — as `$0.1008/hr · $0.00168/min · $0.000028/s`. Amounts print with up\n * to 4 significant decimals, never scientific notation, trailing zeros\n * trimmed.\n */\n\nexport type RatePer = 'second' | 'minute' | 'hour';\n\n/** A rate in the API's input shape: an amount plus the unit it's priced per. */\nexport interface UsdPer {\n usd: number;\n per: string;\n}\n\n/** The same rate normalized to all three units — the API's `rateUsd` shape. */\nexport interface RateAllUnits {\n perSecond: number;\n perMinute: number;\n perHour: number;\n}\n\nconst SECONDS_PER_MINUTE = 60;\nconst SECONDS_PER_HOUR = 3600;\n\n/** `{usd, per}` → `{perSecond, perMinute, perHour}`. */\nexport function rateAllUnits(rate: UsdPer): RateAllUnits {\n const perSecond =\n rate.per === 'second'\n ? rate.usd\n : rate.per === 'minute'\n ? rate.usd / SECONDS_PER_MINUTE\n : rate.usd / SECONDS_PER_HOUR;\n return {\n perSecond,\n perMinute: perSecond * SECONDS_PER_MINUTE,\n perHour: perSecond * SECONDS_PER_HOUR,\n };\n}\n\n/**\n * `$0.1008`, `$14.12`, `$3600`, `$0.000028` — up to 4 significant decimals,\n * trailing zeros trimmed, never scientific notation.\n */\nexport function formatUsd(usd: number): string {\n if (!Number.isFinite(usd)) return '$—';\n if (usd === 0) return '$0';\n // Decimals needed for 4 significant digits; Math.log10(1e-9) = -9 still\n // lands on a plain toFixed call, so tiny per-second values never go\n // exponential.\n // toFixed accepts at most 100 decimals; a rate smaller than 1e-100 would\n // ask for more, so cap it (the string rounds to $0 rather than throwing).\n const decimals = Math.min(100, Math.max(0, 3 - Math.floor(Math.log10(Math.abs(usd)))));\n const fixed = usd.toFixed(decimals);\n // Trailing zeros only count after a decimal point — \"3600\" stays \"3600\".\n const trimmed = fixed.includes('.') ? fixed.replace(/0+$/, '').replace(/\\.$/, '') : fixed;\n return `$${trimmed}`;\n}\n\n/**\n * `$1,234.56`, `$20.00`, `$0.10` — money *amounts* (balances, costs, holds,\n * credits, settlements): always 2 decimals with thousands separators.\n * Non-zero amounts under $0.01 keep up to 4 significant digits (`$0.0042`),\n * negatives render `-$0.50`. Rates use `formatUsd`, not this.\n */\nexport function formatMoney(usd: number): string {\n if (!Number.isFinite(usd)) return '$—';\n const sign = usd < 0 ? '-' : '';\n const abs = Math.abs(usd);\n if (abs !== 0 && abs < 0.01) {\n return `${sign}${formatUsd(abs)}`;\n }\n const s = abs.toLocaleString('en-US', {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n });\n return `${sign}$${s}`;\n}\n\n/** `$0.1008/hr · $0.00168/min · $0.000028/s` — per hour first. */\nexport function formatRateAllUnits(rate: RateAllUnits): string {\n return `${formatUsd(rate.perHour)}/hr · ${formatUsd(rate.perMinute)}/min · ${formatUsd(rate.perSecond)}/s`;\n}\n\n/** Convenience for a `{usd, per}` straight off the wire. */\nexport function formatUsdPer(rate: UsdPer): string {\n return formatRateAllUnits(rateAllUnits(rate));\n}\n","/**\n * `compute market` — both sides of the compute market. Sellers post listings,\n * reprice/pause/resume/withdraw them, and read payouts; buyers set the org\n * market cap, post standing bids, and manage prepaid credits. Everyone reads\n * the book.\n *\n * Auth: identical to `compute actions` — --api-key / COMPUTE_API_KEY / the\n * stored `compute login` (or `compute bench auth login`) session. Seller\n * commands need an org the platform flags `market_provider`; buyer commands\n * need a `market` buyer lane. 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';\nimport { formatMoney, formatUsdPer } from './rate-display.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/** `describeBid` — one row of GET /api/v1/market/bids. */\nexport interface MarketBid {\n id: string;\n size: string;\n region: string | null;\n useCase?: 'actions' | 'sandbox';\n maxUsd: number;\n per: MarketRatePer;\n status: 'open' | 'filled' | 'cancelled';\n createdAt: string;\n expiresAt: string | null;\n}\n\n/** `describeCap` — the org market cap, or null when none is set. */\nexport interface MarketCap {\n usd: number;\n per: MarketRatePer;\n}\n\n/** GET /api/v1/billing/balance. */\nexport interface MarketCreditBalance {\n balanceMicroUsd: number;\n heldMicroUsd: number;\n holds: { id: string; microUsd: number; runId: string | null; jobId: string | null; createdAt: string }[];\n}\n\n/** `describeLedgerEntry` — one row of GET /api/v1/billing/ledger. */\nexport interface MarketLedgerEntry {\n id: string;\n kind: string;\n label: string;\n microUsd: number;\n runId: string | null;\n jobId: string | null;\n createdAt: string;\n}\n\n/** `describePurchase` — one row of GET /api/v1/market/purchases. */\nexport interface MarketPurchase {\n id: string;\n provider: string;\n sellerName: string;\n size: string;\n region: string | null;\n useCase: string;\n usd: number;\n per: MarketRatePer;\n status: 'live' | 'closed' | 'replaced';\n startedAt: string;\n endedAt: string | null;\n secondsBilled: number | null;\n /** Null while the fill is still running. */\n costMicroUsd: number | null;\n runId: string | null;\n jobId: string | null;\n sandboxId: string | null;\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/** How a listing (or offer, or sale) is priced — all three units, per hour first. */\nexport function formatRate(usd: number, per: MarketRatePer): string {\n return formatUsdPer({ 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 = formatMoney(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 ${formatMoney(s.grossUsd)}`,\n `net ${formatMoney(s.netUsd)}`,\n paid,\n ].join(' ');\n}\n\nconst MICRO_USD = 1_000_000;\n\n/**\n * The `POST /api/v1/market/bids` body for `bid`: `{size, region?, maxUsd,\n * per, expiresInHours?, useCase}`. Same `--price <usd>/<unit>` rule as\n * `sell` — the unit is never implied.\n */\nexport function bidBody(opts: {\n size: string;\n price: string;\n per?: string;\n region?: string;\n expiresIn?: string;\n useCase?: string;\n}): Record<string, unknown> {\n const rate = parseRate(opts.price, opts.per);\n const expiresInHours = parseExpiresIn(opts.expiresIn);\n return {\n size: opts.size,\n ...(opts.region !== undefined && { region: opts.region }),\n maxUsd: rate.usd,\n per: rate.per,\n ...(expiresInHours !== undefined && { expiresInHours }),\n useCase: parseMarketLane(opts.useCase),\n };\n}\n\n/** `topup <usd>` → `amountUsd`: a positive dollar amount. */\nexport function parseTopupAmount(value: string): number {\n const usd = Number(value.replace(/^\\$/, ''));\n if (!USD_RE.test(value.replace(/^\\$/, '')) || !Number.isFinite(usd) || usd <= 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Invalid amount \"${value}\". Expected a positive dollar amount (e.g. 50).`,\n );\n }\n return usd;\n}\n\nexport function formatCap(cap: MarketCap | null): string {\n return cap === null\n ? 'No market cap — market-placed jobs need their own bid to fill.'\n : `market cap ${formatRate(cap.usd, cap.per)}`;\n}\n\nexport function formatBidRow(bid: MarketBid): string {\n const status =\n bid.status === 'open'\n ? pc.green('open')\n : bid.status === 'filled'\n ? pc.cyan('filled')\n : pc.gray('cancelled');\n return [\n bid.id,\n status,\n pc.dim(bid.useCase === 'sandbox' ? 'sandbox' : 'actions'),\n safeTerm(bid.size),\n safeTerm(bid.region ?? 'any region'),\n `≤ ${formatRate(bid.maxUsd, bid.per)}`,\n pc.dim(bid.expiresAt ? `expires ${bid.expiresAt}` : 'standing'),\n ].join(' ');\n}\n\nexport function formatCredits(b: MarketCreditBalance): string {\n const lines = [`available ${formatMoney(b.balanceMicroUsd / MICRO_USD)}`];\n if (b.holds.length > 0) {\n lines.push(\n pc.dim(`reserved ${formatMoney(b.heldMicroUsd / MICRO_USD)} across ${b.holds.length} running sandbox${b.holds.length === 1 ? '' : 'es'} or job${b.holds.length === 1 ? '' : 's'}`),\n );\n }\n return lines.join('\\n');\n}\n\nexport function formatLedgerRow(e: MarketLedgerEntry): string {\n const usd = e.microUsd / MICRO_USD;\n const amount = usd < 0 ? `-${formatMoney(-usd)}` : `+${formatMoney(usd)}`;\n return [\n pc.dim(e.createdAt.slice(0, 19).replace('T', ' ')),\n (usd < 0 ? pc.red : pc.green)(amount.padStart(10)),\n safeTerm(e.label),\n pc.dim(e.jobId ? `job ${e.jobId}` : ''),\n ].join(' ').trimEnd();\n}\n\nexport function formatPurchaseRow(p: MarketPurchase): string {\n const cost =\n p.costMicroUsd !== null\n ? formatMoney(p.costMicroUsd / MICRO_USD)\n : p.status === 'live'\n ? pc.yellow('running')\n : '-';\n return [\n pc.dim(p.startedAt.slice(0, 19).replace('T', ' ')),\n cost.padStart(10),\n pc.cyan(safeTerm(p.sellerName)),\n pc.dim(`${safeTerm(p.provider)}/${safeTerm(p.region ?? 'any')}`),\n formatRate(p.usd, p.per),\n p.secondsBilled !== null ? pc.dim(`${p.secondsBilled}s`) : '',\n p.status === 'replaced' ? pc.yellow('replaced') : '',\n pc.dim(p.runId ? `run ${p.runId}` : p.sandboxId ? `sandbox ${p.sandboxId}` : ''),\n ]\n .filter((part) => part !== '')\n .join(' ');\n}\n\n// ─── Commands ───────────────────────────────────────────────────────────────\n\nexport function registerMarketCommands(program: Command): void {\n // Not generally available: registered for the orgs that use it, kept out\n // of `compute --help`.\n const market = program\n .command('market', { hidden: true })\n .description('Buy and 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 // ── Buyer side ──────────────────────────────────────────────────────────\n\n const cap = market\n .command('cap')\n .description('The org market cap: the most a market-placed job pays without its own bid');\n\n common(cap.command('show', { isDefault: true }).description('Show the current cap')).action(\n async (opts: CommonOpts) => {\n try {\n const { marketCap } = await (await client(opts)).get<{ marketCap: MarketCap | null }>(\n '/api/v1/market/bids',\n );\n output(opts, marketCap, (c) => console.log(formatCap(c)));\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n common(\n cap\n .command('set')\n .description('Set the cap')\n .requiredOption('--price <usd/unit>', 'max price per unit of time (e.g. 0.40/hour)')\n .option('--per <unit>', 'unit for a bare --price usd (second, minute, or hour)'),\n ).action(async (opts: CommonOpts & { price: string; per?: string }) => {\n try {\n const rate = parseRate(opts.price, opts.per);\n const { marketCap } = await (await client(opts)).post<{ marketCap: MarketCap | null }>(\n '/api/v1/market/bids',\n { marketCap: rate },\n );\n output(opts, marketCap, (c) => console.log(formatCap(c)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n cap\n .command('clear')\n .description('Remove the cap (refused while your placement order still names market)'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { marketCap } = await (await client(opts)).post<{ marketCap: MarketCap | null }>(\n '/api/v1/market/bids',\n { marketCap: null },\n );\n output(opts, marketCap, (c) => console.log(formatCap(c)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('bids')\n .description(\"Your org's standing bids — open, filled, and cancelled\"),\n ).action(async (opts: CommonOpts) => {\n try {\n const { bids } = await (await client(opts)).get<{ bids: MarketBid[] }>(\n '/api/v1/market/bids',\n );\n output(opts, bids, (rows) => {\n if (rows.length === 0) {\n console.log('No bids yet — post one with `compute market bid`.');\n return;\n }\n for (const bid of rows) console.log(formatBidRow(bid));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('bid')\n .description('Post a standing bid: the most you will pay for a size tier')\n .requiredOption('--size <tier>', 'size tier to buy (e.g. xlarge)')\n .requiredOption('--price <usd/unit>', 'max price per unit of time (e.g. 0.40/hour)')\n .option('--per <unit>', 'unit for a bare --price usd (second, minute, or hour)')\n .option('--region <region>', 'only fill in this region (default: any)')\n .option('--use-case <lane>', 'lane to buy on: actions or sandbox (default: actions)')\n .option('--expires-in <hours>', 'cancel after this many hours (default: standing)'),\n ).action(async (opts: CommonOpts & { size: string; price: string; per?: string; region?: string; useCase?: string; expiresIn?: string }) => {\n try {\n const result = await (await client(opts)).post<{ bid: MarketBid }>(\n '/api/v1/market/bids',\n bidBody(opts),\n );\n output(opts, result, (r) => {\n console.log(`bid placed ${pc.cyan(r.bid.id)}`);\n console.log(formatBidRow(r.bid));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('cancel-bid')\n .description('Cancel an open standing bid')\n .argument('<bid-id>', 'bid ID'),\n ).action(async (bidId: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ bid: MarketBid }>(\n `/api/v1/market/bids?id=${encodeURIComponent(bidId)}`,\n );\n output(opts, result, (r) => console.log(`cancelled ${pc.cyan(r.bid.id)}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('purchases')\n .description('What the market ran for you: seller, price, duration, and cost, newest first')\n .option('--limit <n>', 'purchases per page (max 200, default 50)')\n .option('--cursor <cursor>', 'continue from a previous page'),\n ).action(async (opts: CommonOpts & { limit?: string; cursor?: string }) => {\n try {\n const page = await (await client(opts)).get<{\n purchases: MarketPurchase[];\n nextCursor: string | null;\n }>('/api/v1/market/purchases', { limit: opts.limit, cursor: opts.cursor });\n output(opts, page, (p) => {\n if (p.purchases.length === 0) {\n console.log('No market purchases yet.');\n return;\n }\n for (const row of p.purchases) console.log(formatPurchaseRow(row));\n if (p.nextCursor) console.log(pc.dim(`more: --cursor ${p.nextCursor}`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('credits')\n .description('Prepaid market credits: available balance and reserved holds'),\n ).action(async (opts: CommonOpts) => {\n try {\n const balance = await (await client(opts)).get<MarketCreditBalance>(\n '/api/v1/billing/balance',\n );\n output(opts, balance, (b) => console.log(formatCredits(b)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('ledger')\n .description('Credit history, newest first: top-ups, charges, holds, refunds')\n .option('--limit <n>', 'entries per page (max 200, default 50)')\n .option('--cursor <cursor>', 'continue from a previous page'),\n ).action(async (opts: CommonOpts & { limit?: string; cursor?: string }) => {\n try {\n const page = await (await client(opts)).get<{\n entries: MarketLedgerEntry[];\n nextCursor: string | null;\n }>('/api/v1/billing/ledger', { limit: opts.limit, cursor: opts.cursor });\n output(opts, page, (p) => {\n if (p.entries.length === 0) {\n console.log('No credit activity yet — add credit with `compute credits topup <usd>`.');\n return;\n }\n for (const entry of p.entries) console.log(formatLedgerRow(entry));\n if (p.nextCursor) console.log(pc.dim(`more: --cursor ${p.nextCursor}`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('topup')\n .description('Buy prepaid credits — prints a Stripe checkout link to pay in your browser')\n .argument('<usd>', 'amount in USD (e.g. 50)'),\n ).action(async (amount: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<{ url: string; amountMicroUsd: number }>(\n '/api/v1/billing/topups',\n { amountUsd: parseTopupAmount(amount) },\n );\n output(opts, result, (r) => {\n console.log(`Pay ${formatMoney(r.amountMicroUsd / MICRO_USD)} at:`);\n console.log(r.url);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n // ── Seller credential ───────────────────────────────────────────────────\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 credits` — the org's prepaid credit, which managed accounts bill\n * from: balance, ledger and top-ups over `/api/v1/billing/*`. These lived\n * under `compute market`; credit is every org's now, so they have their own\n * top-level home (`compute market credits|ledger|topup` stay, hidden).\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { client, fail, output, usageErrorOutput, type CommonOpts } from './actions.js';\nimport {\n formatCredits,\n formatLedgerRow,\n parseTopupAmount,\n type MarketCreditBalance,\n type MarketLedgerEntry,\n} from './market.js';\nimport { formatMoney } from './rate-display.js';\n\nconst MICRO_USD = 1_000_000;\n\n/** POST /api/v1/billing/topups. `creditMicroUsd`/`feeBps` arrive from platforms with the top-up fee. */\ninterface TopupCheckout {\n url: string | null;\n amountMicroUsd: number;\n creditMicroUsd?: number;\n feeBps?: number;\n}\n\nexport function registerCreditsCommands(program: Command): void {\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 const credits = common(\n program\n .command('credits')\n .description('Your prepaid credit — managed accounts bill from it: balance, ledger, top-ups')\n .configureOutput({ outputError: usageErrorOutput }),\n ).action(async (opts: CommonOpts) => {\n try {\n const balance = await (await client(opts)).get<MarketCreditBalance>('/api/v1/billing/balance');\n output(opts, balance, (b) => console.log(formatCredits(b)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n credits\n .command('ledger')\n .description('Credit history, newest first: top-ups, grants, holds, charges, refunds')\n .option('--limit <n>', 'entries per page (max 200, default 50)')\n .option('--cursor <cursor>', 'continue from a previous page'),\n ).action(async (opts: CommonOpts & { limit?: string; cursor?: string }) => {\n try {\n const page = await (await client(opts)).get<{ entries: MarketLedgerEntry[]; nextCursor: string | null }>(\n '/api/v1/billing/ledger',\n { limit: opts.limit, cursor: opts.cursor },\n );\n output(opts, page, (p) => {\n if (p.entries.length === 0) {\n console.log('No credit activity yet — add credit with `compute credits topup <usd>`.');\n return;\n }\n for (const entry of p.entries) console.log(formatLedgerRow(entry));\n if (p.nextCursor) console.log(pc.dim(`more: --cursor ${p.nextCursor}`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n credits\n .command('topup')\n .description('Add credit — prints a Stripe checkout link to pay in your browser (owner/admin)')\n .argument('<usd>', 'amount to pay in USD (e.g. 50)'),\n ).action(async (amount: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<TopupCheckout>('/api/v1/billing/topups', {\n amountUsd: parseTopupAmount(amount),\n });\n output(opts, result, (r) => {\n const pay = formatMoney(r.amountMicroUsd / MICRO_USD);\n if (r.creditMicroUsd !== undefined && r.feeBps !== undefined && r.feeBps > 0) {\n console.log(`Pay ${pay} for ${formatMoney(r.creditMicroUsd / MICRO_USD)} of credit (${r.feeBps / 100}% top-up fee) at:`);\n } else {\n console.log(`Pay ${pay} at:`);\n }\n console.log(r.url ?? pc.dim('(no checkout link returned)'));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * Flags given to a parent command reach its subcommand.\n *\n * Several groups declare the shared flags (--org, --api-key, --base-url,\n * --json, …) on the parent as well as on each subcommand, so\n * `compute credits --org team-b topup 50` parses: but commander stores\n * `--org` on `credits`, and `topup`'s action only reads its own options —\n * the checkout would go to the active org instead of team-b. This hook, on\n * the root program, runs before every action and copies each option a parent\n * received (on the command line or from env) onto the subcommand that\n * declares the same option and didn't get it itself. The subcommand's own\n * value always wins, and the nearest parent wins over farther ones.\n */\n\nimport type { Command } from 'commander';\n\nconst GIVEN = new Set(['cli', 'env']);\n\nexport function inheritParentOptions(program: Command): Command {\n return program.hook('preAction', (_hooked, actionCommand) => {\n const declared = new Set(actionCommand.options.map((option) => option.attributeName()));\n for (let parent = actionCommand.parent; parent; parent = parent.parent) {\n for (const [key, value] of Object.entries(parent.opts())) {\n if (!declared.has(key) || value === undefined) continue;\n if (!GIVEN.has(parent.getOptionValueSource(key) ?? '')) continue;\n if (GIVEN.has(actionCommand.getOptionValueSource(key) ?? '')) continue;\n actionCommand.setOptionValueWithSource(key, value, parent.getOptionValueSource(key)!);\n }\n }\n });\n}\n","/**\n * `compute instances` (alias `compute sandboxes`) — drive instances 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 * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as readline from 'node:readline';\nimport { Readable } from 'node:stream';\nimport { Command, Option } from 'commander';\nimport pc from 'picocolors';\nimport * as tar from 'tar';\nimport { ActionsApiError, 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';\nimport {\n clearCurrentInstance,\n dirKey,\n isUuid,\n orgKey,\n readFileCurrent,\n resolveInstanceId,\n setCurrentInstance,\n shortId,\n} from './current-instance.js';\nimport { formatMoney, formatRateAllUnits, formatUsd, formatUsdPer, rateAllUnits } from './rate-display.js';\nimport { parseMaxPrice, registerSettingsCommands } from './settings.js';\nimport { registerBillingCommands } from './sandbox-billing.js';\nimport { syncOnce, sourceFilter, type SyncPlan } from './sync.js';\nimport { localTree } from './sync-fs.js';\nimport { creationClient } from './onboarding.js';\nimport { execute, execCommand, execTimeout, type ExecOpts } from './exec.js';\n\n// ─── Wire types (mirror benchmarks-platform lib/sandboxes) ──────────────────\n// The definitions moved to @computesdk/platform in cli 2.x — re-exported here\n// for one release so the CLI's public names don't change.\nexport type {\n CommandResult,\n FileEntry,\n PathView,\n SandboxCost,\n SandboxDetail,\n SandboxProcess,\n SandboxProcessStatus,\n SandboxSnapshot,\n SandboxSummary,\n} from '@computesdk/platform';\nimport type {\n PathView,\n SandboxDetail,\n SandboxProcess,\n SandboxProcessStatus,\n SandboxSnapshot,\n SandboxSummary,\n} from '@computesdk/platform';\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\n/** `$0.12/h` — the compact one-unit rate the instance line shows. */\nfunction shortRate(rate: { usd: number; per: string }): string {\n return `${formatUsd(rateAllUnits(rate).perHour)}/h`;\n}\n\n/**\n * Who the sandbox runs under: a ComputeSDK managed account (billed from\n * prepaid credit) or the org's own BYOK key (billed by the provider).\n */\nexport function placementLane(source: string | undefined): string {\n if (source === 'house') return 'managed';\n if (source === 'own-key') return 'BYOK';\n return source ?? '—';\n}\n\n/** Where a placement's compute is billed. */\nfunction billedBy(source: string | undefined, provider: string): string {\n if (source === 'house') return 'billed from your ComputeSDK credit';\n if (source === 'own-key') return `billed by ${provider} to your account`;\n return 'billed from your ComputeSDK credit';\n}\n\n/** `2026-10-27 14:02` — a timestamp in the viewer's local time. */\nfunction formatLocalTime(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n const p = (n: number) => String(n).padStart(2, '0');\n return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;\n}\n\n/**\n * The default instance view: one line of ID, status, provider, size and\n * rate, plus a label line when one is set. `--verbose` adds everything the\n * old output printed (providerSandboxId, image, full placement, command\n * count, attach). `attach` never leaves `--json`.\n */\nfunction printSandbox(s: SandboxSummary, verbose = false): void {\n const p = s.placement;\n console.log(\n `${pc.cyan(s.id)} ${s.status} ${p?.box?.provider ?? s.provider ?? '—'} · ${placementLane(p?.source)} ${p?.size ?? '—'} ${p ? shortRate(p.rate) : '—'}`,\n );\n if (s.label) {\n console.log(` label: ${s.label} created: ${formatLocalTime(s.createdAt)}`);\n }\n if (s.destroyError) console.log(` destroyError: ${pc.red(s.destroyError)}`);\n if (!verbose) return;\n console.log(` providerSandboxId: ${s.providerSandboxId ?? '—'} commands: ${s.commandCount}`);\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 (p) {\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 const provider = p.box?.provider ?? s.provider ?? 'the provider';\n console.log(\n ` placement: ${placementLane(p.source)}${box} rate: ${formatUsdPer(p.rate)} ${pc.dim(billedBy(p.source, provider))}`,\n );\n }\n const attach = 'attach' in s ? (s as SandboxDetail).attach : undefined;\n if (attach !== undefined) {\n console.log(\n attach === null\n ? ' attach: none (managed account or platform provider — drive it through ComputeSDK)'\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: 'house' | 'own-key' | 'market';\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\n\nconst usdAmount = (n: number | undefined): string => (n === undefined ? '—' : formatMoney(n));\n\n/** A walk entry as people read it: `daytona (managed)`, `e2b (BYOK)`. */\nfunction walkEntry(entry: string): string {\n if (entry.startsWith('managed/')) return `${entry.slice('managed/'.length)} (managed)`;\n if (entry === 'market' || entry.startsWith('market:')) return entry;\n return `${entry} (BYOK)`;\n}\n\n/** Why a quote can't place, in the caller's terms. */\nfunction quoteRefusal(q: SandboxQuoteWire): string {\n switch (q.reason) {\n case 'insufficient_credits':\n return `not enough ComputeSDK credit for the hold (need ${usdAmount(q.requiredHoldUsd)}, have ${usdAmount(q.creditBalanceUsd)})`;\n case 'no_provider_configured':\n return 'nothing in the router can place this size: no live managed account prices it, and no BYOK key covers it';\n default:\n return q.reason ?? 'nothing in the router can place it';\n }\n}\n\n/**\n * Where a create would land and what it would cost: the provider and whether\n * it's a managed account (billed from credit, with a hold) or your BYOK key\n * (billed by the provider), the rate, and the router's walk.\n */\nfunction printQuote(q: SandboxQuoteWire, timeoutMs?: string): void {\n const row = (label: string, value: string) => console.log(`${label.padEnd(10)} ${value}`);\n if (!q.ok || !q.placement) {\n row('Lands on', pc.red(`nowhere — ${quoteRefusal(q)}`));\n if (q.reason === 'insufficient_credits' && q.topUpPath) row('Top up', q.topUpPath);\n } else {\n const p = q.placement;\n const provider = p.box?.provider ?? p.provider;\n row('Lands on', `${provider} · ${placementLane(p.source)} · ${p.size ?? p.box?.sizeName ?? 'custom size'}`);\n row('Rate', q.rateUsd ? formatRateAllUnits(q.rateUsd) : q.rate ? formatUsdPer(q.rate) : '—');\n if (p.source === 'own-key') {\n row('Billing', `billed by ${provider} to your account`);\n } else if (q.requiredHoldUsd !== undefined) {\n const timeout = timeoutMs !== undefined ? ` for ${timeoutMs}ms` : ' for the timeout';\n row('Billing', `from your ComputeSDK credit: ${usdAmount(q.requiredHoldUsd)} held${timeout}, settled at actual runtime (balance ${usdAmount(q.creditBalanceUsd)})`);\n } else {\n // No hold quoted: the estimate is just that.\n row('Billing', `from your ComputeSDK credit (balance ${usdAmount(q.creditBalanceUsd)})`);\n if (q.estimatedCostUsd !== undefined) row('Estimate', usdAmount(q.estimatedCostUsd));\n }\n }\n row('Tries', q.providerOrder.map(walkEntry).join(' → ') || '—');\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 COMMAND_LEAD_OPTS: LeadOptSpec[] = [\n ...AUTH_LEAD_OPTS,\n { aliases: ['--cwd'], key: 'cwd', flag: 'value' },\n { aliases: ['-e', '--env'], key: 'env', flag: 'repeat' },\n { aliases: ['--timeout-ms'], key: 'timeoutMs', flag: 'value' },\n];\n\nconst EXEC_LEAD_OPTS: LeadOptSpec[] = [\n ...COMMAND_LEAD_OPTS,\n { aliases: ['--timeout'], key: 'timeout', flag: 'value' },\n { aliases: ['--stream'], key: 'stream', flag: 'bool' },\n { aliases: ['-d', '--detach'], key: 'detach', flag: 'bool' },\n];\n\nconst SPAWN_LEAD_OPTS: LeadOptSpec[] = [\n ...AUTH_LEAD_OPTS,\n { aliases: ['-q', '--quiet'], key: 'quiet', flag: 'bool' },\n { aliases: ['--cwd'], key: 'cwd', flag: 'value' },\n { aliases: ['-e', '--env'], key: 'env', flag: 'repeat' },\n { aliases: ['--stdin'], key: 'stdin', flag: 'bool' },\n];\n\nconst SERVE_LEAD_OPTS: LeadOptSpec[] = [\n ...SPAWN_LEAD_OPTS,\n { aliases: ['--port'], key: 'port', flag: 'value' },\n { aliases: ['--timeout-ms'], key: 'timeoutMs', flag: 'value' },\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\n// ─── Output modes and current-instance resolution ────────────────────────────\n\ntype QuietOpts = CommonOpts & { quiet?: boolean; verbose?: boolean; browser?: boolean };\n\n/** `--quiet` and `--json` together is a usage error. */\nfunction checkQuietJson(opts: QuietOpts): void {\n if (opts.quiet && opts.json) throw new Error('--quiet and --json cannot be combined');\n}\n\n/** --quiet prints only `quietLine(data)`; otherwise the --json/human path. */\nfunction emitResult<T>(\n opts: QuietOpts,\n data: T,\n quietLine: (d: T) => string,\n render: (d: T) => void,\n): void {\n if (opts.quiet) {\n console.log(quietLine(data));\n return;\n }\n output(opts, data, render);\n}\n\nconst NO_INSTANCE_HINT =\n 'No sandbox selected. Run `compute new`, pass an ID, or run `compute use <id>`.';\n\ninterface ResolvedSandbox {\n id: string;\n /** Clears the stored pick when the API proves it stale (404), and says so. */\n clearStale: (error: unknown) => void;\n}\n\n/**\n * Resolves the instance a command runs on: explicit UUID > COMPUTE_INSTANCE >\n * this directory's stored pick. When the pick was implicit a dim line names\n * it on stderr so a human sees which box the command hit (silent in\n * --json/--quiet so scripts stay clean).\n */\nfunction resolveSandbox(argId: string | undefined, opts: QuietOpts): ResolvedSandbox {\n const r = resolveInstanceId(argId, opts);\n if (!r) throw new Error(NO_INSTANCE_HINT);\n if (r.source !== 'argument' && !opts.json && !opts.quiet) {\n console.error(\n pc.dim(\n `instance ${shortId(r.id)} (${r.source === 'env' ? 'COMPUTE_INSTANCE' : `current for ${r.dir}`})`,\n ),\n );\n }\n const org = orgKey(opts);\n return {\n id: r.id,\n clearStale: (error) => {\n if (\n r.source === 'file' &&\n error instanceof ActionsApiError &&\n error.status === 404 &&\n readFileCurrent(org) === r.id\n ) {\n clearCurrentInstance(org);\n console.error(pc.dim(`cleared stale current instance ${shortId(r.id)}`));\n }\n },\n };\n}\n\n/** The positional-id rule: only a UUID may occupy the `[sandboxId]` slot. */\nfunction requireUuidOrImplicit(argId: string | undefined, opts: QuietOpts): ResolvedSandbox {\n if (argId !== undefined && !isUuid(argId)) {\n throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n }\n return resolveSandbox(argId, opts);\n}\n\n/**\n * `[resourceOrSandboxId] [resourceId]` commands (logs/wait/kill/stdin/\n * close-stdin/snapshot-delete): one positional is the resource on the\n * implicit instance — UUID-shaped or not; two positionals are always\n * `<sandboxId> <resourceId>`.\n */\nfunction resolveTwoArgTarget(\n argId: string | undefined,\n resourceId: string | undefined,\n opts: QuietOpts,\n label: string,\n): { resolved: ResolvedSandbox; resource: string } {\n if (resourceId === undefined) {\n if (argId === undefined) throw new Error(`missing ${label}`);\n return { resolved: resolveSandbox(undefined, opts), resource: argId };\n }\n if (argId !== undefined && !isUuid(argId)) {\n throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n }\n return { resolved: resolveSandbox(argId, opts), resource: resourceId };\n}\n\n// ─── create/run shared flags ─────────────────────────────────────────────────\n\n/** The create options `create` and `run` share — declared once. */\nfunction addCreateFlags(c: Command): Command {\n return c\n .option('--provider <names>', 'place only on these providers, through your router (its BYOK mode and order), e.g. daytona or daytona,e2b')\n .option('--byok', 'use only your own keys for this create')\n .option('--managed', 'use only ComputeSDK managed accounts for this create')\n // Pre-router: walk exactly these BYOK providers. --provider + --byok covers it.\n .addOption(new Option('--order <providers>').hideHelp())\n .option('--size <size>', 'platform size: small (1 vCPU/2 GiB), medium, large, xlarge, 2xlarge (16/32 GiB), 3xlarge (32/64 GiB); 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 .addOption(new Option('--max-price <usd/unit>').hideHelp())\n .addOption(new Option('--max-price-per <unit>').hideHelp())\n .addOption(new Option('--market').hideHelp())\n .addOption(new Option('--order-type <type>').hideHelp())\n .option('--timeout-ms <ms>', 'sandbox timeout in ms (provider minimums apply, e.g. blaxel ≥5m)')\n .option('--secret <name>', 'vault secret name to inject (repeatable)', (v, a: string[]) => a.concat(v), [] as string[]);\n}\n\ninterface CreateFlagOpts {\n order?: string; provider?: string; byok?: boolean; managed?: boolean; 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\n/** `--provider daytona,e2b` → ['daytona', 'e2b']; empty is a usage error. */\nfunction providerNames(value: string): string[] {\n const names = value.split(',').map((name) => name.trim()).filter(Boolean);\n if (names.length === 0) throw new Error(`--provider \"${value}\" names no providers.`);\n return names;\n}\n\n/** `--byok` → the router's BYOK mode \"only\"; `--managed` → \"off\"; neither → the router's own. */\nfunction accountMode(opts: { byok?: boolean; managed?: boolean }): 'only' | 'off' | undefined {\n if (opts.byok && opts.managed) throw new Error('--byok and --managed are mutually exclusive.');\n return opts.byok ? 'only' : opts.managed ? 'off' : undefined;\n}\n\n/** The POST /api/v1/sandboxes body `create` and `run` share. */\nfunction buildCreateBody(opts: CreateFlagOpts): Record<string, unknown> {\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.provider && opts.order) {\n throw new Error('--provider narrows your router; --order skips it. Pass one.');\n }\n if (opts.provider) body.only = providerNames(opts.provider);\n const mode = accountMode(opts);\n if (mode !== undefined) {\n if (opts.order) throw new Error('--byok/--managed apply to your router; --order skips it.');\n body.byok = mode;\n }\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 return body;\n}\n\n/** `1h` / `30m` / `90s` — compact timeout text for the detach summary. */\nfunction fmtTimeout(ms: number): string {\n if (ms % 3_600_000 === 0) return `${ms / 3_600_000}h`;\n if (ms % 60_000 === 0) return `${ms / 60_000}m`;\n if (ms % 1_000 === 0) return `${ms / 1_000}s`;\n return `${ms}ms`;\n}\n\n/** Mirrors DEFAULT_SANDBOX_TIMEOUT_MS in benchmarks-platform lib/sandboxes/acquire.ts. */\nconst PLATFORM_DEFAULT_TIMEOUT_MS = 30 * 60_000;\n\ntype ListOpts = {\n status?: string;\n customerOnly?: boolean;\n search?: string;\n sort?: string;\n direction?: string;\n limit?: string;\n cursor?: string;\n};\n\nconst LIST_SORTS = ['created', 'name', 'cost', 'runtime'];\n\n/** The `GET /api/v1/sandboxes` query for `compute instances list`. */\nexport function listQuery(opts: ListOpts): Record<string, string | undefined> {\n if (opts.sort !== undefined && !LIST_SORTS.includes(opts.sort)) {\n throw new Error(`--sort must be one of ${LIST_SORTS.join(', ')}`);\n }\n if (opts.direction !== undefined && opts.direction !== 'asc' && opts.direction !== 'desc') {\n throw new Error('--direction must be asc or desc');\n }\n return {\n status: opts.status,\n customerOnly: opts.customerOnly ? 'true' : undefined,\n q: opts.search,\n sort: opts.sort,\n direction: opts.direction,\n limit: opts.limit,\n cursor: opts.cursor,\n };\n}\n\n/** GET /api/v1/sandboxes/options. */\ninterface SandboxOptionsWire {\n byokMode: 'off' | 'first' | 'fallback' | 'only';\n /** How managed rows are ordered, and the size that order is for (absent from older servers). */\n strategy?: 'computesdk' | 'cheapest' | 'custom';\n size?: string;\n options: Array<\n | { account: 'managed'; provider: string; sizes: { name: string; label: string; rate: { usd: number; per: string } | null }[] }\n | { account: 'byok'; provider: string; region: string | null; ready: boolean }\n >;\n}\n\nconst STRATEGY_LINE: Record<NonNullable<SandboxOptionsWire['strategy']>, string> = {\n computesdk: \"ComputeSDK's recommended order\",\n cheapest: 'cheapest first',\n custom: 'your own order',\n};\n\nconst BYOK_MODE_LINE: Record<SandboxOptionsWire['byokMode'], string> = {\n off: 'managed accounts only',\n first: 'your keys first, then managed accounts',\n fallback: 'managed accounts first, then your keys',\n only: 'your keys only',\n};\n\n/**\n * Everything a create can land on, in the router's order: managed accounts\n * with a price per size (billed from credit), BYOK providers (billed by the\n * provider). The first usable row is where a plain `compute new` goes.\n */\nfunction printSandboxOptions(o: SandboxOptionsWire): void {\n if (o.options.length === 0) {\n console.log('Nothing to create on yet: no managed account is live and no BYOK key is set up.');\n return;\n }\n const sizeNames = [...new Set(o.options.flatMap((row) => (row.account === 'managed' ? row.sizes.map((size) => size.name) : [])))]\n .filter((name) => name !== 'default');\n const order = ['small', 'medium', 'large', 'xlarge'];\n sizeNames.sort((a, b) => order.indexOf(a) - order.indexOf(b));\n const providerWidth = Math.max(8, ...o.options.map((row) => (row.account === 'byok' && row.region ? `${row.provider}:${row.region}` : row.provider).length));\n const cell = (text: string) => text.padEnd(11);\n console.log(pc.dim(`${'Provider'.padEnd(providerWidth)} ${'Account'.padEnd(8)} ${sizeNames.map(cell).join(' ')}`.trimEnd()));\n let first: string | null = null;\n for (const row of o.options) {\n const name = row.account === 'byok' && row.region ? `${row.provider}:${row.region}` : row.provider;\n let detail: string;\n let usable: boolean;\n if (row.account === 'managed') {\n const fixed = row.sizes.length === 1 && row.sizes[0]!.name === 'default';\n usable = row.sizes.some((size) => size.rate !== null);\n detail = fixed\n ? row.sizes[0]!.rate ? `default size ${shortRate(row.sizes[0]!.rate)}` : pc.dim('not priced yet')\n : sizeNames.map((size) => {\n const priced = row.sizes.find((entry) => entry.name === size)?.rate;\n return cell(priced ? shortRate(priced) : '—');\n }).join(' ').trimEnd();\n } else {\n usable = row.ready;\n detail = row.ready ? pc.dim(`billed by ${row.provider} to your account`) : pc.dim('key not tested — compute byok verify ' + row.provider);\n }\n if (usable && first === null) first = row.provider;\n console.log(`${name.padEnd(providerWidth)} ${(row.account === 'managed' ? 'managed' : 'BYOK').padEnd(8)} ${detail}`);\n }\n console.log('');\n console.log(`Router: ${BYOK_MODE_LINE[o.byokMode]} (BYOK ${o.byokMode}).`);\n if (o.strategy !== undefined && o.byokMode !== 'only') {\n const size = o.strategy === 'cheapest' && o.size !== undefined ? ` at ${o.size}` : '';\n console.log(`Managed accounts: ${STRATEGY_LINE[o.strategy]}${size} — change with compute sandboxes settings set --routing <computesdk|cheapest|providers>.`);\n }\n if (first !== null) console.log(pc.dim(`A plain \\`compute new\\` lands on ${first}. Pick one: compute new --${first} --size <size>`));\n}\n\nasync function showSandboxOptions(opts: CommonOpts): Promise<void> {\n const c = await client(opts);\n output(opts, await c.get<SandboxOptionsWire>('/api/v1/sandboxes/options'), printSandboxOptions);\n}\n\n/**\n * The `create` flags and action, on `compute sandboxes create` and on the\n * `compute new` shorthand. With `providerShorthand`, the command's operands\n * — `vercel` or an unknown `--vercel` flag, which commander hands over as\n * operands — name providers, as `--provider` does.\n */\nfunction registerCreate(command: Command, { providerShorthand = false }: { providerShorthand?: boolean } = {}): void {\n addCreateFlags(command)\n .option('--no-use', 'do not mark the new instance as this directory\\'s current instance')\n .option('--no-browser', 'print the sign-in URL instead of opening a browser')\n .option('-q, --quiet', 'print only the new instance ID')\n .option('--verbose', 'print the full instance details')\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 if (providerShorthand) {\n command\n .option('--org <slug>', 'organization slug for this command (or $COMPUTE_ORG)')\n .option('--list', 'list what you can create on, with prices, instead of creating (= compute sandboxes options)');\n }\n command\n .action(async (...args: unknown[]) => {\n const operands = providerShorthand ? (args[0] as string[]) : [];\n const opts = args[providerShorthand ? 1 : 0] as QuietOpts & CreateFlagOpts & { use?: boolean; list?: boolean };\n try {\n if (opts.list) {\n if (operands.length > 0) throw new Error('--list shows every option; drop the provider names.');\n await showSandboxOptions(opts);\n return;\n }\n checkQuietJson(opts);\n const { providers, project } = splitCreateOperands(operands);\n if (project) await localTree({ root: project }, sourceFilter(project));\n const named = shorthandProviders(providers);\n if (named.length > 0) {\n if (opts.provider) throw new Error('Name providers either as words/flags or with --provider, not both.');\n opts.provider = named.join(',');\n }\n const body = buildCreateBody(opts);\n const c = await creationClient(opts);\n if (!opts.json && !opts.quiet) await previewPlacement(c, opts);\n const res = await c.post<{ sandbox: SandboxDetail }>('/api/v1/sandboxes', body);\n let projectSync: SyncPlan | undefined;\n if (project) {\n try {\n projectSync = await syncOnce(c, { local: project }, { id: res.sandbox.id, remote: '/app' }, opts);\n } catch (error) {\n let destroyed = false;\n try {\n const cleanup = await c.del<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${res.sandbox.id}`);\n destroyed = cleanup.sandbox.status === 'destroyed';\n } catch { /* include the handle for manual cleanup below */ }\n throw new Error(`Initial sync failed for ${res.sandbox.id}: ${error instanceof Error ? error.message : String(error)}. ` +\n (destroyed ? 'The new sandbox was destroyed.' : `Cleanup unconfirmed; run compute destroy ${res.sandbox.id}.`));\n }\n }\n // Commander stores --no-use as `use: false`.\n if (opts.use !== false) {\n setCurrentInstance(res.sandbox.id, orgKey(opts));\n if (!opts.json && !opts.quiet) {\n console.error(pc.dim(`instance ${shortId(res.sandbox.id)} (current for ${dirKey()})`));\n }\n }\n const detail = { ...res.sandbox, ...(projectSync?.snapshot ? { syncSnapshot: projectSync.snapshot } : {}) };\n emitResult(opts, detail, (s) => s.id, (s) => {\n printSandbox(s, opts.verbose);\n if (s.syncSnapshot) console.log(`Snapshot ${s.syncSnapshot.id} retained until ${s.syncSnapshot.expiresAt}.`);\n });\n if (!opts.json && !opts.quiet) printNextSteps(res.sandbox.id, opts, project ? '/app' : undefined);\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n\n/**\n * Before the create (which only returns once the box is up), say where the\n * router will place it: the same quote `compute sandboxes route` prints.\n * It's the router's first choice; if that provider fails at create time the\n * walk moves on, and the created sandbox's line says where it landed. On\n * stderr, and never fatal: a failed quote just skips the line.\n */\nasync function previewPlacement(c: Awaited<ReturnType<typeof client>>, opts: CreateFlagOpts): Promise<void> {\n // --order and the market flags don't walk the router the quote describes.\n if (opts.order || opts.market || opts.orderType || opts.maxPrice) return;\n const mode = accountMode(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 timeoutMs: opts.timeoutMs,\n only: opts.provider === undefined ? undefined : providerNames(opts.provider).join(','),\n byok: mode,\n };\n let quote: SandboxQuoteWire;\n try {\n quote = (await c.get<{ quote: SandboxQuoteWire }>('/api/v1/sandboxes/quote', params)).quote;\n } catch {\n return; // A preview only; the create below reports any real problem.\n }\n if (!quote.ok || !quote.placement) {\n console.error(pc.dim(`→ the router can't place this: ${quoteRefusal(quote)}`));\n return;\n }\n const p = quote.placement;\n const provider = p.box?.provider ?? p.provider;\n console.error(\n pc.dim(`→ placing on ${provider} · ${placementLane(p.source)} · ${p.size ?? p.box?.sizeName ?? 'custom size'} (${billedBy(p.source, provider)}) …`),\n );\n}\n\n/**\n * Suggest commands for the newly selected instance. An explicit ID is needed\n * when --no-use or COMPUTE_INSTANCE prevents it from becoming current.\n * Keep one-off org/base URL flags and leave stdout available to scripts.\n */\nfunction printNextSteps(id: string, opts: { org?: string; baseUrl?: string; use?: boolean }, cwd?: string): void {\n const context = `${opts.org ? ` --org ${opts.org}` : ''}${opts.baseUrl ? ` --base-url ${opts.baseUrl}` : ''}`;\n const target = opts.use === false || (process.env.COMPUTE_INSTANCE && process.env.COMPUTE_INSTANCE !== id) ? ` ${id}` : '';\n const steps: [string, string][] = [\n [`compute exec${target}${context}${cwd ? ` --cwd ${cwd}` : ''} echo hello`, 'run your first command'],\n [`compute list${context}`, 'see your sandboxes'],\n [`compute destroy${target}${context}`, 'stop billing'],\n ];\n const width = Math.max(...steps.map(([command]) => command.length));\n console.error('');\n console.error('Use it:');\n for (const [command, does] of steps) console.error(` ${command.padEnd(width)} ${pc.dim(does)}`);\n console.error(pc.dim('It runs and bills until it times out or is destroyed.'));\n}\n\n/** Explicit path syntax avoids confusing provider names with local folder names. */\nexport function splitCreateOperands(operands: string[]): { providers: string[]; project?: string } {\n const index = operands.findIndex((value) => value === '.' || value === '..' || value.startsWith('./') || value.startsWith('../') || path.isAbsolute(value) || /^[A-Za-z]:[\\\\/]/.test(value));\n if (index === -1) return { providers: operands };\n if (index !== operands.length - 1) throw new Error('Put the local project directory after the providers: compute new e2b ./my-app.');\n return { providers: operands.slice(0, index), project: path.resolve(operands[index]) };\n}\n\n/** `['--vercel', 'e2b']` → `['vercel', 'e2b']`; anything else is a usage error. */\nfunction shorthandProviders(operands: string[]): string[] {\n return operands.map((operand) => {\n const name = operand.startsWith('--') ? operand.slice(2) : operand;\n if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) {\n throw new Error(`\"${operand}\" isn't a provider name — use e.g. \\`compute new vercel\\` or \\`compute new --vercel\\`.`);\n }\n return name;\n });\n}\n\nexport function registerSandboxesCommands(program: Command): void {\n const cmd = program\n .command('instances')\n .alias('sandboxes')\n .alias('sbx')\n .description('Create and drive compute instances through the platform')\n .enablePositionalOptions()\n .configureOutput({ outputError: usageErrorOutput });\n\n registerCreate(\n cmd\n .command('create')\n .description('Create a sandbox through your Sandboxes router (`compute sandboxes route` shows where it lands)'),\n );\n\n // `compute new` — the short form of `compute sandboxes create`. Providers\n // narrow the router like --provider, as words or as flags:\n // `compute new vercel` / `compute new --vercel` = `--provider vercel`.\n registerCreate(\n program\n .command('new')\n .description('Create a sandbox; compute new e2b . creates on e2b and syncs a local project to /app')\n .argument('[providersAndPath...]', 'provider names followed by an optional local directory (e.g. e2b ./my-app)')\n .allowUnknownOption()\n .configureOutput({ outputError: usageErrorOutput }),\n { providerShorthand: true },\n );\n\n registerSandboxOperations(cmd);\n\n // Each spelling needs its own Command (Commander stores parser state and\n // its parent on the object); both sets use the registrations below.\n const shortcuts = new Command().enablePositionalOptions();\n registerSandboxOperations(shortcuts);\n const rootCommands = new Set(['list', 'get', 'use', 'destroy', 'run', 'serve', 'exec', 'spawn', 'ps', 'logs', 'kill', 'wait', 'cp', 'url']);\n for (const sub of shortcuts.commands) {\n if (rootCommands.has(sub.name())) {\n sub.configureOutput({ outputError: usageErrorOutput });\n program.addCommand(sub);\n }\n }\n}\n\nfunction registerSandboxOperations(cmd: Command): void {\n // `options`: everything a create can land on, with prices, in router order.\n cmd\n .command('options')\n .description('List what you can create sandboxes on: managed accounts with prices per size, and your BYOK providers, in router order')\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 try {\n await showSandboxOptions(opts);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n // `route`: where a create would land under the Sandboxes router, and what\n // it costs — managed (ComputeSDK credit) or BYOK (billed by the provider).\n // `quote` is its pre-router name, kept hidden for existing scripts; the\n // market-only flags are accepted but stay out of help.\n for (const name of ['route', 'quote'] as const) {\n const command = cmd\n .command(name, { hidden: name === 'quote' })\n .description('Show where a sandbox create would land, how it is billed, and the price — creates nothing')\n .option('--size <size>', 'platform size: small, medium (default), large, xlarge, 2xlarge (16/32 GiB), 3xlarge (32/64 GiB)')\n .option('--provider <names>', 'only these providers, through your router (e.g. daytona)')\n .option('--byok', 'only your own keys')\n .option('--managed', 'only ComputeSDK managed accounts')\n .option('--cpus <n>', 'CPU cores (raw resources instead of --size)')\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; a managed account holds credit for it')\n .addOption(new Option('--order-type <type>').hideHelp())\n .addOption(new Option('--market').hideHelp())\n .addOption(new Option('--max-price <usd/unit>').hideHelp())\n .addOption(new Option('--max-price-per <unit>').hideHelp())\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response');\n command.action(async (opts: CommonOpts & {\n size?: string; provider?: string; byok?: boolean; managed?: boolean; 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 only: opts.provider === undefined ? undefined : providerNames(opts.provider).join(','),\n byok: accountMode(opts),\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\n cmd\n .command('list')\n .description('List sandboxes')\n .option('--status <status>', 'active (not destroyed) | creating | running | destroyed')\n .option('--customer-only', 'exclude idle platform sandboxes (warm pool, CI sync, snapshot builds); Actions job sandboxes stay')\n .option('--search <text>', 'match label, id, provider, provider sandbox id or product (Sandboxes, Actions)')\n .option('--sort <column>', 'created (default, newest first) | name | cost | runtime')\n .option('--direction <dir>', 'asc | desc (default: asc for name, desc for the others)')\n .option('--limit <n>', 'page size')\n .option('--cursor <cursor>', 'page cursor from a previous response (pass the same --sort and --direction)')\n .option('-q, --quiet', 'print only instance IDs, one per line')\n .option('--verbose', 'print the full instance details')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (opts: QuietOpts & ListOpts) => {\n try {\n checkQuietJson(opts);\n const c = await client(opts);\n const res = await c.get<{ sandboxes: SandboxSummary[]; nextCursor: string | null }>(\n '/api/v1/sandboxes',\n listQuery(opts),\n );\n emitResult(\n opts,\n res,\n (page) => page.sandboxes.map((s) => s.id).join('\\n'),\n (page) => {\n page.sandboxes.forEach((s) => printSandbox(s, opts.verbose));\n if (page.nextCursor) console.log(pc.dim(`nextCursor: ${page.nextCursor}`));\n },\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('--verbose', 'print the full instance details')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (argId: string | undefined, opts: QuietOpts) => {\n try {\n checkQuietJson(opts);\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.get<{ sandbox: SandboxDetail }>(`/api/v1/sandboxes/${resolved.id}`);\n output(opts, res.sandbox, (s) => printSandbox(s, opts.verbose));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('use [sandboxId]')\n .description('Show or set this directory\\'s current instance (COMPUTE_INSTANCE always wins)')\n .option('--clear', 'forget this directory\\'s current instance')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (argId: string | undefined, opts: QuietOpts & { clear?: boolean }) => {\n try {\n const org = orgKey(opts);\n if (opts.clear) {\n const prev = clearCurrentInstance(org);\n output(opts, { cleared: prev ?? null }, () =>\n console.log(\n prev\n ? `forgot ${shortId(prev)} (was current for ${dirKey()})`\n : 'nothing to forget',\n ),\n );\n return;\n }\n if (argId === undefined) {\n const r = resolveInstanceId(undefined, opts);\n output(opts, { id: r?.id ?? null, source: r?.source ?? null }, () => {\n if (!r) console.log(NO_INSTANCE_HINT);\n else {\n const where =\n r.source === 'env' ? 'COMPUTE_INSTANCE' : `current for ${r.dir}`;\n console.log(`instance ${shortId(r.id)} (${where})`);\n }\n });\n return;\n }\n if (!isUuid(argId)) {\n throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n }\n const c = await client(opts);\n const res = await c.get<{ sandbox: SandboxDetail }>(`/api/v1/sandboxes/${argId}`);\n if (res.sandbox.status === 'destroyed') {\n throw new Error(`instance ${shortId(argId)} is destroyed — pick a running instance`);\n }\n setCurrentInstance(argId, org);\n output(opts, { id: argId, dir: dirKey() }, () =>\n console.log(`instance ${shortId(argId)} (current for ${dirKey()})`),\n );\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 (argId: string | undefined, opts: QuietOpts) => {\n try {\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.del<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${resolved.id}`)\n .catch((e) => { resolved.clearStale(e); throw e; });\n // Never leave a dead instance as this directory's current pick.\n const org = orgKey(opts);\n if (readFileCurrent(org) === resolved.id) {\n clearCurrentInstance(org);\n if (!opts.json) {\n console.error(pc.dim(`cleared current instance ${shortId(resolved.id)}`));\n }\n }\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n addCreateFlags(\n cmd\n .command('run [command...]')\n .description(\n 'Create an instance, run a command on it, and tear it down. ' +\n '`run <cmd>` waits and destroys; `--keep` waits and keeps; `-d` returns immediately.',\n ),\n )\n .option('--no-browser', 'print the sign-in URL instead of opening a browser')\n .option('--keep', 'keep the instance after the command exits (it becomes this directory\\'s current instance)')\n .option('-d, --detach', 'start the command and return immediately (instance becomes current)')\n .option('--yes', 'non-interactive: Ctrl-C destroys without asking')\n .option('-q, --quiet', 'with --detach, print only the instance ID')\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 (rawCommand: string[], rawOpts: QuietOpts & CreateFlagOpts & { keep?: boolean; detach?: boolean; yes?: boolean }) => {\n let opts = rawOpts;\n try {\n checkQuietJson(opts);\n if (opts.keep && opts.detach) throw new Error('--keep and --detach are mutually exclusive.');\n const lead = takeLeadingOptions(rawCommand, COMMAND_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 await runInstanceCommand(command, opts);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('serve [sandboxId] [command...]')\n .description('Start a server, wait for its port to listen publicly, and print the URL')\n .option('--port <n>', 'the TCP port the server listens on (required)')\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('--timeout-ms <ms>', 'give up waiting for the port after this (default 120000)')\n .option('-q, --quiet', 'print only the URL')\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 (argId: string | undefined, rawCommand: string[], rawOpts: QuietOpts & { port: string; cwd?: string; env?: string[]; timeoutMs?: string }) => {\n let opts = rawOpts;\n try {\n checkQuietJson(opts);\n if (argId !== undefined && !isUuid(argId)) {\n rawCommand.unshift(argId);\n argId = undefined;\n }\n const lead = takeLeadingOptions(rawCommand, SERVE_LEAD_OPTS);\n opts = mergeLeadOpts(rawOpts, lead.inline);\n const command = lead.command;\n if (command.length === 0) throw new Error('missing command to serve');\n if (opts.port === undefined) throw new Error('--port is required');\n const port = Number(opts.port);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new Error('--port must be an integer between 1 and 65535');\n }\n const resolved = resolveSandbox(argId, opts);\n await serveInstanceCommand(resolved.id, command, port, opts);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('exec [sandboxId] [command...]')\n .description('Run a shell command or argv in a sandbox; --stream follows output, --detach returns a job ID')\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('--timeout <seconds>', 'command timeout in seconds (0: no command time limit)')\n .option('--timeout-ms <ms>', 'command timeout in ms (legacy spelling)')\n .option('--stream', 'print stdout and stderr while the command runs')\n .option('-d, --detach', 'start a background process and print its job ID')\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 (argId: string | undefined, rawCommand: string[], rawOpts: ExecOpts) => {\n let opts = rawOpts;\n try {\n // A non-UUID first positional is the first word of the command, not\n // an ID — `exec ls -la` works on the implicit instance.\n if (argId !== undefined && !isUuid(argId)) {\n rawCommand.unshift(argId);\n argId = undefined;\n }\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 // Reject incompatible options before resolving auth or starting work.\n execTimeout(opts);\n const resolved = resolveSandbox(argId, opts);\n const c = await client(opts);\n await execute(c, resolved.id, {\n command: execCommand(command),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {}),\n }, opts).catch((e) => { resolved.clearStale(e); throw e; });\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('-q, --quiet', 'print only the job ID')\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 (argId: string | undefined, rawCommand: string[], rawOpts: QuietOpts & { cwd?: string; env?: string[]; stdin?: boolean }) => {\n let opts = rawOpts;\n try {\n if (argId !== undefined && !isUuid(argId)) {\n rawCommand.unshift(argId);\n argId = undefined;\n }\n const lead = takeLeadingOptions(rawCommand, SPAWN_LEAD_OPTS);\n opts = mergeLeadOpts(rawOpts, lead.inline);\n checkQuietJson(opts);\n const command = lead.command;\n if (command.length === 0) throw new Error('missing command to spawn');\n const resolved = resolveSandbox(argId, opts);\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${resolved.id}/processes`,\n {\n command: execCommand(command),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {}),\n ...(opts.stdin ? { stdin: true } : {}),\n },\n ).catch((e) => { resolved.clearStale(e); throw e; });\n emitResult(opts, res.process, (p) => p.jobId, 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 (argId: string | undefined, opts: QuietOpts) => {\n try {\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.get<{ processes: SandboxProcess[] }>(\n `/api/v1/sandboxes/${resolved.id}/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 [jobOrSandboxId] [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 (argId: string | undefined, jobId: string | undefined, opts: QuietOpts & { follow?: boolean }) => {\n try {\n // `logs <jobId>` — a non-UUID first positional is the job, not the instance.\n const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, 'jobId');\n const c = await client(opts);\n if (opts.follow) {\n await followProcess(c, resolved.id, job);\n return;\n }\n const res = await c.get<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${resolved.id}/processes/${job}`,\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 [jobOrSandboxId] [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 (argId: string | undefined, jobId: string | undefined, opts: QuietOpts & { timeoutMs?: string }) => {\n try {\n const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, 'jobId');\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${resolved.id}/processes/${job}/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 [jobOrSandboxId] [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 (argId: string | undefined, jobId: string | undefined, opts: QuietOpts & { signal?: string }) => {\n try {\n const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, 'jobId');\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${resolved.id}/processes/${job}/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 [jobOrSandboxId] [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 (argId: string | undefined, jobId: string | undefined, opts: QuietOpts & { data?: string; file?: string; base64?: boolean }) => {\n try {\n const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, 'jobId');\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/${resolved.id}/processes/${job}/stdin`,\n { data, ...(opts.base64 ? { encoding: 'base64' } : {}) },\n );\n output(opts, res, () => console.log(`wrote ${data.length} chars to ${job}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('close-stdin [jobOrSandboxId] [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 (argId: string | undefined, jobId: string | undefined, opts: QuietOpts) => {\n try {\n const { resolved, resource: job } = resolveTwoArgTarget(argId, jobId, opts, 'jobId');\n const c = await client(opts);\n const res = await c.post<{ ok: boolean }>(\n `/api/v1/sandboxes/${resolved.id}/processes/${job}/close-stdin`,\n {},\n );\n output(opts, res, () => console.log(`closed stdin on ${job}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('ls [pathOrSandboxId] [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 (argId: string | undefined, path: string | undefined, opts: QuietOpts) => {\n try {\n // `ls /app` — a non-UUID first positional is the path.\n let resolved: ResolvedSandbox;\n let p: string;\n if (argId !== undefined && !isUuid(argId)) {\n if (path !== undefined) throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n resolved = resolveSandbox(undefined, opts);\n p = argId;\n } else {\n resolved = resolveSandbox(argId, opts);\n p = path ?? '/';\n }\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${resolved.id}/files`, {\n path: p,\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 [pathOrSandboxId] [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 (argId: string | undefined, path: string | undefined, opts: QuietOpts) => {\n try {\n let resolved: ResolvedSandbox;\n let p: string;\n if (argId !== undefined && !isUuid(argId)) {\n if (path !== undefined) throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n resolved = resolveSandbox(undefined, opts);\n p = argId;\n } else {\n resolved = resolveSandbox(argId, opts);\n if (path === undefined) throw new Error('missing path');\n p = path;\n }\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${resolved.id}/files`, { path: p });\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 [pathOrSandboxId] [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 (argId: string | undefined, path: string | undefined, opts: QuietOpts & { content?: string; file?: string }) => {\n try {\n let resolved: ResolvedSandbox;\n let p: string;\n if (argId !== undefined && !isUuid(argId)) {\n if (path !== undefined) throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n resolved = resolveSandbox(undefined, opts);\n p = argId;\n } else {\n resolved = resolveSandbox(argId, opts);\n if (path === undefined) throw new Error('missing path');\n p = path;\n }\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/${resolved.id}/files`,\n { path: p, 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 [pathOrSandboxId] [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 (argId: string | undefined, path: string | undefined, opts: QuietOpts) => {\n try {\n let resolved: ResolvedSandbox;\n let p: string;\n if (argId !== undefined && !isUuid(argId)) {\n if (path !== undefined) throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n resolved = resolveSandbox(undefined, opts);\n p = argId;\n } else {\n resolved = resolveSandbox(argId, opts);\n if (path === undefined) throw new Error('missing path');\n p = path;\n }\n const c = await client(opts);\n const res = await c.post<{ path: string }>(`/api/v1/sandboxes/${resolved.id}/files`, {\n path: p,\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 [pathOrSandboxId] [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 (argId: string | undefined, path: string | undefined, opts: QuietOpts) => {\n try {\n let resolved: ResolvedSandbox;\n let p: string;\n if (argId !== undefined && !isUuid(argId)) {\n if (path !== undefined) throw new Error(`\"${argId}\" is not a sandbox ID — expected a UUID.`);\n resolved = resolveSandbox(undefined, opts);\n p = argId;\n } else {\n resolved = resolveSandbox(argId, opts);\n if (path === undefined) throw new Error('missing path');\n p = path;\n }\n const c = await client(opts);\n const res = await c.del<{ path: string; removed: boolean }>(\n `/api/v1/sandboxes/${resolved.id}/files?path=${encodeURIComponent(p)}`,\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('cp <src> <dst>')\n .description('Copy files/dirs between here and an instance — remote side is [id:]/abs/path')\n .option('-q, --quiet', 'print nothing on success')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--org <slug>')\n .option('--json', 'print the raw response')\n .action(async (src: string, dst: string, opts: QuietOpts) => {\n try {\n checkQuietJson(opts);\n await cpCommand(src, dst, opts);\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('-q, --quiet', 'print only the URL (the default)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (argId: string | undefined, opts: QuietOpts & { port: string; protocol?: string }) => {\n try {\n checkQuietJson(opts);\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.get<{ url: string }>(`/api/v1/sandboxes/${resolved.id}/urls`, {\n port: opts.port,\n protocol: opts.protocol,\n });\n emitResult(opts, res, (r) => safeTerm(r.url), (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 (argId: string | undefined, opts: QuietOpts) => {\n try {\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.get<{ snapshots: SandboxSnapshot[] }>(\n `/api/v1/sandboxes/${resolved.id}/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 (argId: string | undefined, opts: QuietOpts & { label?: string }) => {\n try {\n const resolved = requireUuidOrImplicit(argId, opts);\n const c = await client(opts);\n const res = await c.post<{ snapshot: SandboxSnapshot }>(\n `/api/v1/sandboxes/${resolved.id}/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 [snapOrSandboxId] [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 (argId: string | undefined, snapshotId: string | undefined, opts: QuietOpts) => {\n try {\n const { resolved, resource: snap } = resolveTwoArgTarget(argId, snapshotId, opts, 'snapshotId');\n const c = await client(opts);\n const res = await c.del<{ ok: boolean }>(\n `/api/v1/sandboxes/${resolved.id}/snapshots/${snap}`,\n );\n output(opts, res, () => console.log(`deleted snapshot ${snap}`));\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 // Registered after the --org pass so `settings`, `costs` and their subcommands declare\n // their own full option set (the loop above only covers direct children).\n const nestedCommon = (sub: Command) =>\n sub\n .option('--api-key <key>', 'platform API key (or COMPUTE_API_KEY)')\n .option('--base-url <url>', 'platform base URL')\n .option('--org <slug>', 'organization slug for this command (or $COMPUTE_ORG)')\n .option('--allow-untrusted-host', 'allow non-computesdk.com base URLs')\n .option('--json', 'print the raw response');\n registerSettingsCommands(cmd, 'sandboxes', nestedCommon, { client, fail, output, usageErrorOutput });\n registerBillingCommands(cmd, nestedCommon, { client, fail, output });\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\n// ─── run ─────────────────────────────────────────────────────────────────────\n\n/** The `-d`/`Ctrl-C d` summary — everything needed to re-attach later. */\nfunction printDetachSummary(sandboxId: string, jobId: string, timeoutText: string): void {\n console.log(`instance ${sandboxId} job ${jobId} (running; ${timeoutText})`);\n // Explicit ids: COMPUTE_INSTANCE and the pick can point elsewhere.\n console.log(` follow: compute instances logs ${sandboxId} ${jobId}`);\n console.log(` wait: compute instances wait ${sandboxId} ${jobId}`);\n console.log(` destroy: compute instances destroy ${sandboxId}`);\n}\n\n/** The timeout text for the detach summary: requested, else the platform default. */\nfunction runTimeoutText(opts: { timeoutMs?: string }): string {\n return opts.timeoutMs\n ? `instance timeout: ${fmtTimeout(Number(opts.timeoutMs))}`\n : `instance timeout: ${fmtTimeout(PLATFORM_DEFAULT_TIMEOUT_MS)} (platform default)`;\n}\n\nfunction confirmedDestroyedSandbox(result: { sandbox: SandboxSummary }, id: string): SandboxSummary {\n if (result?.sandbox?.status !== 'destroyed') {\n throw new Error('Teardown was not confirmed; run compute destroy ' + id);\n }\n return result.sandbox;\n}\n\n/**\n * `compute instances run` — create, spawn, stream via repeated `wait` calls\n * (each returns the cumulative buffers; we print only the delta), then destroy\n * in a `finally`. `--keep` skips the destroy, `-d` skips the wait too; both\n * leave the instance as this directory's current one.\n */\nasync function runInstanceCommand(\n command: string[],\n opts: QuietOpts & CreateFlagOpts & { keep?: boolean; detach?: boolean; yes?: boolean },\n): Promise<void> {\n const startedAt = Date.now();\n const body = buildCreateBody(opts);\n const c = await creationClient(opts);\n const created = await c.post<{ sandbox: SandboxDetail }>('/api/v1/sandboxes', body);\n const sandbox = created.sandbox;\n const org = orgKey(opts);\n // Before anything else: the ID on stderr, so a `kill -9` leaves a handle.\n if (!opts.json) console.error(pc.dim(`instance ${sandbox.id}`));\n\n const spawned = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${sandbox.id}/processes`,\n { command: command.map(shellQuote).join(' ') },\n ).catch(async (e) => {\n try { await c.del(`/api/v1/sandboxes/${sandbox.id}`); } catch { /* best effort */ }\n throw e;\n });\n const jobId = spawned.process.jobId;\n\n if (opts.detach) {\n setCurrentInstance(sandbox.id, org);\n if (opts.json) console.log(JSON.stringify({ type: 'detached', sandboxId: sandbox.id, jobId }));\n else if (opts.quiet) console.log(sandbox.id);\n else printDetachSummary(sandbox.id, jobId, runTimeoutText(opts));\n return;\n }\n\n let exitCode: number | null = null;\n let destroyRequested = false;\n let detachRequested = false;\n let prompting = false;\n let deleted = false;\n let kept = false;\n let settledCostUsd: number | undefined;\n let cleanupError: string | undefined;\n let printedOut = 0;\n let printedErr = 0;\n\n const flush = (p: SandboxProcessStatus) => {\n if (prompting) return; // Ctrl-C prompt owns the terminal right now\n if (p.stdout.length > printedOut) {\n const data = p.stdout.slice(printedOut);\n if (opts.json) console.log(JSON.stringify({ type: 'stdout', data }));\n else process.stdout.write(data);\n printedOut = p.stdout.length;\n }\n if (p.stderr.length > printedErr) {\n const data = p.stderr.slice(printedErr);\n if (opts.json) console.log(JSON.stringify({ type: 'stderr', data }));\n else process.stderr.write(data);\n printedErr = p.stderr.length;\n }\n };\n\n const onSignal = () => {\n if (!process.stdin.isTTY || opts.json || opts.yes || prompting) {\n // Non-TTY, --yes, or a 2nd Ctrl-C mid-prompt: destroy outright\n // (a mid-prompt Ctrl-C counts as N — keep waiting — unless readline\n // already closed, in which case fall through to destroy below).\n if (prompting) return;\n destroyRequested = true;\n return;\n }\n prompting = true;\n const rl = readline.createInterface({ input: process.stdin, output: process.stderr });\n rl.question(`Destroy instance ${shortId(sandbox.id)}? [y/N/d] `, (answer) => {\n rl.close();\n prompting = false;\n const a = answer.trim().toLowerCase();\n if (a === 'y') destroyRequested = true;\n else if (a === 'd') detachRequested = true;\n // N/Enter: keep waiting.\n });\n };\n process.on('SIGINT', onSignal);\n process.on('SIGTERM', onSignal);\n\n try {\n const deadline = opts.timeoutMs ? Date.now() + Number(opts.timeoutMs) : undefined;\n // Repeated waits, streaming the cumulative buffers' new tail each round.\n // ~55s per call stays under the route's wall-clock cap.\n while (exitCode === null && !destroyRequested && !detachRequested) {\n const remaining = deadline === undefined ? 55_000 : Math.max(1, deadline - Date.now());\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandbox.id}/processes/${jobId}/wait`,\n { timeoutMs: Math.min(55_000, remaining) },\n );\n flush(res.process);\n if (res.process.status === 'exited') {\n exitCode = res.process.exitCode ?? 128;\n } else if (deadline !== undefined && Date.now() >= deadline) {\n destroyRequested = true;\n }\n }\n } finally {\n process.removeListener('SIGINT', onSignal);\n process.removeListener('SIGTERM', onSignal);\n if (detachRequested) {\n kept = true;\n setCurrentInstance(sandbox.id, org);\n if (!opts.json) printDetachSummary(sandbox.id, jobId, runTimeoutText(opts));\n } else if (opts.keep && exitCode !== null) {\n kept = true;\n // --keep only keeps a run that reached an exit; a wait error or a\n // destroy request falls through to deletion so a failed run can't\n // leave a running instance behind.\n setCurrentInstance(sandbox.id, org);\n if (!opts.json && opts.quiet) console.log(sandbox.id);\n else if (!opts.json) {\n console.error(pc.dim(`kept instance ${shortId(sandbox.id)} (current for ${dirKey()})`));\n console.log(sandbox.id);\n }\n } else {\n try {\n const result = await c.del<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${sandbox.id}`);\n const cost = confirmedDestroyedSandbox(result, sandbox.id).cost;\n deleted = true;\n if (cost?.settled && cost.costUsd !== null && Number.isFinite(cost.costUsd)) settledCostUsd = cost.costUsd;\n } catch (e) {\n cleanupError = e instanceof Error ? e.message : String(e);\n if (!opts.json) console.error(pc.red(`destroy failed for ${sandbox.id}: ${safeTerm(cleanupError)}`));\n }\n const orgNow = orgKey(opts);\n if (readFileCurrent(orgNow) === sandbox.id) clearCurrentInstance(orgNow);\n }\n const summary = {\n type: 'summary', sandboxId: sandbox.id, jobId, exitCode,\n elapsedSeconds: (Date.now() - startedAt) / 1000,\n provider: sandbox.placement?.box?.provider ?? sandbox.provider,\n deleted, kept,\n ...(cleanupError ? { cleanupError } : {}),\n ...(settledCostUsd !== undefined ? { costUsd: settledCostUsd } : {}),\n };\n if (opts.json) console.log(JSON.stringify(summary));\n else console.error(pc.dim(\n `exit ${exitCode ?? 'unknown'} · ${summary.elapsedSeconds.toFixed(1)}s · ${safeTerm(summary.provider ?? 'unknown provider')}` +\n (settledCostUsd !== undefined ? ` · $${settledCostUsd.toFixed(4)}` : '') +\n ` · ${sandbox.id} ${deleted ? 'deleted' : summary.kept ? 'kept' : 'cleanup unconfirmed'}`,\n ));\n }\n\n process.exitCode = detachRequested ? 0 : (cleanupError && exitCode === 0 ? 1 : exitCode ?? (destroyRequested ? 130 : 1));\n}\n\n// ─── serve ───────────────────────────────────────────────────────────────────\n\ninterface PortsResponse {\n ports: { port: number; address: string; public: boolean }[];\n waited?: boolean;\n found?: boolean;\n}\n\n/** Wait-cap per `/ports?wait=` call — the route caps at 60s. */\nconst SERVE_POLL_MS = 30_000;\nconst SERVE_DEFAULT_WAIT_MS = 120_000;\n\n/**\n * `compute instances serve` — start a server process and wait until its port\n * listens on a public address, then print the provider URL.\n *\n * Failure modes per spec: a loopback-only bind fails with the bind hint; the\n * process exiting early prints its exit code and last log lines.\n */\nasync function serveInstanceCommand(\n id: string,\n command: string[],\n port: number,\n opts: QuietOpts & { cwd?: string; env?: string[]; timeoutMs?: string },\n): Promise<void> {\n const c = await client(opts);\n const spawned = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${id}/processes`,\n {\n command: command.map(shellQuote).join(' '),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.env?.length ? { env: parseInputs(opts.env) } : {}),\n },\n );\n const jobId = spawned.process.jobId;\n\n const jobStatus = () =>\n c.get<{ process: SandboxProcessStatus }>(`/api/v1/sandboxes/${id}/processes/${jobId}`);\n const reportExit = (proc: SandboxProcessStatus): void => {\n if (!opts.json) {\n const logs = `${proc.stdout}${proc.stderr}`.trimEnd().split('\\n');\n if (logs.length > 0 && logs[0] !== '') {\n console.error(pc.dim('--- last log lines ---'));\n for (const line of logs.slice(-50)) console.error(safeTerm(line));\n }\n }\n fail(new Error(`The server exited (code ${proc.exitCode ?? '?'}) before port ${port} listened.`), opts);\n };\n\n const waitMs = opts.timeoutMs ? Number(opts.timeoutMs) : SERVE_DEFAULT_WAIT_MS;\n const deadline = Date.now() + waitMs;\n let entry: PortsResponse['ports'][number] | undefined;\n let remaining = waitMs;\n while (!entry && remaining > 0) {\n const res = await c.get<PortsResponse>(\n `/api/v1/sandboxes/${id}/ports?wait=${port}&timeoutMs=${Math.min(SERVE_POLL_MS, remaining)}`,\n );\n entry = res.ports.find((p) => p.port === port);\n if (entry) break;\n // Not listening — did the server die?\n const proc = await jobStatus();\n if (proc.process.status === 'exited') {\n reportExit(proc.process);\n return; // fail() stubs process.exit in tests — don't keep polling.\n }\n remaining = deadline - Date.now();\n }\n\n if (entry) {\n // A listener doesn't prove our server bound the port — when another\n // process already owns it our job dies silently. Check before printing.\n const proc = await jobStatus();\n if (proc.process.status === 'exited') {\n reportExit(proc.process);\n return;\n }\n } else {\n if (!opts.json) printServeJobFooter(id, jobId);\n fail(new Error(`Port ${port} never listened within ${fmtTimeout(waitMs)}.`), opts);\n return;\n }\n\n if (!entry.public) {\n if (!opts.json) printServeJobFooter(id, jobId);\n fail(new Error(\n `Port ${port} is listening on ${safeTerm(entry.address)} only. ` +\n `Bind to 0.0.0.0 (e.g. --host 0.0.0.0) so it can be reached.`),\n opts,\n );\n return;\n }\n\n const { url } = await c.get<{ url: string }>(`/api/v1/sandboxes/${id}/urls?port=${port}`);\n if (opts.quiet) {\n console.log(safeTerm(url));\n return;\n }\n // --json emits the raw field; only terminal output is sanitized.\n output(opts, { url }, () => {\n console.log(safeTerm(url));\n printServeJobFooter(id, jobId);\n });\n}\n\nfunction printServeJobFooter(sandboxId: string, jobId: string): void {\n // Always name the instance: the implicit instance may be a different box.\n console.error(pc.dim(` job ${jobId}`));\n console.error(pc.dim(` logs: compute instances logs ${sandboxId} ${jobId}`));\n console.error(pc.dim(` kill: compute instances kill ${sandboxId} ${jobId}`));\n}\n\n\n\n// ─── cp ─────────────────────────────────────────────────────────────────────\n\n/** Wire shapes for the platform `/transfers` endpoints. */\ninterface TransferCreate {\n transferId: string;\n uploadUrl?: string;\n downloadUrl?: string;\n expiresAt?: string;\n bytes?: number;\n files?: number;\n}\ninterface TransferComplete {\n path: string;\n bytes: number;\n files: number;\n}\n\n/** Stderr progress appears past this size on TTYs. */\nconst CP_PROGRESS_MIN_BYTES = 10 * 1024 * 1024;\n\n/** Presigned transfer URLs must be https — except loopback, for local dev. */\nfunction assertTransferUrl(raw: string): void {\n let u: URL;\n try {\n u = new URL(raw);\n } catch {\n throw new Error('platform returned a malformed transfer URL');\n }\n if (u.protocol === 'https:') return;\n const loopback = ['localhost', '127.0.0.1', '::1', '[::1]'].includes(u.hostname);\n if (!(u.protocol === 'http:' && loopback)) {\n throw new Error(`refusing insecure transfer URL: ${u.protocol}//${u.hostname} (expected https)`);\n }\n}\n\n/** tar entries that would write outside the extract root. */\nfunction tarEntryIsSafe(p: string, entry: unknown): boolean {\n if (path.isAbsolute(p) || p.split('/').includes('..')) return false;\n const { type, linkpath } = entry as { type?: string; linkpath?: string };\n if ((type === 'Link' || type === 'SymbolicLink') && linkpath) {\n if (path.isAbsolute(linkpath) || linkpath.split('/').includes('..')) return false;\n }\n return true;\n}\n\n/**\n * One side of `cp <src> <dst>`: a remote endpoint is `[uuid:]/abs/path`\n * (omitted uuid = the current instance); anything else is a local path —\n * `box:./x` and `label:…` stay local, matching the positional-ID rule.\n */\nfunction parseCpEndpoint(arg: string): { remoteId?: string; remotePath: string } | { local: string } {\n const m = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})?:(\\/.*)$/.exec(arg);\n if (m) return { remoteId: m[1] || undefined, remotePath: m[2] };\n return { local: arg };\n}\n\n/**\n * `compute instances cp` — one side remote (`[id:]/abs/path`), one side local.\n * Upload: tar.gz the local path → PUT the presigned `uploadUrl` → `/complete`\n * makes the box pull + extract under the remote dir. Download: `/transfers`\n * makes the box tar + PUT; we GET the `downloadUrl` and extract into the\n * local dir (created if missing — the remote basename always stays the\n * top-level entry, docker-style `cp src dst/…` semantics; no rename form).\n */\nasync function cpCommand(src: string, dst: string, opts: QuietOpts): Promise<void> {\n const s = parseCpEndpoint(src);\n const d = parseCpEndpoint(dst);\n const sRemote = 'remotePath' in s;\n const dRemote = 'remotePath' in d;\n if (sRemote === dRemote) {\n throw new Error('cp needs exactly one remote side — write it as [id:]/abs/path (e.g. 3f2a…:/app or :/app)');\n }\n const c = await client(opts);\n if (!sRemote && 'remotePath' in d && 'local' in s) {\n const resolved = resolveSandbox(d.remoteId, opts);\n const r = await cpUpload(c, resolved.id, s.local, d.remotePath, opts);\n output(opts, r, (done) => {\n if (!opts.quiet) console.log(`copied ${done.files} files (${formatBytes(done.bytes)}) → ${shortId(resolved.id)}:${d.remotePath}`);\n });\n } else if ('remotePath' in s && 'local' in d) {\n const resolved = resolveSandbox(s.remoteId, opts);\n const r = await cpDownload(c, resolved.id, s.remotePath, d.local, opts);\n output(opts, r, (done) => {\n if (!opts.quiet) console.log(`copied ${done.files} files (${formatBytes(done.bytes)}) → ${d.local}`);\n });\n }\n}\n\n/** Write `X/Y MB` progress to stderr while a known total streams by. */\nfunction cpProgress(total: number, opts: QuietOpts): { bump: (n: number) => void; done: () => void } {\n const show = !opts.quiet && !opts.json && process.stderr.isTTY && total > CP_PROGRESS_MIN_BYTES;\n let sent = 0;\n return {\n bump(n) {\n if (!show) return;\n sent += n;\n process.stderr.write(`\\r${formatBytes(sent)} / ${formatBytes(total)} (${Math.round((sent / total) * 100)}%)`);\n },\n done() {\n if (show) process.stderr.write('\\n');\n },\n };\n}\n\nasync function cpUpload(\n c: ActionsClient,\n sandboxId: string,\n localPath: string,\n remotePath: string,\n opts: QuietOpts,\n): Promise<TransferComplete> {\n // statSync first so a missing path errors before anything is created.\n const abs = path.resolve(localPath);\n fs.statSync(abs);\n // Private 0700 dir: a shared /tmp path can be pre-created by another\n // local user and the tarball written somewhere attacker-readable.\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'compute-cp-up-'));\n const tmp = path.join(tmpDir, 'archive.tar.gz');\n try {\n await tar.create({ gzip: true, file: tmp, cwd: path.dirname(abs) }, [path.basename(abs)]);\n const size = fs.statSync(tmp).size;\n const created = await c.post<TransferCreate>(\n `/api/v1/sandboxes/${sandboxId}/transfers`,\n { direction: 'upload', path: remotePath },\n );\n if (!created.uploadUrl) throw new Error('platform did not return an upload URL');\n assertTransferUrl(created.uploadUrl);\n const progress = cpProgress(size, opts);\n try {\n const stream = fs.createReadStream(tmp);\n stream.on('data', (chunk: Buffer | string) => progress.bump(typeof chunk === 'string' ? chunk.length : chunk.byteLength));\n const res = await fetch(created.uploadUrl, {\n method: 'PUT',\n headers: { 'content-length': String(size), 'content-type': 'application/gzip' },\n // @ts-expect-error Readable.toWeb body is supported at runtime; DOM types lag\n body: Readable.toWeb(stream),\n duplex: 'half',\n });\n if (!res.ok) throw new Error(`upload failed: HTTP ${res.status}`);\n } finally {\n progress.done();\n }\n return await c.post<TransferComplete>(\n `/api/v1/sandboxes/${sandboxId}/transfers/${created.transferId}/complete`,\n {},\n );\n } finally {\n fs.rmSync(tmpDir, { recursive: true, force: true });\n }\n}\n\nasync function cpDownload(\n c: ActionsClient,\n sandboxId: string,\n remotePath: string,\n localDir: string,\n opts: QuietOpts,\n): Promise<TransferComplete> {\n const created = await c.post<TransferCreate>(\n `/api/v1/sandboxes/${sandboxId}/transfers`,\n { direction: 'download', path: remotePath },\n );\n if (!created.downloadUrl) throw new Error('platform did not return a download URL');\n assertTransferUrl(created.downloadUrl);\n const res = await fetch(created.downloadUrl);\n if (!res.ok) throw new Error(`download failed: HTTP ${res.status}`);\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'compute-cp-dl-'));\n const tmp = path.join(tmpDir, 'archive.tar.gz');\n try {\n const progress = cpProgress(created.bytes ?? 0, opts);\n const ws = fs.createWriteStream(tmp);\n try {\n // A stream error (e.g. ENOSPC) must fail the copy, not hang on 'drain'.\n await new Promise<void>((resolve, reject) => {\n ws.once('error', reject);\n const reader = res.body!.getReader();\n const pump = async (): Promise<void> => {\n for (;;) {\n const { done, value } = await reader.read();\n if (done || value === undefined) break;\n progress.bump(value.byteLength);\n if (!ws.write(value)) await new Promise<void>((r) => ws.once('drain', () => r()));\n }\n };\n pump().then(\n () => ws.end(() => resolve()),\n reject,\n );\n });\n } finally {\n ws.destroy();\n }\n progress.done();\n fs.mkdirSync(localDir, { recursive: true });\n await tar.extract({ file: tmp, cwd: localDir, filter: tarEntryIsSafe });\n return { path: localDir, bytes: created.bytes ?? fs.statSync(tmp).size, files: created.files ?? 0 };\n } finally {\n fs.rmSync(tmpDir, { recursive: true, force: true });\n }\n}\n\n/** Human byte count for the cp summary line and progress. */\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n} B`;\n const units = ['KB', 'MB', 'GB', 'TB'];\n let v = n / 1024;\n let i = 0;\n while (v >= 1024 && i < units.length - 1) { v /= 1024; i += 1; }\n return `${v >= 100 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;\n}\n","/**\n * The \"current instance\" — the instance a directory's commands default to.\n *\n * One global setting would be unsafe (two agents or terminals would stomp on\n * each other), so the entry is scoped twice: to the working directory's git\n * root (the cwd itself outside a repo) and to the org the command runs as.\n * `COMPUTE_INSTANCE` always wins for agents and CI; an explicit ID argument\n * wins over everything.\n *\n * The file lives next to `credentials.json` (`~/.benchsdk/current-instances.json`,\n * mode 0600). Nothing is written into the user's project.\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/** Resolved lazily so tests can point BENCHSDK_STATE_DIR at a tmp dir. */\nfunction stateDir(): string {\n return process.env.BENCHSDK_STATE_DIR ?? join(homedir(), '.benchsdk');\n}\n\nfunction statePath(): string {\n return join(stateDir(), 'current-instances.json');\n}\n\n/** `[dirKey][orgKey] = sandboxId`. */\ntype Store = Record<string, Record<string, string>>;\n\nexport type InstanceSource = 'argument' | 'env' | 'file';\n\nexport interface ResolvedInstance {\n id: string;\n source: InstanceSource;\n /** The directory key the `file` hit came from — shown in the dim line. */\n dir?: string;\n}\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** The platform validates sandbox ids as UUIDs; only a UUID may take the id slot. */\nexport function isUuid(value: string | undefined): value is string {\n return value !== undefined && UUID_RE.test(value);\n}\n\n/** The git root when inside a repo, else the working directory itself. */\nexport function dirKey(cwd = process.cwd()): string {\n const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8' });\n return r.status === 0 && r.stdout.trim() !== '' ? r.stdout.trim() : cwd;\n}\n\n/** A stable org discriminator: the slug override, else a hash of the bearer key. */\nexport function orgKey(opts: { org?: string; apiKey?: string }): string {\n const slug = opts.org || process.env.COMPUTE_ORG;\n if (slug) return `org:${slug}`;\n const key = opts.apiKey || process.env.COMPUTE_API_KEY || process.env.BENCHMARKS_PLATFORM_API_KEY;\n if (key) return `key:${createHash('sha256').update(key).digest('hex').slice(0, 12)}`;\n // OAuth login: key the pick to the org recorded by the last `org use` on\n // this machine (a cache — the consent row is the truth), so switching orgs\n // doesn't silently reuse the previous org's instance.\n try {\n const raw = JSON.parse(readFileSync(join(stateDir(), 'credentials.json'), 'utf8')) as {\n orgId?: string;\n orgSlug?: string;\n };\n const org = raw?.orgId ?? raw?.orgSlug;\n if (org) return `org:${org}`;\n } catch {\n // No stored login — unauthenticated commands share 'default'.\n }\n return 'default';\n}\n\nfunction readStore(): Store {\n try {\n const parsed = JSON.parse(readFileSync(statePath(), 'utf8')) as unknown;\n if (typeof parsed !== 'object' || parsed === null) return {};\n return parsed as Store;\n } catch {\n return {};\n }\n}\n\nfunction writeStore(store: Store): void {\n mkdirSync(stateDir(), { recursive: true });\n // tmp+rename: readers never see a truncated file, and the rename lands with\n // the fresh file's 0600 mode even when replacing a permissive old one.\n const tmp = `${statePath()}.${process.pid}.tmp`;\n writeFileSync(tmp, JSON.stringify(store, null, 2) + '\\n', { mode: 0o600 });\n renameSync(tmp, statePath());\n}\n\n/**\n * mkdir is atomic: the first creator wins. Writers serialize their\n * read-modify-write so two commands updating different picks can't clobber\n * each other; gives up after ~1s rather than hang on a stale lock dir.\n */\nfunction withStoreLock<T>(fn: () => T): T {\n const lock = `${statePath()}.lock`;\n for (let attempt = 0; ; attempt++) {\n try {\n mkdirSync(lock);\n break;\n } catch {\n if (attempt === 99) return fn();\n const until = Date.now() + 10;\n while (Date.now() < until) {\n // spin — writes take microseconds, so a short busy wait suffices\n }\n }\n }\n try {\n return fn();\n } finally {\n try {\n rmSync(lock, { recursive: true, force: true });\n } catch {\n // Already gone — another process took over a stale lock.\n }\n }\n}\n\n/** Persist `sandboxId` as the current instance for this directory + org. */\nexport function setCurrentInstance(sandboxId: string, org: string, dir = dirKey()): void {\n withStoreLock(() => {\n const store = readStore();\n (store[dir] ??= {})[org] = sandboxId;\n writeStore(store);\n });\n}\n\n/** Forget this directory + org's current instance; returns the forgotten id. */\nexport function clearCurrentInstance(org: string, dir = dirKey()): string | undefined {\n return withStoreLock(() => {\n const store = readStore();\n const prev = store[dir]?.[org];\n if (prev === undefined) return undefined;\n delete store[dir][org];\n if (Object.keys(store[dir]).length === 0) delete store[dir];\n writeStore(store);\n return prev;\n });\n}\n\n/** What `use --clear` and destroyed-instance cleanup report on. */\nexport function readFileCurrent(org: string, dir = dirKey()): string | undefined {\n return readStore()[dir]?.[org];\n}\n\n/**\n * The instance a command targets: the explicit argument if it is a UUID, else\n * `COMPUTE_INSTANCE`, else this directory's stored pick. `undefined` when none\n * apply — the caller prints the no-instance hint.\n */\nexport function resolveInstanceId(\n arg: string | undefined,\n opts: { org?: string; apiKey?: string },\n dir = dirKey(),\n): ResolvedInstance | undefined {\n if (isUuid(arg)) return { id: arg, source: 'argument' };\n const env = process.env.COMPUTE_INSTANCE;\n if (env) return { id: env, source: 'env' };\n const file = readFileCurrent(orgKey(opts), dir);\n if (file) return { id: file, source: 'file', dir };\n return undefined;\n}\n\n/** `3f2a…` — the short id form used in informational lines. */\nexport function shortId(id: string): string {\n return id.length > 8 ? `${id.slice(0, 4)}…` : id;\n}\n\n/** Delete the state file wholesale (logout-style hygiene; not wired today). */\nexport function _resetStateFileForTests(): void {\n const p = statePath();\n if (existsSync(p)) rmSync(p);\n}\n","/**\n * `compute instances costs` — the org's sandbox spend\n * (`GET /api/v1/sandboxes/costs`).\n */\n\nimport type { Command } from 'commander';\nimport type { ActionsClient } from './actions-client.js';\nimport type { CommonOpts } from './actions.js';\nimport { formatMoney } from './rate-display.js';\nimport { safeTerm } from './term.js';\n\n/** Injected by `sandboxes.ts`, matching the settings commands. */\nexport interface BillingDeps {\n client: (opts: CommonOpts) => Promise<ActionsClient>;\n output: <T>(opts: CommonOpts, data: T, render: (data: T) => void) => void;\n fail: (error: unknown, opts?: CommonOpts) => never;\n}\n\n// Wire shape mirrors benchmarks-platform lib/sandboxes/router.ts (`OrgSandboxCosts`).\n\nexport interface SandboxCosts {\n currency: string;\n running: { count: number; costUsd: number };\n settled: { count: number; costUsd: number };\n totalUsd: number;\n byProvider: Array<{\n provider: string;\n count: number;\n costUsd: number;\n /** Absent on servers that predate the per-provider split. */\n running?: { count: number; costUsd: number };\n settled?: { count: number; costUsd: number };\n }>;\n}\n\nfunction printTable(header: string[], rows: string[][]): void {\n const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));\n const line = (cells: string[]) => cells.map((c, i) => c.padEnd(widths[i])).join(' ').trimEnd();\n console.log(line(header));\n for (const row of rows) console.log(line(row));\n}\n\n/** Older servers send no per-provider running / settled split; those cells show `—`. */\nexport function printCosts(c: SandboxCosts, customerOnly: boolean): void {\n if (customerOnly) console.log('customer sandboxes only');\n printTable(\n ['PROVIDER', 'SANDBOXES', 'RUNNING', 'RUNNING COST', 'SETTLED', 'TOTAL'],\n [\n [\n 'all',\n String(c.running.count + c.settled.count),\n String(c.running.count),\n formatMoney(c.running.costUsd),\n `${c.settled.count} · ${formatMoney(c.settled.costUsd)}`,\n formatMoney(c.totalUsd),\n ],\n ...c.byProvider.map((p) => [\n safeTerm(p.provider),\n String(p.count),\n p.running ? String(p.running.count) : '—',\n p.running ? formatMoney(p.running.costUsd) : '—',\n p.settled ? `${p.settled.count} · ${formatMoney(p.settled.costUsd)}` : '—',\n formatMoney(p.costUsd),\n ]),\n ],\n );\n if (c.currency !== 'USD') console.log(`currency: ${safeTerm(c.currency)}`);\n}\n\nexport function registerBillingCommands(\n group: Command,\n common: (cmd: Command) => Command,\n deps: BillingDeps,\n): void {\n common(\n group\n .command('costs')\n .description(\"Show the org's sandbox spend: running, settled and per provider\")\n .option('--customer-only', 'exclude idle platform sandboxes (warm pool, CI sync, snapshot builds); Actions job sandboxes stay'),\n ).action(async (opts: CommonOpts & { customerOnly?: boolean }) => {\n try {\n const c = await deps.client(opts);\n const res = await c.get<SandboxCosts>(\n '/api/v1/sandboxes/costs',\n opts.customerOnly ? { customerOnly: 'true' } : undefined,\n );\n deps.output(opts, res, (data) => printCosts(data, opts.customerOnly === true));\n } catch (e) {\n deps.fail(e, opts);\n }\n });\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { spawnSync } from 'node:child_process';\nimport { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport ignore, { type Ignore } from 'ignore';\nimport * as tar from 'tar';\nimport { Command } from 'commander';\nimport { client, fail, output, safeTerm, type CommonOpts } from './actions.js';\nimport type { ActionsClient } from './actions-client.js';\nimport { isUuid, resolveInstanceId } from './current-instance.js';\nimport type { SyncEntry } from './sync-fs.js';\nimport { SnapshotSession, selectSnapshot, endpointRoot, ignoredPaths, type CaptureResult } from './snapshot-engine.js';\nimport { randomUUID } from 'node:crypto';\nimport { retainCapture, type RetainedSnapshot } from './sync-retention.js';\n\nexport type SyncEndpoint = { local: string } | { id: string; remote: string };\nexport interface SyncOptions extends CommonOpts { delete?: boolean; dryRun?: boolean; watch?: boolean }\nexport interface SyncPlan { copy: SyncEntry[]; remove: SyncEntry[]; snapshot?: RetainedSnapshot }\n\nexport function syncEndpoint(value: string, opts: CommonOpts): SyncEndpoint {\n const match = /^([^:]*):(\\/.*)$/.exec(value);\n if (!match || /^[a-zA-Z]:[\\\\/]/.test(value)) return { local: path.resolve(value) };\n const id = match[1] || resolveInstanceId(undefined, opts)?.id;\n if (!id || !isUuid(id)) throw new Error('Use a sandbox UUID or select one with compute new / compute use <id>.');\n const remote = path.posix.normalize(match[2]);\n if (remote === '/' || remote.split('/').includes('.git')) throw new Error('Sync requires a project directory outside .git.');\n return { id, remote };\n}\n\n/** Nested .gitignore rules, relative to each rule file. Ignored trees are never read. */\nexport function sourceFilter(root: string): (name: string, directory: boolean) => boolean {\n const git = spawnSync('git', ['-C', root, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' });\n const filterRoot = git.status === 0 ? git.stdout.trim() : root;\n const prefix = path.relative(filterRoot, root).split(path.sep).join('/');\n const cache = new Map<string, { base: string; rules: Ignore }[]>();\n const rulesFor = (dir: string): { base: string; rules: Ignore }[] => {\n if (cache.has(dir)) return cache.get(dir)!;\n const inherited = dir ? rulesFor(path.posix.dirname(dir) === '.' ? '' : path.posix.dirname(dir)) : [];\n let rules = inherited;\n try {\n rules = [...inherited, { base: dir, rules: ignore().add(fs.readFileSync(path.join(filterRoot, dir, '.gitignore'), 'utf8')) }];\n } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }\n cache.set(dir, rules);\n return rules;\n };\n return (name, directory) => {\n if (name.split('/').includes('.git')) return true;\n name = prefix ? prefix + '/' + name : name;\n const parent = path.posix.dirname(name);\n let ignored = false;\n for (const { base, rules } of rulesFor(parent === '.' ? '' : parent)) {\n const relative = (base ? name.slice(base.length + 1) : name) + (directory ? '/' : '');\n const result = rules.test(relative);\n if (result.ignored) ignored = true;\n if (result.unignored) ignored = false;\n }\n return ignored;\n };\n}\n\nexport async function planSync(session: SnapshotSession, source: SyncEntry[], destination: SyncEntry[], remove: boolean, excluded: (name: string, directory: boolean) => boolean = () => false): Promise<SyncPlan> {\n const difference = await session.diff(source, destination);\n const changes = new Set([...difference.added, ...difference.changed.map((e) => e.path)]);\n const deleted = new Set(difference.deleted);\n const src = new Map(source.map((e) => [e.path, e]));\n const dst = new Map(destination.map((e) => [e.path, e]));\n const copy: SyncEntry[] = [];\n for (const entry of source) {\n const previous = dst.get(entry.path);\n if (previous && previous.type !== entry.type) throw new Error(`Sync type conflict at ${entry.path}; move or remove the destination entry first.`);\n if (changes.has(entry.path) && (!previous || entry.type !== 'directory')) {\n if (previous?.links && previous.links > 1) throw new Error(`Sync cannot overwrite a hard-linked destination file: ${entry.path}. Move or unlink it first.`);\n copy.push(entry);\n }\n }\n // Never delete ignored entries or a directory containing protected children.\n const ignoredPaths = destination.filter((e) => excluded(e.path, e.type === 'directory')).map((e) => e.path);\n const protectedPaths = destination.filter((e) => e.protected || excluded(e.path, e.type === 'directory')).map((e) => e.path);\n const removed = remove ? destination.filter((e) => !e.protected && deleted.has(e.path) && !src.has(e.path) && !ignoredPaths.some((p) => e.path === p || e.path.startsWith(p + '/')) &&\n !protectedPaths.some((p) => p.startsWith(e.path + '/'))) : [];\n removed.sort((a, b) => b.path.split('/').length - a.path.split('/').length || b.path.localeCompare(a.path));\n return { copy, remove: removed };\n}\n\nfunction transferUrl(raw: string): string {\n const url = new URL(raw);\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) throw new Error('Insecure sync transfer URL.');\n return raw;\n}\nasync function download(c: ActionsClient, source: { id: string; remote: string }, target: string): Promise<string> {\n const created = await c.post<{ downloadUrl: string }>(`/api/v1/sandboxes/${source.id}/transfers`, { direction: 'download', path: source.remote });\n const response = await fetch(transferUrl(created.downloadUrl), { redirect: 'error' });\n if (!response.ok || !response.body) throw new Error(`Sync download failed (${response.status}).`);\n const file = path.join(target, 'source.tar.gz');\n await pipeline(Readable.fromWeb(response.body as Parameters<typeof Readable.fromWeb>[0]), fs.createWriteStream(file, { mode: 0o600 }));\n const wrapper = path.posix.basename(source.remote);\n const validate = (name: string, entry: { type?: string; linkpath?: string }) => {\n const parts = name.replace(/\\/$/, '').split('/');\n if (parts[0] !== wrapper || parts.some((p) => p === '..' || p === '' || p === '.') || name.includes('\\\\')) throw new Error('Unsafe sync archive entry.');\n if (parts.includes('.git')) return false;\n if (!['File', 'Directory'].includes(entry.type ?? '')) throw new Error('Unsupported sync archive entry.');\n return true;\n };\n // Validate the complete archive before writing any of its entries.\n let invalid: unknown;\n await tar.list({ file, onReadEntry: (entry) => {\n try { validate(entry.path, entry); } catch (error) { invalid = error; }\n entry.resume();\n } });\n if (invalid) throw invalid;\n const unpacked = path.join(target, 'unpacked');\n fs.mkdirSync(unpacked);\n await tar.extract({ file, cwd: unpacked, filter: (name, entry) => validate(name, entry as tar.ReadEntry), strict: true });\n return path.join(unpacked, wrapper);\n}\nasync function upload(c: ActionsClient, destination: { id: string; remote: string }, root: string, entries: SyncEntry[], temp: string): Promise<void> {\n if (!entries.length) return;\n const archive = path.join(temp, 'changes.tar.gz');\n await tar.create({ file: archive, gzip: true, cwd: root, noDirRecurse: true, portable: true }, entries.map((e) => e.path));\n const created = await c.post<{ transferId: string; uploadUrl: string }>(`/api/v1/sandboxes/${destination.id}/transfers`, { direction: 'upload', path: destination.remote });\n const response = await fetch(transferUrl(created.uploadUrl), {\n method: 'PUT', redirect: 'error', headers: { 'content-type': 'application/gzip', 'content-length': String(fs.statSync(archive).size) },\n // @ts-expect-error Node fetch accepts a web stream with duplex.\n body: Readable.toWeb(fs.createReadStream(archive)), duplex: 'half',\n });\n if (!response.ok) throw new Error(`Sync upload failed (${response.status}).`);\n await c.post(`/api/v1/sandboxes/${destination.id}/transfers/${created.transferId}/complete`, {});\n}\n\nexport async function syncOnce(c: ActionsClient, source: SyncEndpoint, destination: SyncEndpoint, opts: SyncOptions): Promise<SyncPlan> {\n if ('local' in source && 'local' in destination) throw new Error('Sync requires at least one sandbox endpoint ([id]:/path).');\n if ('id' in source && 'id' in destination && source.id.toLowerCase() === destination.id.toLowerCase() &&\n (source.remote === destination.remote || source.remote.startsWith(destination.remote + '/') || destination.remote.startsWith(source.remote + '/'))) throw new Error('Source and destination sync directories must not overlap.');\n const session = new SnapshotSession(c);\n try {\n const excluded = 'local' in source ? sourceFilter(source.local) : () => false;\n const src = await session.scan(source, false, 'local' in source ? excluded : undefined);\n const dst = await session.scan(destination, true);\n const plan = await planSync(session, src.entries, dst.entries, !!opts.delete, excluded);\n if (opts.dryRun) return plan;\n if (!plan.copy.length && !plan.remove.length) {\n await session.guard(destination, { missing: true, directories: [] });\n return plan;\n }\n if (plan.copy.length) {\n const sourceRoot = endpointRoot(source);\n const captureRoot = 'id' in source ? await session.remoteRoot(source.id) : session.temp;\n const sourceStore = path.posix.join(captureRoot, 'store');\n const checkpointId = randomUUID();\n const capture = await session.operation<CaptureResult & { missing?: string[] }>('id' in source ? source.id : undefined, 'capture', {\n checkpointId, paths: [sourceRoot, ...src.entries.filter((e) => e.type === 'directory' && !e.path.includes('/')).map((e) => path.posix.join(sourceRoot, e.path))],\n exclude: 'local' in source ? ignoredPaths(source.local, excluded) : ['**/.git', '**/.git/**'],\n store: { kind: 'fs', root: sourceStore },\n });\n if (capture.missing?.length) throw new Error('Source changed during snapshot capture.');\n if (capture.manifestKey !== `manifests/${checkpointId}.json`) throw new Error('Invalid snapshot manifest key.');\n const store = 'local' in source ? sourceStore : path.join(session.temp, 'metadata');\n if ('id' in source) {\n fs.mkdirSync(path.join(store, 'manifests'), { recursive: true });\n fs.mkdirSync(path.join(store, 'blobs'));\n const manifestText = await session.read(source.id, path.posix.join(sourceStore, capture.manifestKey));\n const metadata = JSON.parse(manifestText);\n if (!/^sha256:[a-f0-9]{64}$/.test(metadata.config?.digest)) throw new Error('Invalid snapshot config digest.');\n fs.writeFileSync(path.join(store, capture.manifestKey), manifestText);\n fs.writeFileSync(path.join(store, 'blobs', metadata.config.digest.slice(7)), await session.read(source.id, path.posix.join(sourceStore, 'blobs', metadata.config.digest.slice(7))));\n }\n plan.snapshot = await retainCapture(c, session, source, sourceStore, store, capture.manifestKey, 'id' in source ? source.id : (destination as { id: string }).id, [sourceRoot]);\n const manifest = selectSnapshot(store, capture.manifestKey, sourceRoot, plan.copy, dst, endpointRoot(destination));\n // Only the config and layers referenced by this selected OCI view travel.\n let bundle = path.join(session.temp, 'bundle');\n fs.mkdirSync(path.join(bundle, 'blobs'), { recursive: true });\n fs.mkdirSync(path.join(bundle, 'manifests'));\n const selected = JSON.parse(fs.readFileSync(path.join(store, manifest), 'utf8'));\n const refs = [selected.config, ...selected.layers] as { digest: string }[];\n const entries: SyncEntry[] = [\n { path: 'blobs', type: 'directory', mode: 0o700 }, { path: 'manifests', type: 'directory', mode: 0o700 },\n { path: manifest, type: 'file', mode: 0o600 },\n ];\n fs.copyFileSync(path.join(store, manifest), path.join(bundle, manifest));\n for (const ref of refs) {\n if (!/^sha256:[a-f0-9]{64}$/.test(ref.digest)) throw new Error('Invalid snapshot blob digest.');\n const relative = 'blobs/' + ref.digest.slice(7);\n if ('local' in source || ref === selected.config) fs.copyFileSync(path.join(store, relative), path.join(bundle, relative));\n entries.push({ path: relative, type: 'file', mode: 0o600 });\n }\n if ('id' in source) {\n const remoteBundle = path.posix.join(captureRoot, 'selected-store');\n const layers = refs.slice(1).map((ref) => ref.digest.slice(7));\n const layerList = path.posix.join(captureRoot, 'selected-layers.json');\n await session.write(source.id, layerList, JSON.stringify(layers));\n await session.command(source.id, `const fs=require('node:fs'),p=require('node:path'),dest=${JSON.stringify(remoteBundle)},src=${JSON.stringify(sourceStore)};fs.mkdirSync(p.join(dest,'blobs'),{recursive:true});fs.mkdirSync(p.join(dest,'manifests'));for(const hex of JSON.parse(fs.readFileSync(${JSON.stringify(layerList)},'utf8')))fs.copyFileSync(p.join(src,'blobs',hex),p.join(dest,'blobs',hex));`);\n await session.write(source.id, path.posix.join(remoteBundle, manifest), fs.readFileSync(path.join(bundle, manifest), 'utf8'));\n const configFile = 'blobs/' + selected.config.digest.slice(7);\n await session.write(source.id, path.posix.join(remoteBundle, configFile), fs.readFileSync(path.join(bundle, configFile), 'utf8'));\n bundle = await download(c, { id: source.id, remote: remoteBundle }, session.temp);\n }\n let restoreStore = bundle;\n if ('id' in destination) {\n restoreStore = path.posix.join(await session.remoteRoot(destination.id), 'bundle');\n await session.guard({ id: destination.id, remote: restoreStore }, { missing: true, directories: entries.filter((e) => e.type === 'directory') });\n await upload(c, { id: destination.id, remote: restoreStore }, bundle, entries, session.temp);\n }\n const current = await session.scan(destination, true);\n if (JSON.stringify(current.entries) !== JSON.stringify(dst.entries)) throw new Error('Destination changed during sync; rerun to try again.');\n await session.guard(destination, { missing: true, directories: plan.copy.filter((e) => e.type === 'directory') });\n const restored = await session.operation<{ failures: unknown[] }>('id' in destination ? destination.id : undefined, 'restore', {\n checkpointId: 'selected', manifestUrl: undefined,\n // The engine reads the selected manifest from its fs object store.\n store: { kind: 'fs', root: restoreStore }, destDir: endpointRoot(destination), strictArch: false,\n });\n if (restored.failures.length) throw new Error('Snapshot restore was incomplete.');\n }\n if (plan.remove.length) {\n // Delete only after successful capture, transfer and integrity-checked restore.\n await session.guard(destination, { remove: plan.remove });\n }\n return plan;\n } finally { await session.close(); }\n}\n\nexport function printSync(plan: SyncPlan, opts: SyncOptions): void {\n const result = { dryRun: !!opts.dryRun, copied: plan.copy.map((e) => e.path), deleted: plan.remove.map((e) => e.path), ...(plan.snapshot ? { snapshot: plan.snapshot } : {}) };\n if (opts.json) { console.log(JSON.stringify(result)); return; }\n output(opts, result, () => {\n if (opts.dryRun) {\n for (const entry of plan.copy) console.log(`copy ${safeTerm(entry.path)}`);\n for (const entry of plan.remove) console.log(`delete ${safeTerm(entry.path)}`);\n }\n if (plan.snapshot) console.log(`Snapshot ${plan.snapshot.id} retained until ${plan.snapshot.expiresAt}.`);\n console.log(`${opts.dryRun ? 'Would sync' : 'Synced'} ${plan.copy.length} entries; ${plan.remove.length} deleted${opts.dryRun ? ' (dry run)' : ''}.`);\n });\n}\nexport function registerSyncCommand(program: Command): void {\n program.command('sync <source> <destination>')\n .description('One-way directory sync: local paths or [sandbox-id]:/path (empty ID selects the current sandbox)')\n .option('--delete', 'delete destination-only entries, preserving .git and ignored local source paths')\n .option('--dry-run', 'show changes without modifying the destination')\n .option('--watch', 'repeat one-way sync every 2 seconds until interrupted')\n .option('--api-key <key>').option('--base-url <url>').option('--org <slug>').option('--allow-untrusted-host')\n .option('--json', 'print a JSON result per sync pass (JSON Lines with --watch)')\n .action(async (src: string, dst: string, opts: SyncOptions) => {\n const stop = new AbortController();\n const interrupt = () => stop.abort();\n try {\n if (opts.watch && opts.dryRun) throw new Error('--watch and --dry-run cannot be combined.');\n const source = syncEndpoint(src, opts);\n const destination = syncEndpoint(dst, opts);\n const c = await client(opts);\n if (opts.watch && !opts.json) console.error('Watching for changes (one-way sync, every 2 seconds). Press Ctrl-C to stop.');\n if (opts.watch) { process.on('SIGINT', interrupt); process.on('SIGTERM', interrupt); }\n do {\n const plan = await syncOnce(c, source, destination, opts);\n if (!opts.watch || plan.copy.length || plan.remove.length) printSync(plan, opts);\n if (!opts.watch || stop.signal.aborted) break;\n try { await delay(2000, undefined, { signal: stop.signal }); } catch { break; }\n } while (!stop.signal.aborted);\n } catch (error) { fail(error, opts); }\n finally { process.removeListener('SIGINT', interrupt); process.removeListener('SIGTERM', interrupt); }\n });\n}\n","/** Retain full project captures before applying a selected view to the destination. */\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { createRequire } from 'node:module';\nimport type { ActionsClient } from './actions-client.js';\nimport type { SnapshotSession, EngineEndpoint } from './snapshot-engine.js';\nexport interface RetainedSnapshot { id: string; expiresAt: string }\ninterface Upload { objects: { key: string; url: string }[]; manifestPutUrl: string; manifestJson: string }\n\n/** Self-contained so remote sources upload directly from their private scratch. */\nasync function publish(input: { store: string; upload: Upload; manifest: unknown }, requireModule: NodeRequire): Promise<void> {\n const fs = requireModule('node:fs') as typeof import('node:fs');\n const path = requireModule('node:path') as typeof import('node:path');\n const crypto = requireModule('node:crypto') as typeof import('node:crypto');\n const checkUrl = (value: string) => {\n const url = new URL(value);\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) throw new Error('Insecure retained snapshot upload URL.');\n };\n for (const object of input.upload.objects) {\n if (!/^blobs\\/[a-f0-9]{64}$/.test(object.key)) throw new Error('Invalid retained snapshot object key.');\n checkUrl(object.url);\n const file = path.join(input.store, object.key);\n const hash = crypto.createHash('sha256');\n for await (const chunk of fs.createReadStream(file)) hash.update(chunk);\n if (hash.digest('hex') !== object.key.slice(6)) throw new Error('Retained snapshot blob digest mismatch.');\n const response = await fetch(object.url, {\n method: 'PUT', redirect: 'error', signal: AbortSignal.timeout(290_000),\n headers: { 'content-length': String(fs.statSync(file).size) },\n // @ts-expect-error Node streams require duplex, which DOM fetch types omit.\n body: fs.createReadStream(file), duplex: 'half',\n });\n if (!response.ok) throw new Error(`Retained snapshot upload failed (${response.status}).`);\n await response.body?.cancel();\n }\n checkUrl(input.upload.manifestPutUrl);\n const response = await fetch(input.upload.manifestPutUrl, {\n method: 'PUT', redirect: 'error', signal: AbortSignal.timeout(290_000),\n headers: { 'content-type': 'application/json' }, body: input.upload.manifestJson,\n });\n if (!response.ok) throw new Error(`Retained snapshot manifest upload failed (${response.status}).`);\n await response.body?.cancel();\n}\n\nexport async function retainCapture(c: ActionsClient, session: SnapshotSession, source: EngineEndpoint, sourceStore: string, metadataStore: string, manifestKey: string, anchorId: string, paths: string[]): Promise<RetainedSnapshot> {\n const manifest = JSON.parse(fs.readFileSync(path.join(metadataStore, manifestKey), 'utf8'));\n const registered = await c.post<{ snapshot: RetainedSnapshot; upload: Upload }>(`/api/v1/sandboxes/${anchorId}/sync-snapshots`, { manifest, paths });\n const input = { store: sourceStore, upload: registered.upload, manifest };\n if ('local' in source) await publish(input, createRequire(import.meta.url));\n else {\n const payload = path.posix.join(await session.remoteRoot(source.id), 'retained-upload.json');\n await session.write(source.id, payload, JSON.stringify(input));\n await session.command(source.id, `(${publish.toString()})(JSON.parse(require('node:fs').readFileSync(${JSON.stringify(payload)},'utf8')),require).catch(e=>{console.error(e.message);process.exitCode=1})`);\n }\n const completed = await c.post<{ snapshot: RetainedSnapshot }>(`/api/v1/snapshots/${registered.snapshot.id}/sync`, {});\n return { id: completed.snapshot.id, expiresAt: completed.snapshot.expiresAt };\n}\n","import { loadCredentials } from '@benchsdk/cli';\nimport { ActionsCliError } from './actions-client.js';\nimport { client, type CommonOpts } from './actions.js';\nimport { login } from './login.js';\n\n/** Only creation may initiate login, and only before any provision request. */\nexport async function creationClient(opts: CommonOpts & { quiet?: boolean; browser?: boolean }) {\n const interactive = process.stdin.isTTY && process.stderr.isTTY && !process.env.CI && !opts.json && !opts.quiet &&\n !opts.apiKey && !process.env.COMPUTE_API_KEY && !process.env.BENCHMARKS_PLATFORM_API_KEY &&\n !process.env.BENCHMARKS_PLATFORM_TOKEN;\n // Snapshot before resolution: a legacy session resolver may clear its\n // rejected credentials. That must not turn it into a first-run login.\n const credentials = interactive ? await loadCredentials() : undefined;\n try {\n return await client(opts);\n } catch (error) {\n if (!(error instanceof ActionsCliError) || error.code !== 'no_credentials' || !interactive ||\n credentials?.token || credentials?.apiKey || credentials?.refreshToken) throw error;\n await login({ baseUrl: opts.baseUrl, browser: opts.browser, org: opts.org });\n return client(opts);\n }\n}\n","/** Browser-assisted RFC 8628 login, using the shared compute/bench session. */\nimport { createHash } from 'node:crypto';\nimport { mkdirSync, readFileSync, writeFileSync, renameSync, rmSync, readdirSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { spawn } from 'node:child_process';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport {\n BENCH_OAUTH_CLIENT_ID,\n BENCH_OAUTH_SCOPE,\n getMe,\n saveCredentials,\n setActiveOrganization,\n type CliAuth,\n} from '@benchsdk/cli';\nimport { DEFAULT_BASE_URL, isSecurePlatformTransport, isTrustedPlatformHost } from '@computesdk/platform';\nimport { envBaseUrl } from './session.js';\n\n/** No shell: a verification URL must never be interpreted as a command. */\nexport function openBrowser(url: string): Promise<boolean> {\n const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'rundll32' : 'xdg-open';\n const args = process.platform === 'win32' ? ['url.dll,FileProtocolHandler', url] : [url];\n return new Promise((resolve) => {\n const child = spawn(command, args, { stdio: 'ignore', timeout: 5000 });\n child.once('error', () => resolve(false));\n child.once('close', (code) => resolve(code === 0));\n });\n}\n\ninterface OAuthResponse {\n device_code?: string;\n user_code?: string;\n verification_uri?: string;\n verification_uri_complete?: string;\n expires_in?: number;\n interval?: number;\n access_token?: string;\n refresh_token?: string;\n error?: string;\n error_description?: string;\n}\n\nasync function postForm(url: string, params: Record<string, string>, timeoutMs = 30_000): Promise<OAuthResponse> {\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams(params),\n signal: AbortSignal.timeout(Math.max(1, Math.min(30_000, timeoutMs))),\n redirect: 'error',\n });\n const body = await response.json() as OAuthResponse;\n if (!response.ok && !body.error) throw new Error(`Sign-in failed (${response.status}). Run compute login to retry.`);\n return body;\n}\n\ninterface PendingLogin {\n baseUrl: string;\n device: OAuthResponse;\n expiresAt: number;\n}\nfunction stateDir(): string {\n return process.env.BENCHSDK_STATE_DIR ?? join(homedir(), '.benchsdk');\n}\nfunction pendingPath(baseUrl: string): string {\n return join(stateDir(), `compute-login-${createHash('sha256').update(baseUrl).digest('hex')}.json`);\n}\nfunction readPending(baseUrl: string, includeExpired = false): PendingLogin | undefined {\n try {\n const pending = JSON.parse(readFileSync(pendingPath(baseUrl), 'utf8')) as PendingLogin;\n if (pending.baseUrl === baseUrl && pending.device && Number.isFinite(pending.expiresAt) && (includeExpired || pending.expiresAt > Date.now())) return pending;\n } catch { /* no pending login */ }\n return undefined;\n}\nfunction savePending(pending: PendingLogin): void {\n mkdirSync(stateDir(), { recursive: true });\n const file = pendingPath(pending.baseUrl);\n const tmp = `${file}.${process.pid}.tmp`;\n writeFileSync(tmp, JSON.stringify(pending), { mode: 0o600 });\n renameSync(tmp, file);\n}\nfunction removePending(baseUrl: string, deviceCode: string): void {\n // A completed/denied attempt must not erase a newer login.\n if (readPending(baseUrl, true)?.device.device_code === deviceCode) rmSync(pendingPath(baseUrl), { force: true });\n}\nexport function clearPendingLogins(): void {\n let files: string[];\n try { files = readdirSync(stateDir()); } catch { return; }\n for (const file of files) {\n if (/^compute-login-[a-f0-9]{64}\\.json$/.test(file)) rmSync(join(stateDir(), file), { force: true });\n }\n}\n\nexport interface LoginOptions {\n baseUrl?: string;\n browser?: boolean;\n org?: string;\n json?: boolean;\n wait?: boolean;\n new?: boolean;\n}\n\nexport async function login(options: LoginOptions = {}): Promise<void> {\n const baseUrl = (options.baseUrl || envBaseUrl() || DEFAULT_BASE_URL).replace(/\\/+$/, '').replace(/\\/api\\/v1$/, '');\n if (!isTrustedPlatformHost(baseUrl) || !isSecurePlatformTransport(baseUrl)) {\n throw new Error('Sign in against a trusted ComputeSDK HTTPS host (or localhost for development).');\n }\n const resource = `${baseUrl}/api/v1`;\n const authUrl = `${baseUrl}/api/auth`;\n const pending = options.new ? undefined : readPending(baseUrl);\n if (options.json && options.wait && !pending) {\n throw new Error('No pending sign-in. Run compute login --json first to get the sign-in URL.');\n }\n const device = pending?.device ?? await postForm(`${authUrl}/device/code`, {\n client_id: BENCH_OAUTH_CLIENT_ID, scope: BENCH_OAUTH_SCOPE, resource,\n });\n if (device.error) throw new Error(device.error_description || device.error);\n const verificationUrl = device.verification_uri_complete || device.verification_uri;\n if (!device.device_code || !device.user_code || !verificationUrl ||\n !Number.isFinite(device.expires_in) || device.expires_in! <= 0 ||\n (device.interval !== undefined && (!Number.isFinite(device.interval) || device.interval <= 0))) {\n throw new Error('Invalid sign-in response. Run compute login to retry.');\n }\n const parsedUrl = new URL(verificationUrl);\n if (parsedUrl.origin !== new URL(baseUrl).origin || parsedUrl.username || parsedUrl.password) {\n throw new Error('The sign-in server returned an unexpected verification URL.');\n }\n const expiresAt = pending?.expiresAt ?? Date.now() + device.expires_in! * 1000;\n savePending({ baseUrl, device, expiresAt });\n if (options.json && !options.wait) {\n console.log(JSON.stringify({ verificationUrl, code: device.user_code, expiresAt: new Date(expiresAt).toISOString() }));\n return;\n }\n if (!options.json) {\n console.error(`Sign in to ComputeSDK: ${verificationUrl}`);\n console.error(`Confirm code: ${device.user_code}`);\n console.error('Waiting for approval. Press Ctrl-C to cancel.');\n if (options.browser !== false && !(await openBrowser(verificationUrl))) {\n console.error('Could not open a browser. Open the sign-in URL above to continue.');\n }\n }\n\n let intervalMs = (device.interval ?? 5) * 1000;\n while (Date.now() + intervalMs < expiresAt) {\n await delay(intervalMs);\n const token = await postForm(`${authUrl}/oauth2/token`, {\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n device_code: device.device_code, client_id: BENCH_OAUTH_CLIENT_ID, resource,\n }, expiresAt - Date.now());\n if (token.error === 'authorization_pending') continue;\n if (token.error === 'slow_down') {\n intervalMs += 5000;\n device.interval = intervalMs / 1000;\n savePending({ baseUrl, device, expiresAt });\n continue;\n }\n if (token.error === 'access_denied') {\n removePending(baseUrl, device.device_code);\n throw new Error('Sign-in was denied. Run compute login to try again.');\n }\n if (token.error === 'expired_token') break;\n if (token.error) throw new Error(token.error_description || token.error);\n if (!token.access_token || !Number.isFinite(token.expires_in) || token.expires_in! <= 0) {\n throw new Error('Invalid sign-in token response. Run compute login to retry.');\n }\n const credentials = {\n baseUrl, token: token.access_token, refreshToken: token.refresh_token,\n tokenExpiresAt: Date.now() + token.expires_in! * 1000,\n kind: 'oauth' as const, clientId: BENCH_OAUTH_CLIENT_ID,\n };\n await saveCredentials(credentials);\n removePending(baseUrl, device.device_code);\n // Approval normally binds the org server-side. Keep the shared store's\n // org cache current too, so directory-scoped sandbox selection is correct.\n // Use the token just issued, regardless of API keys in the environment.\n const auth: CliAuth = { ...credentials, apiBaseUrl: resource, authBaseUrl: authUrl };\n const me = await getMe(auth);\n const requestedOrg = options.org || process.env.COMPUTE_ORG;\n const override = requestedOrg ? me.organizations.find((o) => o.slug === requestedOrg) : undefined;\n if (requestedOrg && !override) {\n throw new Error(`Signed in, but not a member of organization ${requestedOrg}. Run compute org list.`);\n }\n let active = me.organizations.find((o) => o.id === me.activeOrganizationId);\n if (!me.activeOrganizationId && me.organizations.length === 1) {\n active = (await setActiveOrganization(auth, me.organizations[0].slug)).organization ?? undefined;\n }\n const effective = override ?? active;\n if (!effective) throw new Error('Signed in, but no active organization. Run compute org list, then compute org use <slug>.');\n // A one-off override must not change the server's shared active org or\n // cache it as the default for subsequent commands on this machine.\n await saveCredentials({\n ...credentials, ...(active ? { orgSlug: active.slug, orgId: active.id } : {}),\n });\n if (options.json) console.log(JSON.stringify({ signedIn: true, organization: effective.slug }));\n else console.error(`Signed in. ${override ? 'Using' : 'Active'} organization: ${effective.slug}.`);\n return;\n }\n removePending(baseUrl, device.device_code);\n throw new Error('Sign-in code expired. Run compute login to get a new code.');\n}\n","/**\n * The stored-login session behind `compute login`, `whoami` and `org …`,\n * resolved through `@benchsdk/cli` (shared `~/.benchsdk/credentials.json`).\n * That package reads only bench's env names, so compute's are passed in as\n * explicit overrides here.\n */\n\nimport type { CliAuth } from '@benchsdk/cli';\nimport { DEFAULT_BASE_URL, isSecurePlatformTransport, isTrustedPlatformHost } from '@computesdk/platform';\nimport { describeFetchFailure, isFetchFailure } from './net.js';\n\nexport function envBaseUrl(env: NodeJS.ProcessEnv = process.env): string | undefined {\n return env.COMPUTE_PLATFORM_URL || env.BENCHMARKS_PLATFORM_URL || undefined;\n}\n\n/**\n * `@benchsdk/cli` doesn't check where it sends a key, so compute applies its\n * own rule before handing COMPUTE_API_KEY over (as `resolvePlatformAuth`\n * does for every other command): a computesdk.com or loopback host, over\n * HTTPS off loopback. A key the user gives bench directly\n * (BENCHMARKS_PLATFORM_API_KEY) is bench's business and isn't checked here.\n */\nexport function assertComputeKeyDestination(baseUrl: string): void {\n const url = baseUrl.replace(/\\/+$/, '');\n if (!isTrustedPlatformHost(url)) {\n throw new Error(\n `Refusing to send COMPUTE_API_KEY to ${url}: it is not a computesdk.com or localhost host. ` +\n 'To use a key with a host you trust, set BENCHMARKS_PLATFORM_API_KEY for it instead.',\n );\n }\n if (!isSecurePlatformTransport(url)) {\n throw new Error(`Refusing to send COMPUTE_API_KEY over plaintext HTTP to ${url}; use https://.`);\n }\n}\n\n/**\n * `@benchsdk/cli` `resolveAuth` overrides. COMPUTE_API_KEY goes in as an\n * explicit key, so it wins over the stored login (as for every other compute\n * command), but only to a host compute itself would send it to;\n * BENCHMARKS_PLATFORM_API_KEY still works through bench's own env.\n */\nexport function benchAuthOverrides(\n opts: { baseUrl?: string } = {},\n env: NodeJS.ProcessEnv = process.env,\n): { baseUrl?: string; apiKey?: string } {\n const baseUrl = opts.baseUrl ?? envBaseUrl(env);\n const apiKey = env.COMPUTE_API_KEY || undefined;\n if (apiKey) assertComputeKeyDestination(baseUrl ?? DEFAULT_BASE_URL);\n return { baseUrl, apiKey };\n}\n\nexport async function benchAuth(opts: { baseUrl?: string } = {}): Promise<CliAuth> {\n const { resolveAuth } = await import('@benchsdk/cli');\n return resolveAuth(benchAuthOverrides(opts));\n}\n\nexport interface Organization {\n id: string;\n name: string;\n slug: string;\n}\n\n/** `GET /api/v1/me`, or for an org API key (no user) the key's org. */\nexport interface Whoami {\n user: { id: string; name?: string | null; email?: string | null } | null;\n activeOrganizationId: string | null;\n organizations: Organization[];\n credential?: 'api_key';\n}\n\nfunction errorReason(body: unknown): string | undefined {\n if (typeof body !== 'string' || body === '') return undefined;\n try {\n const parsed = JSON.parse(body) as { message?: unknown; error?: unknown };\n const reason = parsed.message ?? parsed.error;\n return typeof reason === 'string' ? reason : undefined;\n } catch {\n return body.slice(0, 200);\n }\n}\n\nfunction httpStatus(error: unknown): number | undefined {\n const status = (error as { status?: unknown } | null)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n/**\n * Org API keys carry no user, so `/api/v1/me` answers them 401 \"User\n * credential required\"; `/api/v1/actions/org` is the v1 route that names the\n * org a key belongs to.\n */\nasync function apiKeyOrganization(auth: CliAuth, apiKey: string): Promise<Organization> {\n const url = `${auth.apiBaseUrl}/actions/org`;\n let response: Response;\n try {\n response = await fetch(url, { headers: { Authorization: `Bearer ${apiKey}` } });\n } catch (error) {\n throw isFetchFailure(error) ? describeFetchFailure(error, url) : error;\n }\n const text = await response.text();\n if (!response.ok) {\n const reason = errorReason(text);\n throw new Error(\n `This API key has no user identity, and its organization could not be read (${response.status}${reason ? `: ${reason}` : ''}).`,\n );\n }\n const org = JSON.parse(text) as { organizationId: string; name: string; slug: string };\n return { id: org.organizationId, name: org.name, slug: org.slug };\n}\n\nexport async function fetchWhoami(auth: CliAuth): Promise<Whoami> {\n const { getMe } = await import('@benchsdk/cli');\n try {\n return await getMe(auth);\n } catch (error) {\n if (isFetchFailure(error)) throw describeFetchFailure(error, `${auth.apiBaseUrl}/me`);\n if (httpStatus(error) !== 401) throw error;\n const reason = errorReason((error as { body?: unknown }).body);\n if (auth.apiKey && !auth.token && reason === 'User credential required') {\n const org = await apiKeyOrganization(auth, auth.apiKey);\n return { user: null, activeOrganizationId: org.id, organizations: [org], credential: 'api_key' };\n }\n throw new Error(\n `Authentication failed (401 Unauthorized)${reason ? `: ${reason}` : ''}. ` +\n 'Check COMPUTE_API_KEY / the stored login, or run `compute login`.',\n );\n }\n}\n\nexport function formatWhoami(me: Whoami): string[] {\n const active = me.organizations.find((o) => o.id === me.activeOrganizationId);\n const who = me.user ? (me.user.email ?? me.user.name ?? me.user.id) : 'API key (no user identity)';\n return [\n who,\n `active org: ${active ? `${active.slug} (${active.id})` : '—'}${me.organizations.length > 1 ? ' — change with `compute org use <slug>`' : ''}`,\n ];\n}\n","/**\n * Node's fetch rejects a refused or unresolvable connection with a bare\n * `TypeError: fetch failed` (the socket error is only on `cause`), which\n * `@benchsdk/cli` prints as-is. These helpers name the URL and the cause.\n */\n\nexport function isFetchFailure(error: unknown): error is TypeError {\n return error instanceof TypeError && /fetch failed/i.test(error.message);\n}\n\nexport function describeFetchFailure(error: TypeError, url: string): TypeError {\n let target = url;\n try {\n const parsed = new URL(url);\n target = `${parsed.origin}${parsed.pathname}`;\n } catch {\n // keep the raw string\n }\n const cause = (error as { cause?: unknown }).cause;\n const described = new TypeError(`fetch failed (${target})${cause instanceof Error ? `: ${cause.message}` : ''}`);\n (described as { cause?: unknown }).cause = cause;\n return described;\n}\n\nfunction requestUrl(input: Parameters<typeof fetch>[0]): string {\n if (typeof input === 'string') return input;\n if (input instanceof URL) return input.href;\n return input.url;\n}\n\nexport function withFetchFailureContext(fetchImpl: typeof fetch): typeof fetch {\n return async (input, init) => {\n try {\n return await fetchImpl(input, init);\n } catch (error) {\n if (isFetchFailure(error)) throw describeFetchFailure(error, requestUrl(input));\n throw error;\n }\n };\n}\n","/**\n * `compute agents` — managed agents on the platform's `/api/v1/agents` API:\n * an agent is a durable config (name, prompt, harness, model, secrets,\n * provider order, volume); a session is one routed sandbox running it.\n *\n * Auth: identical to `compute actions`/`compute sandboxes` — --api-key /\n * COMPUTE_API_KEY / the stored `compute login` session. Types mirror the wire\n * shapes in benchmarks-platform `lib/agents/types.ts` — keep them in sync by\n * hand; the API is the contract.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { readFileSync } from 'node:fs';\nimport { client, fail, output, safeTerm, usageErrorOutput, type CommonOpts } from './actions.js';\n\n// ─── Wire types (mirror benchmarks-platform lib/agents/types.ts) ────────────\n\nexport type AgentHarness = 'pi' | 'opencode';\nexport type AgentSessionStatus = 'starting' | 'running' | 'stopped' | 'failed';\nexport type AgentEventKind = 'user' | 'turn' | 'status' | 'error';\n\nexport interface AgentVolume {\n diskId?: string;\n path?: string;\n bucket?: string;\n prefix?: string;\n region?: string;\n managed?: boolean;\n}\n\nexport interface AgentSummary {\n id: string;\n name: string;\n harness: AgentHarness;\n model: string | null;\n secrets: string[];\n providerOrder: string[] | null;\n volume: AgentVolume | null;\n sessionCount: number;\n createdAt: string;\n}\n\nexport interface AgentSessionSummary {\n id: string;\n agentId: string;\n status: AgentSessionStatus;\n sandboxId: string | null;\n error: string | null;\n createdAt: string;\n stoppedAt: string | null;\n}\n\nexport interface AgentEventView {\n seq: number;\n kind: AgentEventKind;\n payload: unknown;\n createdAt: string;\n}\n\n// ─── Rendering ───────────────────────────────────────────────────────────────\n\nfunction formatLocalTime(iso: string | null): string {\n if (iso === null) return '—';\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) return iso;\n const p = (n: number) => String(n).padStart(2, '0');\n return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;\n}\n\nfunction printAgent(a: AgentSummary): void {\n console.log(\n `${pc.cyan(safeTerm(a.name))} ${a.id.slice(0, 8)} ${a.harness}${a.model ? ` ${safeTerm(a.model)}` : ''} sessions: ${a.sessionCount} created: ${formatLocalTime(a.createdAt)}`,\n );\n}\n\nfunction printAgentDetail(a: AgentSummary): void {\n printAgent(a);\n if (a.providerOrder) console.log(` order: ${safeTerm(a.providerOrder.join(', '))}`);\n if (a.secrets.length > 0) console.log(` secrets: ${safeTerm(a.secrets.join(', '))}`);\n if (a.volume) console.log(` volume: ${a.volume.diskId ?? '—'} at ${a.volume.path ?? '—'}`);\n}\n\nfunction printSession(s: AgentSessionSummary): void {\n // Full session id — `send`, `events` and `stop` all take it as an argument.\n console.log(\n `${pc.cyan(s.id)} ${s.status} sandbox: ${s.sandboxId ?? '—'} ${formatLocalTime(s.createdAt)}${s.error ? ` ${pc.red(safeTerm(s.error))}` : ''}`,\n );\n}\n\n/** One journal line: who spoke and what the turn produced. */\nfunction printEvent(e: AgentEventView): void {\n const payload = (e.payload ?? {}) as Record<string, unknown>;\n if (e.kind === 'user') {\n console.log(`${pc.green('you')} #${e.seq} ${safeTerm(String(payload.message ?? ''))}`);\n return;\n }\n if (e.kind === 'turn') {\n const events = Array.isArray(payload.events) ? payload.events : [payload];\n for (const ev of events) {\n const o = ev as Record<string, unknown>;\n const text = o.text ?? o.message ?? o.content;\n if (typeof text === 'string') console.log(pc.dim(`#${e.seq}`) + ` ${safeTerm(text)}`);\n else console.log(pc.dim(`#${e.seq} ${safeTerm(JSON.stringify(o))}`));\n }\n return;\n }\n console.log(pc.dim(`#${e.seq} ${e.kind} ${safeTerm(JSON.stringify(payload))}`));\n}\n\nfunction authOpts(cmd: Command): Command {\n return cmd\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('--org <slug>', 'organization slug (or COMPUTE_ORG)')\n .option('--json', 'print the raw response');\n}\n\n// ─── Commands ────────────────────────────────────────────────────────────────\n\nexport function registerAgentsCommands(program: Command): void {\n const cmd = program\n .command('agents')\n .alias('ag')\n .description('Managed agents: durable agent configs running sessions in routed sandboxes')\n .enablePositionalOptions()\n .configureOutput({ outputError: usageErrorOutput });\n\n authOpts(cmd.command('list').alias('ls').description('List agents')).action(\n async (opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const agents: AgentSummary[] = [];\n let cursor: string | undefined;\n for (;;) {\n const res = await c.get<{ agents: AgentSummary[]; nextCursor: string | null }>(\n '/api/v1/agents',\n { cursor },\n );\n agents.push(...res.agents);\n if (res.nextCursor === null) break;\n cursor = res.nextCursor;\n }\n output(opts, { agents }, (r) => {\n if (r.agents.length === 0) console.log('No agents yet — `compute agents create`.');\n for (const a of r.agents) printAgent(a);\n });\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd\n .command('create <name>')\n .description('Create an agent (prompt via --prompt or --prompt-file)')\n .option('--prompt <text>', 'the agent\\'s mission / system prompt')\n .option('--prompt-file <path>', 'read the prompt from a file')\n .option('--harness <harness>', 'pi or opencode (default pi)')\n .option('--model <model>', 'model id passed to the harness')\n .option('--secret <name...>', 'vault secret names to inject')\n .option('--order <providers>', 'provider order, comma-separated')\n .option('--volume-disk <diskId>', 'Archil disk id to mount at --volume-path')\n .option('--volume-path <path>', 'volume mount path (default /agent)'),\n ).action(\n async (\n name: string,\n opts: CommonOpts & {\n prompt?: string;\n promptFile?: string;\n harness?: string;\n model?: string;\n secret?: string[];\n order?: string;\n volumeDisk?: string;\n volumePath?: string;\n },\n ) => {\n try {\n const prompt = opts.prompt ?? (opts.promptFile ? readFileSync(opts.promptFile, 'utf8') : undefined);\n if (!prompt?.trim()) fail(new Error('--prompt or --prompt-file is required'), opts);\n const volume =\n opts.volumeDisk !== undefined || opts.volumePath !== undefined\n ? { diskId: opts.volumeDisk, path: opts.volumePath }\n : undefined;\n const c = await client(opts);\n const res = await c.post<{ agent: AgentSummary }>('/api/v1/agents', {\n name,\n prompt,\n harness: opts.harness,\n model: opts.model,\n secrets: opts.secret,\n providerOrder: opts.order?.split(',').map((s) => s.trim()).filter(Boolean),\n volume,\n });\n output(opts, res, (r) => {\n printAgentDetail(r.agent);\n console.error(pc.dim(`agent ${r.agent.name} created — run it with \\`compute agents run ${r.agent.name} \"…\"\\``));\n });\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(cmd.command('describe <ref>').alias('get').description('Show one agent (id or name)')).action(\n async (ref: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ agent: AgentSummary }>(`/api/v1/agents/${encodeURIComponent(ref)}`);\n output(opts, res, (r) => printAgentDetail(r.agent));\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd\n .command('update <ref>')\n .description('Update an agent\\'s config')\n .option('--name <name>')\n .option('--prompt <text>')\n .option('--prompt-file <path>')\n .option('--harness <harness>')\n .option('--model <model>')\n .option('--secret <name...>')\n .option('--clear-secrets', 'remove all declared vault secrets')\n .option('--order <providers>')\n .option('--volume-disk <diskId>')\n .option('--volume-path <path>'),\n ).action(\n async (\n ref: string,\n opts: CommonOpts & {\n name?: string;\n prompt?: string;\n promptFile?: string;\n harness?: string;\n model?: string;\n secret?: string[];\n clearSecrets?: boolean;\n order?: string;\n volumeDisk?: string;\n volumePath?: string;\n },\n ) => {\n try {\n const prompt = opts.prompt ?? (opts.promptFile ? readFileSync(opts.promptFile, 'utf8') : undefined);\n const body: Record<string, unknown> = {\n name: opts.name,\n prompt,\n harness: opts.harness,\n model: opts.model,\n secrets: opts.clearSecrets ? [] : opts.secret,\n providerOrder: opts.order?.split(',').map((s) => s.trim()).filter(Boolean),\n };\n if (opts.volumeDisk !== undefined || opts.volumePath !== undefined) {\n body.volume = { diskId: opts.volumeDisk, path: opts.volumePath };\n }\n for (const k of Object.keys(body)) if (body[k] === undefined) delete body[k];\n const c = await client(opts);\n const res = await c.patch<{ agent: AgentSummary }>(\n `/api/v1/agents/${encodeURIComponent(ref)}`,\n body,\n );\n output(opts, res, (r) => printAgentDetail(r.agent));\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd\n .command('delete <ref>')\n .alias('rm')\n .description('Delete an agent and stop its live sessions')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (ref: string, opts: CommonOpts & { yes?: boolean }) => {\n try {\n const c = await client(opts);\n if (!opts.yes) {\n const res = await c.get<{ agent: AgentSummary }>(`/api/v1/agents/${encodeURIComponent(ref)}`);\n console.error(`Deleting agent ${pc.cyan(res.agent.name)} (${res.agent.id}). Pass -y to confirm.`);\n process.exit(1);\n }\n await c.del(`/api/v1/agents/${encodeURIComponent(ref)}`);\n output(opts, { deleted: ref }, () => console.log(`deleted ${ref}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n authOpts(cmd.command('sessions <ref>').description('List an agent\\'s sessions')).action(\n async (ref: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ sessions: AgentSessionSummary[] }>(\n `/api/v1/agents/${encodeURIComponent(ref)}/sessions`,\n );\n output(opts, res, (r) => {\n if (r.sessions.length === 0) console.log('No sessions yet.');\n for (const s of r.sessions) printSession(s);\n });\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd\n .command('run <ref> [message]')\n .description('Start a session on a routed sandbox and optionally send a first message')\n .option('--resume <sessionId>', 'resume a stopped conversation on a new sandbox using its persistent disk')\n .option('--size <size>', 'platform size for the session\\'s sandbox'),\n ).action(async (ref: string, message: string | undefined, opts: CommonOpts & { size?: string; resume?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ session: AgentSessionSummary; events: AgentEventView[] }>(\n `/api/v1/agents/${encodeURIComponent(ref)}/sessions`,\n { message, size: opts.size, resumeSessionId: opts.resume },\n );\n output(opts, res, (r) => {\n printSession(r.session);\n for (const e of r.events) printEvent(e);\n console.error(pc.dim(`session ${r.session.id} — continue with \\`compute agents send ${r.session.id} \"…\"\\``));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n authOpts(cmd.command('session <sessionId>').description('Show one session')).action(\n async (sessionId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ session: AgentSessionSummary }>(\n `/api/v1/agent-sessions/${encodeURIComponent(sessionId)}`,\n );\n output(opts, res, (r) => printSession(r.session));\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd.command('send <sessionId> <message>').description('Send a message; the agent runs a turn'),\n ).action(async (sessionId: string, message: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ events: AgentEventView[] }>(\n `/api/v1/agent-sessions/${encodeURIComponent(sessionId)}/events`,\n { message },\n );\n output(opts, res, (r) => {\n for (const e of r.events) printEvent(e);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n authOpts(\n cmd\n .command('events <sessionId>')\n .description('Show the session event journal; --follow polls for new events')\n .option('--after <seq>', 'only events above this seq')\n .option('--follow', 'poll every 2s until the session settles or Ctrl-C'),\n ).action(\n async (sessionId: string, opts: CommonOpts & { after?: string; follow?: boolean }) => {\n try {\n const c = await client(opts);\n let after = opts.after !== undefined ? Number(opts.after) : undefined;\n const once = async (): Promise<number> => {\n const res = await c.get<{ events: AgentEventView[]; latestSeq: number }>(\n `/api/v1/agent-sessions/${encodeURIComponent(sessionId)}/events`,\n { after: after !== undefined ? String(after) : undefined },\n );\n if (opts.json) {\n output(opts, res, () => {});\n } else {\n for (const e of res.events) printEvent(e);\n }\n after = res.latestSeq;\n return res.events.length;\n };\n if (!opts.follow) {\n await once();\n return;\n }\n // Polling for v1 — SSE replaces this when the API grows a stream.\n for (;;) {\n const status = (\n await c.get<{ session: AgentSessionSummary }>(\n `/api/v1/agent-sessions/${encodeURIComponent(sessionId)}`,\n )\n ).session.status;\n await once();\n if (status !== 'running' && status !== 'starting') break;\n await new Promise((r) => setTimeout(r, 2000));\n }\n } catch (e) {\n fail(e, opts);\n }\n },\n );\n\n authOpts(\n cmd.command('stop <sessionId>').description('Stop a session and release its sandbox'),\n ).action(async (sessionId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n await c.del(`/api/v1/agent-sessions/${encodeURIComponent(sessionId)}`);\n output(opts, { stopped: sessionId }, () => console.log(`stopped ${sessionId}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/** Read-only diagnostics using the same credentials and org routing as commands. */\nimport { Command } from 'commander';\nimport type { SandboxSummary } from '@computesdk/platform';\nimport { client, output, safeTerm, type CommonOpts } from './actions.js';\nimport { resolveInstanceId } from './current-instance.js';\nimport type { ActionsOrg } from './actions-client.js';\nimport type { MarketCreditBalance } from './market.js';\n\nexport interface ComputeStatus {\n authenticated: boolean;\n ready: boolean;\n organization: ActionsOrg | null;\n credits: { balanceUsd: number; heldUsd: number } | null;\n sandbox: { id: string; status: string; provider: string | null } | null;\n routing: { ready: boolean; reason?: string } | null;\n issues: string[];\n}\nconst message = (error: unknown) => error instanceof Error ? error.message : String(error);\n\nexport async function getStatus(opts: CommonOpts): Promise<ComputeStatus> {\n const status: ComputeStatus = {\n authenticated: false, ready: false, organization: null, credits: null,\n sandbox: null, routing: null, issues: [],\n };\n try {\n const c = await client(opts);\n const selected = resolveInstanceId(undefined, opts);\n // Partial service failures should leave the other diagnostics visible.\n const [org, balance, route, sandbox] = await Promise.allSettled([\n c.org(),\n c.get<MarketCreditBalance>('/api/v1/billing/balance'),\n c.get<{ quote: { ok: boolean; reason?: string } }>('/api/v1/sandboxes/quote'),\n selected ? c.get<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${selected.id}`) : Promise.resolve(null),\n ]);\n if (org.status === 'fulfilled') {\n status.authenticated = true;\n status.organization = org.value;\n } else status.issues.push(`Authentication / organization: ${message(org.reason)}`);\n if (balance.status === 'fulfilled') {\n status.credits = { balanceUsd: balance.value.balanceMicroUsd / 1e6, heldUsd: balance.value.heldMicroUsd / 1e6 };\n } else status.issues.push(`Credits: ${message(balance.reason)}`);\n if (route.status === 'fulfilled') {\n status.routing = { ready: route.value.quote.ok, ...(route.value.quote.reason ? { reason: route.value.quote.reason } : {}) };\n } else status.issues.push(`Routing: ${message(route.reason)}`);\n if (sandbox.status === 'fulfilled' && sandbox.value) {\n const s = sandbox.value.sandbox;\n status.sandbox = { id: s.id, status: s.status, provider: s.provider };\n } else if (sandbox.status === 'rejected') {\n status.sandbox = { id: selected!.id, status: 'unknown', provider: null };\n status.issues.push(`Selected sandbox: ${message(sandbox.reason)}`);\n }\n status.ready = status.authenticated && status.routing?.ready === true;\n } catch (error) {\n status.issues.push(message(error));\n }\n return status;\n}\n\nexport function registerStatusCommand(program: Command): void {\n program.command('status')\n .description('Show authentication, effective organization, credits, selected sandbox and routing readiness')\n .option('--api-key <key>').option('--base-url <url>').option('--org <slug>')\n .option('--allow-untrusted-host')\n .option('--json', 'print machine-readable JSON')\n .option('--check', 'exit 1 unless authenticated and the default sandbox route is ready')\n .action(async (opts: CommonOpts & { check?: boolean }) => {\n const status = await getStatus(opts);\n output(opts, status, (s) => {\n console.log(`Authentication: ${s.authenticated ? 'verified' : 'not verified — run compute login'}`);\n console.log(`Organization: ${safeTerm(s.organization?.slug ?? 'unavailable')}`);\n console.log(`Credits: ${s.credits ? `$${s.credits.balanceUsd.toFixed(2)} ($${s.credits.heldUsd.toFixed(2)} held)` : 'unavailable'}`);\n console.log(`Sandbox: ${s.sandbox ? safeTerm(`${s.sandbox.id} · ${s.sandbox.status} · ${s.sandbox.provider ?? 'unknown provider'}`) : 'none selected — run compute new'}`);\n console.log(`Routing: ${s.routing ? s.routing.ready ? 'ready' : safeTerm(s.routing.reason ?? 'unavailable') : 'unavailable'}`);\n for (const issue of s.issues) console.log(safeTerm(issue));\n });\n if (opts.check && !status.ready) process.exitCode = 1;\n });\n}\n","/**\n * `compute bench …` — the benchmarks CLI (`@benchsdk/runner`'s `bench`\n * binary) run in-process. compute's env names and `--org` are mapped onto the\n * names bench reads, so `compute bench` talks to the same platform, with the\n * same key and org, as the rest of `compute`.\n */\n\nimport { DEFAULT_BASE_URL } from '@computesdk/platform';\nimport { withFetchFailureContext } from './net.js';\nimport { assertComputeKeyDestination } from './session.js';\n\n/** The canonical name first; the rest are dispatch aliases. */\nexport const BENCH_COMMANDS = new Set(['bench', 'benchmark']);\n\n/** Verbs `@benchsdk/runner` parses itself; its parser has no `--org`. */\nconst RUNNER_VERBS = new Set(['run', 'check', '__manifest']);\n\n/**\n * `args` is `process.argv.slice(2)`. Returns the bench argv when the\n * invocation is `compute [--org <slug>] bench …`; anything else is left to\n * commander.\n */\nexport function parseBenchDispatch(args: string[]): { argv: string[]; org?: string } | null {\n let org: string | undefined;\n let i = 0;\n while (i < args.length && !BENCH_COMMANDS.has(args[i])) {\n const arg = args[i];\n if (arg === '--org' && i + 1 < args.length) {\n org = args[i + 1];\n i += 2;\n } else if (arg.startsWith('--org=')) {\n org = arg.slice('--org='.length);\n i += 1;\n } else {\n return null;\n }\n }\n if (i >= args.length) return null;\n const argv = args.slice(i + 1);\n return org ? { argv, org } : { argv };\n}\n\n/** bench's own `--base-url <url>` / `--base-url=<url>`, which wins over its env. */\nfunction baseUrlFlag(argv: string[]): string | undefined {\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i];\n if (arg === '--') return undefined;\n if (arg === '--base-url') return argv[i + 1];\n if (arg.startsWith('--base-url=')) return arg.slice('--base-url='.length);\n }\n return undefined;\n}\n\nfunction hasOrgFlag(argv: string[]): boolean {\n for (const arg of argv) {\n if (arg === '--') return false;\n if (arg === '--org' || arg.startsWith('--org=')) return true;\n }\n return false;\n}\n\n/**\n * Maps compute's env names onto bench's without overriding settings bench\n * already has: COMPUTE_PLATFORM_URL → BENCHMARKS_PLATFORM_URL,\n * COMPUTE_API_KEY → BENCHMARKS_PLATFORM_API_KEY, and the org (compute's\n * leading `--org`, else COMPUTE_ORG) → a leading `--org` unless bench's argv\n * already has one. Empty variables count as unset. COMPUTE_API_KEY is only\n * handed over for a host compute would send it to (bench checks none): the\n * URL bench will use — its `--base-url`, else BENCHMARKS_PLATFORM_URL, else\n * COMPUTE_PLATFORM_URL — must be computesdk.com or loopback, over HTTPS.\n */\nexport function benchInvocation(\n argv: string[],\n env: NodeJS.ProcessEnv,\n computeOrg?: string,\n): { argv: string[]; env: Record<string, string> } {\n const out: Record<string, string> = {};\n if (env.COMPUTE_PLATFORM_URL && !env.BENCHMARKS_PLATFORM_URL) {\n out.BENCHMARKS_PLATFORM_URL = env.COMPUTE_PLATFORM_URL;\n }\n if (env.COMPUTE_API_KEY && !env.BENCHMARKS_PLATFORM_API_KEY) {\n assertComputeKeyDestination(\n baseUrlFlag(argv) || env.BENCHMARKS_PLATFORM_URL || env.COMPUTE_PLATFORM_URL || DEFAULT_BASE_URL,\n );\n out.BENCHMARKS_PLATFORM_API_KEY = env.COMPUTE_API_KEY;\n }\n const org = computeOrg || env.COMPUTE_ORG;\n if (!org || RUNNER_VERBS.has(argv[0]) || hasOrgFlag(argv)) return { argv, env: out };\n return { argv: ['--org', org, ...argv], env: out };\n}\n\n/** Runs bench; the runner exits the process itself once the command is done. */\nexport async function runBench(dispatch: { argv: string[]; org?: string }): Promise<void> {\n const inv = benchInvocation(dispatch.argv, process.env, dispatch.org);\n Object.assign(process.env, inv.env);\n globalThis.fetch = withFetchFailureContext(globalThis.fetch);\n const { run } = await import('@benchsdk/runner');\n await run(inv.argv);\n}\n","/**\n * `compute __manifest` — the command tree of the `compute` binary as JSON, in\n * the schema shared with `bench __manifest`. The benchmarks platform vendors\n * it to check that the commands its API surface map names really exist.\n * `bench …` is recorded as a passthrough by the bench versions compute\n * bundles; the bench manifest describes those commands.\n */\n\nimport type { Command, Option } from 'commander';\nimport { createRequire } from 'module';\nimport { existsSync, readFileSync, realpathSync } from 'fs';\nimport { dirname, join, sep } from 'path';\nimport { BENCH_COMMANDS } from './bench.js';\n\nexport const MANIFEST_COMMAND = '__manifest';\n\nexport interface ManifestCommand {\n path: string[];\n /** Every other spelling of `path` that commander accepts (aliases at any level). */\n aliases: string[][];\n args: string[];\n flags: string[];\n summary: string;\n}\n\nexport interface PackageVersion {\n package: string;\n version: string;\n /**\n * Set when the package resolves to a checkout (a `link:` override to a\n * branch build) rather than an npm install: its version number may not be\n * published, or may predate the commands it carries.\n */\n linked?: true;\n released?: false;\n}\n\nexport interface CliManifest {\n schemaVersion: 1;\n bin: 'compute';\n package: '@computesdk/cli';\n version: string;\n source: { repo: 'computesdk/computesdk'; released: boolean };\n globalFlags: string[];\n commands: ManifestCommand[];\n passthrough: {\n bench: { path: string[]; aliases: string[][]; runner: PackageVersion; cli: PackageVersion };\n };\n}\n\n/**\n * Version of `name` as resolved from `fromDir`. Walks up from the resolved\n * entry because the bench packages' `exports` maps hide `./package.json`.\n */\nexport function resolvedPackage(name: string, fromDir: string): { dir: string; version: string } {\n const require = createRequire(join(fromDir, 'noop.js'));\n let dir = dirname(require.resolve(name));\n for (;;) {\n const file = join(dir, 'package.json');\n if (existsSync(file)) {\n const pkg = JSON.parse(readFileSync(file, 'utf-8')) as { name?: string; version: string };\n if (pkg.name === name) return { dir, version: pkg.version };\n }\n const parent = dirname(dir);\n if (parent === dir) throw new Error(`package.json for ${name} not found from ${fromDir}`);\n dir = parent;\n }\n}\n\n/** An installed package's real path always runs through node_modules; a linked checkout's does not. */\nexport function isLinkedPackage(realDir: string): boolean {\n return !realDir.split(sep).includes('node_modules');\n}\n\nfunction packageVersion(name: string, resolved: { dir: string; version: string }): PackageVersion {\n const entry: PackageVersion = { package: name, version: resolved.version };\n if (isLinkedPackage(realpathSync(resolved.dir))) {\n entry.linked = true;\n entry.released = false;\n }\n return entry;\n}\n\n/** The bench versions `compute bench` runs: the runner, and the @benchsdk/cli the runner itself loads. */\nexport function bundledBench(fromDir: string): { runner: PackageVersion; cli: PackageVersion } {\n const runner = resolvedPackage('@benchsdk/runner', fromDir);\n const cli = resolvedPackage('@benchsdk/cli', runner.dir);\n return {\n runner: packageVersion('@benchsdk/runner', runner),\n cli: packageVersion('@benchsdk/cli', cli),\n };\n}\n\n// commander 11 has no public accessor for `{ hidden: true }` on commands.\nfunction isHidden(cmd: Command): boolean {\n return (cmd as unknown as { _hidden?: boolean })._hidden === true;\n}\n\nfunction flagsOf(cmd: Command): string[] {\n const flags = cmd\n .createHelp()\n .visibleOptions(cmd)\n .map((o: Option) => o.long ?? o.short)\n .filter((f): f is string => Boolean(f));\n return [...new Set(flags)];\n}\n\nfunction argsOf(cmd: Command): string[] {\n return cmd.registeredArguments.map((a) => {\n const name = `${a.name()}${a.variadic ? '...' : ''}`;\n return a.required ? `<${name}>` : `[${name}]`;\n });\n}\n\nfunction summaryOf(cmd: Command): string {\n return (cmd.summary() || cmd.description()).split('\\n')[0].trim();\n}\n\n/** Every combination of names along the path, minus the canonical one. */\nfunction aliasPaths(names: string[][]): string[][] {\n let paths: string[][] = [[]];\n for (const choices of names) paths = paths.flatMap((p) => choices.map((c) => [...p, c]));\n return paths.slice(1);\n}\n\nfunction walk(cmd: Command, ancestors: string[][], skip: Set<string>, out: ManifestCommand[]): void {\n for (const sub of cmd.commands) {\n if (isHidden(sub) || (ancestors.length === 0 && skip.has(sub.name()))) continue;\n const names = [...ancestors, [sub.name(), ...sub.aliases()]];\n out.push({\n path: names.map((n) => n[0]),\n aliases: aliasPaths(names),\n args: argsOf(sub),\n flags: flagsOf(sub),\n summary: summaryOf(sub),\n });\n walk(sub, names, skip, out);\n }\n}\n\nexport function buildCliManifest(\n program: Command,\n options: { version: string; released: boolean; packageDir: string },\n): CliManifest {\n const [benchName, ...benchAliases] = [...BENCH_COMMANDS];\n const commands: ManifestCommand[] = [];\n walk(program, [], new Set([benchName]), commands);\n return {\n schemaVersion: 1,\n bin: 'compute',\n package: '@computesdk/cli',\n version: options.version,\n source: { repo: 'computesdk/computesdk', released: options.released },\n globalFlags: flagsOf(program),\n commands,\n passthrough: {\n bench: {\n path: [benchName],\n aliases: benchAliases.map((a) => [a]),\n ...bundledBench(options.packageDir),\n },\n },\n };\n}\n\nexport function manifestJson(manifest: CliManifest): string {\n return `${JSON.stringify(manifest, null, 2)}\\n`;\n}\n\n/**\n * Compares a manifest file with the generated one. A `source.ref` stamped by\n * whoever vendored the file is ignored.\n */\nexport function manifestMatches(fileContent: string, generated: CliManifest): boolean {\n let committed: { source?: Record<string, unknown> };\n try {\n committed = JSON.parse(fileContent);\n } catch {\n return false;\n }\n if (committed.source) delete committed.source.ref;\n return JSON.stringify(committed) === JSON.stringify(generated);\n}\n\n/** Registers the hidden `compute __manifest [--released] [--check <file>]`. */\nexport function registerManifestCommand(\n program: Command,\n options: { version: string; packageDir: string },\n): void {\n program\n .command(MANIFEST_COMMAND, { hidden: true })\n .description('Print the command tree as JSON (for the benchmarks platform surface map)')\n .option('--released', 'mark the manifest as describing a version published to npm')\n .option('--check <file>', 'exit 1 unless <file> equals the generated manifest (ignoring source.ref)')\n .action((opts: { released?: boolean; check?: string }) => {\n const manifest = buildCliManifest(program, {\n version: options.version,\n released: Boolean(opts.released),\n packageDir: options.packageDir,\n });\n if (opts.check) {\n if (!manifestMatches(readFileSync(opts.check, 'utf-8'), manifest)) {\n console.error(\n `${opts.check} is out of date. Regenerate it with \\`pnpm --filter @computesdk/cli run manifest\\`.`,\n );\n process.exit(1);\n }\n console.log(`${opts.check} matches the ${manifest.commands.length}-command manifest.`);\n return;\n }\n process.stdout.write(manifestJson(manifest));\n });\n}\n","/**\n * `compute org members|invitations|invite|member set-role|member remove|leave`\n * and `compute invitations [show|accept|decline]` — the org's members and\n * invitations over the v1 organization routes, and the signed-in user's own\n * invitations.\n *\n * Org routes are called with the `current` org alias: the server resolves the\n * credential's org (an org API key's own org, or for a user login the org\n * `--org`/`COMPUTE_ORG` names through X-Org-Slug, else the active org).\n *\n * Writes that change who is in the org (invite, cancel, role change, remove,\n * leave, decline) ask for confirmation on a terminal and need `-y` elsewhere.\n * Accept has no confirmation: it is the invitee's own answer. Leave, accept,\n * decline and the user's own invitations need a user login; an org API key is\n * refused locally, and the server's `user_credential_required` is rendered\n * with the same hint for keys this CLI cannot recognise.\n */\n\nimport type { Command } from 'commander';\nimport pc from 'picocolors';\nimport {\n ActionsApiError,\n ActionsCliError,\n ActionsClient,\n codeForStatus,\n resolveActionsAuth,\n toErrorEnvelope,\n} from './actions-client.js';\nimport { output, usageErrorOutput, type CommonOpts } from './actions.js';\nimport { confirmWrite } from './confirm.js';\nimport { safeTerm } from './term.js';\n\n// Wire shapes: benchmarks-platform v1 organization member/invitation routes\n// (research design F-ORG-2 / F-ORG-3).\n\nexport interface OrgMember {\n id: string;\n userId: string;\n name: string | null;\n email: string;\n role: string;\n createdAt: string;\n}\n\nexport interface OrgInvitation {\n id: string;\n email: string;\n role: string;\n status: 'pending' | 'accepted' | 'rejected' | 'canceled' | (string & {});\n expiresAt: string;\n createdAt: string;\n inviterId: string;\n url: string;\n}\n\nexport interface UserInvitation extends OrgInvitation {\n organization: { id: string; name: string; slug: string };\n}\n\nexport interface InviteResponse {\n invitation: OrgInvitation;\n emailSent: boolean;\n emailError?: string;\n}\n\nexport interface AcceptResponse {\n member: OrgMember;\n organization: { id: string; name: string; slug: string };\n}\n\ntype WriteOpts = CommonOpts & { yes?: boolean };\n\nconst ORG_PATH = '/api/v1/organizations/current';\nconst MEMBER_ROLES = ['member', 'admin'] as const;\ntype MemberRole = (typeof MEMBER_ROLES)[number];\n\nconst USER_LOGIN_HINT =\n 'This needs a user login, and org API keys have no user: run `compute login`, and drop --api-key / unset COMPUTE_API_KEY.';\n\n/** Org API keys carry these prefixes; OAuth and session tokens do not. */\nexport function isOrgApiKey(key: string): boolean {\n return /^(bp|csdk)_/.test(key);\n}\n\nconst segment = (id: string) => encodeURIComponent(id);\n\nfunction orgName(opts: CommonOpts): string | undefined {\n return opts.org || process.env.COMPUTE_ORG || undefined;\n}\n\nasync function orgClient(opts: CommonOpts): Promise<ActionsClient> {\n return new ActionsClient(await resolveActionsAuth(opts));\n}\n\nasync function userClient(opts: CommonOpts, what: string): Promise<ActionsClient> {\n const auth = await resolveActionsAuth(opts);\n if (isOrgApiKey(auth.apiKey)) {\n throw new ActionsCliError(\n 'user_credential_required',\n `${what} needs a user login, and org API keys have no user. Run \\`compute login\\`, and drop --api-key / unset COMPUTE_API_KEY.`,\n );\n }\n return new ActionsClient(auth);\n}\n\nfunction apiHint(error: ActionsApiError): string | undefined {\n const body = error.body;\n if (body && typeof body === 'object' && typeof (body as { hint?: unknown }).hint === 'string') {\n return (body as { hint: string }).hint;\n }\n return error.code === 'user_credential_required' ? USER_LOGIN_HINT : undefined;\n}\n\n/**\n * Like `actions.ts` `fail`, plus the platform's `hint` (in the envelope and on\n * its own line) and the error code when the server sent one more specific\n * than the status implies.\n */\nfunction fail(error: unknown, opts: CommonOpts = {}): never {\n const hint = error instanceof ActionsApiError ? apiHint(error) : undefined;\n if (opts.json) {\n const envelope = toErrorEnvelope(error) as ReturnType<typeof toErrorEnvelope> & { error: { hint?: string } };\n if (hint) envelope.error.hint = hint;\n process.stderr.write(JSON.stringify(envelope) + '\\n');\n } else if (error instanceof ActionsApiError) {\n const code = error.code !== codeForStatus(error.status) ? ` ${error.code}` : '';\n console.error(pc.red(`Error (${error.status}${code}): ${error.message}`));\n if (hint) console.error(pc.dim(`hint: ${hint}`));\n } else {\n console.error(pc.red(`Error: ${error instanceof Error ? error.message : String(error)}`));\n }\n process.exit(1);\n}\n\nfunction memberRole(role: string, ownerMessage: string): MemberRole {\n if (role === 'owner') throw new ActionsCliError('invalid_argument', ownerMessage);\n if (!(MEMBER_ROLES as readonly string[]).includes(role)) {\n throw new ActionsCliError('invalid_argument', `Invalid role \"${role}\" — use member or admin.`);\n }\n return role as MemberRole;\n}\n\nfunction printTable(header: string[], rows: string[][]): void {\n const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));\n const line = (cells: string[]) => cells.map((c, i) => c.padEnd(widths[i])).join(' ').trimEnd();\n console.log(line(header));\n for (const row of rows) console.log(line(row));\n}\n\nexport function printMembers(res: { members: OrgMember[] }): void {\n if (res.members.length === 0) {\n console.log('No members.');\n return;\n }\n printTable(\n ['EMAIL', 'ROLE', 'NAME', 'MEMBER ID', 'JOINED'],\n res.members.map((m) => [safeTerm(m.email), safeTerm(m.role), safeTerm(m.name ?? '—'), safeTerm(m.id), safeTerm(m.createdAt)]),\n );\n}\n\nexport function printOrgInvitations(res: { invitations: OrgInvitation[] }): void {\n if (res.invitations.length === 0) {\n console.log('No pending invitations.');\n return;\n }\n printTable(\n ['ID', 'EMAIL', 'ROLE', 'EXPIRES', 'LINK'],\n res.invitations.map((i) => [safeTerm(i.id), safeTerm(i.email), safeTerm(i.role), safeTerm(i.expiresAt), safeTerm(i.url)]),\n );\n}\n\nexport function printUserInvitations(res: { invitations: UserInvitation[] }): void {\n if (res.invitations.length === 0) {\n console.log('No pending invitations.');\n return;\n }\n printTable(\n ['ID', 'ORG', 'ROLE', 'EXPIRES', 'ORG NAME'],\n res.invitations.map((i) => [\n safeTerm(i.id),\n safeTerm(i.organization.slug),\n safeTerm(i.role),\n safeTerm(i.expiresAt),\n safeTerm(i.organization.name),\n ]),\n );\n console.log(pc.dim('Accept with `compute invitations accept <id>`; decline with `compute invitations decline <id> -y`.'));\n}\n\nfunction printInvitationDetail(inv: UserInvitation): void {\n const rows: Array<[string, string]> = [\n ['invitation', safeTerm(inv.id)],\n ['org', `${safeTerm(inv.organization.slug)} (${safeTerm(inv.organization.name)})`],\n ['email', safeTerm(inv.email)],\n ['role', safeTerm(inv.role)],\n ['status', safeTerm(inv.status)],\n ['expires', safeTerm(inv.expiresAt)],\n ['link', safeTerm(inv.url)],\n ];\n for (const [k, v] of rows) console.log(`${k.padEnd(10)} ${v}`);\n}\n\nfunction printInvite(res: InviteResponse): void {\n const inv = res.invitation;\n console.log(`Invited ${safeTerm(inv.email)} as ${safeTerm(inv.role)} (invitation ${safeTerm(inv.id)}, expires ${safeTerm(inv.expiresAt)}).`);\n if (res.emailSent) {\n console.log(`Emailed ${safeTerm(inv.email)} the invitation link.`);\n } else {\n const reason = res.emailError ? ` (${safeTerm(res.emailError)})` : '';\n console.log(pc.yellow(`The invitation email was not sent${reason}; share the link instead.`));\n }\n console.log(`Link: ${safeTerm(inv.url)}`);\n}\n\n/** A member by id, user id or email (case-insensitive). */\nexport function findMember(members: OrgMember[], ref: string): OrgMember | undefined {\n const lower = ref.toLowerCase();\n return (\n members.find((m) => m.id === ref) ??\n members.find((m) => m.userId === ref) ??\n members.find((m) => m.email.toLowerCase() === lower)\n );\n}\n\nasync function resolveMember(c: ActionsClient, ref: string, opts: CommonOpts): Promise<OrgMember> {\n const { members } = await c.get<{ members: OrgMember[] }>(`${ORG_PATH}/members`);\n const member = findMember(members, ref);\n if (!member) {\n const org = orgName(opts);\n throw new ActionsCliError('not_found', `No member ${ref} in ${org ? `org ${org}` : 'this organization'}.`);\n }\n return member;\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+$/;\n\n/**\n * `common` adds the shared platform flags; every command here sends its usage\n * errors through the `--json` envelope.\n */\nfunction command(parent: Command, name: string): Command {\n return parent.command(name).configureOutput({ outputError: usageErrorOutput });\n}\n\nfunction common(cmd: Command): Command {\n return 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, for a user login (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\n/** Registers the member and invitation commands on the existing `compute org` group. */\nexport function registerOrgMemberCommands(org: Command): void {\n common(\n command(org, 'members').description(\"List the organization's members with their roles\"),\n ).action(async (opts: CommonOpts) => {\n try {\n const c = await orgClient(opts);\n output(opts, await c.get<{ members: OrgMember[] }>(`${ORG_PATH}/members`), printMembers);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const invitations = common(\n command(org, 'invitations')\n .description(\"List the organization's pending invitations with their links (owner/admin)\")\n .allowExcessArguments(false),\n ).action(async (opts: CommonOpts) => {\n try {\n const c = await orgClient(opts);\n output(opts, await c.get<{ invitations: OrgInvitation[] }>(`${ORG_PATH}/invitations`), printOrgInvitations);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(invitations, 'cancel')\n .description('Cancel a pending invitation; its link stops working (owner/admin)')\n .argument('<invitationId>', 'invitation id (see `compute org invitations`)')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (invitationId: string, opts: WriteOpts) => {\n try {\n await confirmWrite(`Cancel invitation ${invitationId}? Its link stops working.`, opts);\n const c = await orgClient(opts);\n const res = await c.del<{ invitation: OrgInvitation }>(`${ORG_PATH}/invitations/${segment(invitationId)}`);\n output(opts, res, (r) =>\n console.log(`Cancelled the invitation for ${safeTerm(r.invitation.email)} (${r.invitation.id}).`),\n );\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(org, 'invite')\n .description('Invite someone to the organization by email and print the invite link (owner/admin)')\n .argument('<email>', 'email address to invite')\n .option('--role <role>', 'member | admin (owners are invited in the web app)', 'member')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (email: string, opts: WriteOpts & { role: string }) => {\n try {\n const role = memberRole(opts.role, 'Owner invitations require the web app.');\n if (!EMAIL.test(email)) {\n throw new ActionsCliError('invalid_argument', `Invalid email \"${email}\".`);\n }\n const target = orgName(opts);\n await confirmWrite(`Invite ${email} as ${role}${target ? ` to ${target}` : ''}?`, opts);\n const c = await orgClient(opts);\n output(opts, await c.post<InviteResponse>(`${ORG_PATH}/invitations`, { email, role }), printInvite);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const member = command(org, 'member').description(\"Change a member's role or remove a member (owner/admin)\");\n\n common(\n command(member, 'set-role')\n .description(\"Change a member's role between member and admin (owner roles change in the web app)\")\n .argument('<member>', 'member id or email (see `compute org members`)')\n .argument('<role>', 'member | admin')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (ref: string, roleArg: string, opts: WriteOpts) => {\n try {\n const role = memberRole(roleArg, 'Owner role changes require the web app.');\n const c = await orgClient(opts);\n const target = await resolveMember(c, ref, opts);\n await confirmWrite(`Change ${target.email} from ${target.role} to ${role}?`, opts);\n const res = await c.patch<{ member: OrgMember }>(`${ORG_PATH}/members/${segment(target.id)}`, { role });\n output(opts, res, (r) => console.log(`${safeTerm(r.member.email)} is now ${safeTerm(r.member.role)}.`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(member, 'remove')\n .alias('rm')\n .description('Remove a member from the organization (owners are removed in the web app)')\n .argument('<member>', 'member id or email (see `compute org members`)')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (ref: string, opts: WriteOpts) => {\n try {\n const c = await orgClient(opts);\n const target = await resolveMember(c, ref, opts);\n const org = orgName(opts);\n await confirmWrite(\n `Remove ${target.email} (${target.role}) from ${org ?? 'the organization'}? They lose access at once.`,\n opts,\n );\n const res = await c.del<{ removed: OrgMember }>(`${ORG_PATH}/members/${segment(target.id)}`);\n output(opts, res, (r) =>\n console.log(`Removed ${safeTerm(r.removed.email)} (${safeTerm(r.removed.role)}) from ${org ?? 'the organization'}.`),\n );\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(org, 'leave')\n .description('Leave the organization (needs a user login; the last owner cannot leave)')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (opts: WriteOpts) => {\n try {\n const c = await userClient(opts, '`compute org leave`');\n const org = orgName(opts);\n await confirmWrite(`Leave ${org ?? 'the active organization'}? You lose access to it at once.`, opts);\n const res = await c.post<{ left: true }>(`${ORG_PATH}/leave`, {});\n output(opts, res, () => {\n console.log(`Left ${org ?? 'the organization'}.`);\n // Leaving revokes the user's OAuth grants for that org, so a login\n // granted through it stops working on the next call.\n console.log(\n pc.dim('If your login was granted for that organization, it no longer works: run `compute login` again.'),\n );\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n\n/** `compute invitations [show|accept|decline]` — the signed-in user's own invitations. */\nexport function registerInvitationsCommands(program: Command): void {\n const invitations = common(\n command(program, 'invitations')\n .description('Your pending invitations to other organizations (needs a user login)')\n .allowExcessArguments(false),\n ).action(async (opts: CommonOpts) => {\n try {\n const c = await userClient(opts, '`compute invitations`');\n output(opts, await c.get<{ invitations: UserInvitation[] }>('/api/v1/me/invitations'), printUserInvitations);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(invitations, 'show')\n .description('Show one of your invitations')\n .argument('<invitationId>', 'invitation id (see `compute invitations`)'),\n ).action(async (invitationId: string, opts: CommonOpts) => {\n try {\n const c = await userClient(opts, '`compute invitations show`');\n const res = await c.get<{ invitation: UserInvitation }>(`/api/v1/invitations/${segment(invitationId)}`);\n output(opts, res, (r) => printInvitationDetail(r.invitation));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(invitations, 'accept')\n .description('Accept an invitation and join its organization (no confirmation)')\n .argument('<invitationId>', 'invitation id (see `compute invitations`)')\n .option('-y, --yes', 'accepted for symmetry with decline; accept never asks'),\n ).action(async (invitationId: string, opts: WriteOpts) => {\n try {\n const c = await userClient(opts, '`compute invitations accept`');\n const res = await c.post<AcceptResponse>(`/api/v1/invitations/${segment(invitationId)}/accept`, {});\n output(opts, res, (r) => {\n const slug = safeTerm(r.organization.slug);\n console.log(`Joined ${slug} as ${safeTerm(r.member.role)}.`);\n console.log(pc.dim(`Switch to it with \\`compute org use ${slug}\\`, or pass --org ${slug}.`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n command(invitations, 'decline')\n .description('Decline an invitation')\n .argument('<invitationId>', 'invitation id (see `compute invitations`)')\n .option('-y, --yes', 'skip the confirmation'),\n ).action(async (invitationId: string, opts: WriteOpts) => {\n try {\n const c = await userClient(opts, '`compute invitations decline`');\n await confirmWrite(`Decline invitation ${invitationId}? Its link stops working.`, opts);\n const res = await c.post<{ invitation: OrgInvitation & Partial<Pick<UserInvitation, 'organization'>> }>(\n `/api/v1/invitations/${segment(invitationId)}/decline`,\n {},\n );\n output(opts, res, (r) => {\n const org = r.invitation.organization?.slug;\n console.log(org ? `Declined the invitation to ${safeTerm(org)}.` : `Declined invitation ${r.invitation.id}.`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA0BA,SAAS,mBACd,MACA,eACuB;AACvB,SAAO,oBAAoB,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EAC/B,SAAS,YAAY;AAAA,EACrB,YAAYP,MAAKH,YAAW,IAAI;AAClC,CAAC;AAOD,eAAe,OAAO;AACpB,QAAM,QAAQ,mBAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC;AACtD,MAAI,OAAO;AACT,UAAM,SAAS,KAAK;AACpB;AAAA,EACF;AACA,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAMO,KAAG,IAAI;AAAA,SAAY,MAAM,OAAO,EAAE,CAAC;AACjD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["pc","list","common","settings","pc","path","common","runs","p","list","pc","common","path","pc","plural","common","client","output","fail","pc","common","client","output","fail","Option","pc","readFileSync","message","p","client","path","program","common","org","p","requireModule","fs","path","relative","segment","scanLocalTree","path","fileURLToPath","createHash","relative","p","Command","Option","pc","readFileSync","fileURLToPath","dirname","join","pc","pc","p","program","common","list","pc","RATE_UNITS","formatRate","pc","p","program","common","pc","MICRO_USD","program","common","p","pc","program","fs","path","Readable","Command","Option","pc","tar","spawnSync","mkdirSync","readFileSync","writeFileSync","join","org","p","common","fs","path","spawnSync","randomUUID","fs","path","createRequire","requireModule","response","spawnSync","relative","ignoredPaths","p","randomUUID","program","createHash","mkdirSync","readFileSync","writeFileSync","renameSync","rmSync","readdirSync","homedir","join","delay","DEFAULT_BASE_URL","isSecurePlatformTransport","isTrustedPlatformHost","DEFAULT_BASE_URL","isSecurePlatformTransport","isTrustedPlatformHost","isTrustedPlatformHost","isSecurePlatformTransport","DEFAULT_BASE_URL","org","getMe","command","resolve","stateDir","join","homedir","createHash","readFileSync","mkdirSync","writeFileSync","renameSync","rmSync","readdirSync","DEFAULT_BASE_URL","isTrustedPlatformHost","isSecurePlatformTransport","delay","p","pc","org","Option","command","program","Command","list","resolve","path","Readable","pc","readFileSync","formatLocalTime","p","program","message","org","program","DEFAULT_BASE_URL","org","DEFAULT_BASE_URL","createRequire","existsSync","readFileSync","realpathSync","dirname","join","sep","require","createRequire","join","dirname","existsSync","readFileSync","sep","realpathSync","p","program","pc","fail","printTable","org","program","__filename","fileURLToPath","__dirname","dirname","readFileSync","join","Command","Option","getMe","pc","org","loadCredentials","saveCredentials","setActiveOrganization"]}
|