@computesdk/cli 1.0.14 → 1.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +94 -4
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/.pnpm/tsup@8.5.0_jiti@2.6.1_postcss@8.5.6_tsx@4.20.3_typescript@5.8.3_yaml@2.8.2/node_modules/tsup/assets/esm_shims.js","../src/repl.ts","../src/workspace-cli.ts","../src/index.ts","../src/providers.ts","../src/actions.ts","../src/actions-client.ts","../src/market.ts","../src/sandboxes.ts","../src/auth.ts","../src/setup.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 * REPL Mode - Run commands one at a time\n *\n * Shell-like interface where each line is executed as a command.\n * Special commands prefixed with /.\n */\n\nimport * as readline from 'readline';\nimport * as path from 'path';\nimport * as os from 'os';\nimport * as fs from 'fs';\nimport pc from 'picocolors';\nimport { compute, type SandboxInterface } from 'computesdk';\n\ntype SessionResult = 'exit';\n\ninterface ReplContext {\n sandboxes: Map<string, SandboxInterface>;\n activeSandboxId: string;\n}\n\n/**\n * Start REPL mode.\n */\nexport async function startREPL(sandbox: SandboxInterface, provider: string): Promise<void> {\n // Mark provider as used - reserved for future provider-specific REPL behavior\n void provider;\n const ctx: ReplContext = {\n sandboxes: new Map([[sandbox.sandboxId, sandbox]]),\n activeSandboxId: sandbox.sandboxId,\n };\n\n await runSession(ctx);\n}\n\nfunction buildPrompt(sandboxId: string): string {\n if (!sandboxId) return pc.gray('[no sandbox] ') + pc.bold('$ ');\n return pc.cyan(`[${sandboxId}] `) + pc.bold('$ ');\n}\n\n/**\n * Run a single REPL session.\n *\n * Creates a readline interface, processes commands, and returns\n * 'exit' when the user wants to quit.\n */\nfunction runSession(ctx: ReplContext): Promise<SessionResult> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n prompt: buildPrompt(ctx.activeSandboxId),\n terminal: true,\n historySize: 1000,\n });\n\n // Load history\n loadHistory(rl);\n\n return new Promise<SessionResult>((resolve) => {\n let resolved = false;\n const done = (result: SessionResult) => {\n if (resolved) return;\n resolved = true;\n rl.close();\n resolve(result);\n };\n\n rl.on('SIGINT', () => {\n console.log();\n rl.prompt();\n });\n\n rl.on('close', () => {\n done('exit');\n });\n\n rl.on('line', async (line: string) => {\n const trimmed = line.trim();\n\n if (!trimmed) {\n rl.prompt();\n return;\n }\n\n if (trimmed === '.exit') {\n done('exit');\n return;\n }\n\n // Save to history\n saveToHistory(trimmed);\n\n try {\n if (trimmed.startsWith('/')) {\n const result = await handleSpecialCommand(ctx, trimmed, rl);\n if (result === 'exit') {\n done(result);\n return;\n }\n } else if (ctx.sandboxes.size === 0) {\n console.log(pc.yellow('No active sandbox. Use /new to create one.'));\n } else {\n const sandbox = ctx.sandboxes.get(ctx.activeSandboxId)!;\n await executeCommand(sandbox, trimmed);\n }\n } catch (error) {\n console.log(pc.red(`✗ ${(error as Error).message}`));\n }\n\n if (!resolved) {\n rl.prompt();\n }\n });\n\n rl.prompt();\n });\n}\n\n/**\n * Execute a shell command in the sandbox\n */\nasync function executeCommand(sandbox: SandboxInterface, command: string): Promise<void> {\n const result = await sandbox.runCommand(command);\n\n // Print stdout\n if (result.stdout) {\n process.stdout.write(result.stdout);\n if (!result.stdout.endsWith('\\n')) {\n console.log();\n }\n }\n\n // Print stderr in red\n if (result.stderr) {\n process.stderr.write(pc.red(result.stderr));\n if (!result.stderr.endsWith('\\n')) {\n console.log();\n }\n }\n\n // Show exit code if non-zero\n if (result.exitCode !== 0) {\n console.log(pc.gray(`exit code: ${result.exitCode}`));\n }\n}\n\n/**\n * Handle special commands (prefixed with /)\n * Returns 'exit' to quit, or null to continue\n */\nasync function handleSpecialCommand(\n ctx: ReplContext,\n input: string,\n rl: readline.Interface,\n): Promise<SessionResult | null> {\n const [cmd, ...args] = input.slice(1).split(/\\s+/);\n\n switch (cmd.toLowerCase()) {\n case 'help':\n case 'h':\n case '?':\n showHelp();\n return null;\n\n case 'info':\n case 'i': {\n if (ctx.sandboxes.size === 0) {\n console.log(pc.yellow('No active sandbox. Use /new to create one.'));\n return null;\n }\n const activeSandbox = ctx.sandboxes.get(ctx.activeSandboxId)!;\n console.log();\n console.log(pc.bold(' Sandbox Info'));\n console.log(` ID: ${pc.cyan(activeSandbox.sandboxId)}`);\n console.log();\n return null;\n }\n\n case 'url':\n case 'u': {\n if (ctx.sandboxes.size === 0) {\n console.log(pc.yellow('No active sandbox. Use /new to create one.'));\n return null;\n }\n const activeSandbox = ctx.sandboxes.get(ctx.activeSandboxId)!;\n if (args.length === 0) {\n console.log(pc.gray('Usage: /url <port>'));\n } else {\n const port = parseInt(args[0], 10);\n if (isNaN(port)) {\n console.log(pc.red('Invalid port number'));\n } else {\n const url = await activeSandbox.getUrl({ port });\n console.log(pc.cyan(url));\n }\n }\n return null;\n }\n\n case 'new': {\n console.log(pc.gray(' Creating new sandbox...'));\n const newSandbox = await compute.sandbox.create();\n ctx.sandboxes.set(newSandbox.sandboxId, newSandbox);\n ctx.activeSandboxId = newSandbox.sandboxId;\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(` Sandbox ready: ${pc.cyan(newSandbox.sandboxId)}`);\n console.log(` ${pc.gray(`Active sandboxes: ${ctx.sandboxes.size}`)}`);\n return null;\n }\n\n case 'destroy': {\n if (args.length === 0) {\n console.log(pc.gray('Usage: /destroy <sandbox-id> or /destroy --all'));\n console.log(pc.gray('Use /list to see all sandboxes'));\n return null;\n }\n if (args[0] === '--all') {\n if (ctx.sandboxes.size === 0) {\n console.log(pc.yellow(' No sandboxes to destroy.'));\n return null;\n }\n const count = ctx.sandboxes.size;\n console.log(pc.gray(` Destroying ${count} sandbox${count > 1 ? 'es' : ''}...`));\n await Promise.all(\n Array.from(ctx.sandboxes.values()).map(s => s.destroy()),\n );\n ctx.sandboxes.clear();\n ctx.activeSandboxId = '';\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(` Destroyed ${pc.cyan(String(count))} sandbox${count > 1 ? 'es' : ''}`);\n console.log(pc.yellow(' No sandboxes remaining. Use /new to create one or /exit to quit.'));\n return null;\n }\n const targetId = args[0];\n const target = ctx.sandboxes.get(targetId);\n if (!target) {\n // Try partial match\n const matches = Array.from(ctx.sandboxes.keys()).filter(id => id.startsWith(targetId));\n if (matches.length === 1) {\n return destroySandbox(ctx, matches[0], rl);\n } else if (matches.length > 1) {\n console.log(pc.yellow(' Ambiguous ID. Matches:'));\n for (const id of matches) {\n console.log(` ${pc.cyan(id)}`);\n }\n } else {\n console.log(pc.red(` Sandbox not found: ${targetId}`));\n console.log(pc.gray(' Use /list to see all sandboxes'));\n }\n return null;\n }\n return destroySandbox(ctx, targetId, rl);\n }\n\n case 'list':\n case 'ls': {\n console.log();\n console.log(pc.bold(' Sandboxes'));\n for (const id of ctx.sandboxes.keys()) {\n const marker = id === ctx.activeSandboxId ? pc.green(' ●') : ' ';\n console.log(` ${marker} ${pc.cyan(id)}`);\n }\n console.log();\n return null;\n }\n\n case 'switch':\n case 'sw': {\n if (args.length === 0) {\n console.log(pc.gray('Usage: /switch <sandbox-id>'));\n console.log(pc.gray('Use /list to see all sandboxes'));\n return null;\n }\n const switchId = args[0];\n if (ctx.sandboxes.has(switchId)) {\n ctx.activeSandboxId = switchId;\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(` Switched to ${pc.cyan(switchId)}`);\n return null;\n }\n // Try partial match\n const matches = Array.from(ctx.sandboxes.keys()).filter(id => id.startsWith(switchId));\n if (matches.length === 1) {\n ctx.activeSandboxId = matches[0];\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(` Switched to ${pc.cyan(matches[0])}`);\n } else if (matches.length > 1) {\n console.log(pc.yellow(' Ambiguous ID. Matches:'));\n for (const id of matches) {\n console.log(` ${pc.cyan(id)}`);\n }\n } else {\n console.log(pc.red(` Sandbox not found: ${switchId}`));\n console.log(pc.gray(' Use /list to see all sandboxes'));\n }\n return null;\n }\n\n case 'exit':\n case 'quit':\n case 'q':\n return 'exit';\n\n default:\n console.log(pc.yellow(`Unknown command: /${cmd}`));\n console.log(pc.gray('Type /help for available commands'));\n return null;\n }\n}\n\n/**\n * Destroy a sandbox by ID and update context\n */\nasync function destroySandbox(\n ctx: ReplContext,\n sandboxId: string,\n rl: readline.Interface,\n): Promise<null> {\n const target = ctx.sandboxes.get(sandboxId)!;\n console.log(pc.gray(` Destroying ${sandboxId}...`));\n await target.destroy();\n ctx.sandboxes.delete(sandboxId);\n console.log(` Destroyed ${pc.cyan(sandboxId)}`);\n\n // If we destroyed the active sandbox, switch to another\n if (ctx.activeSandboxId === sandboxId && ctx.sandboxes.size > 0) {\n ctx.activeSandboxId = ctx.sandboxes.keys().next().value!;\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(` Switched to ${pc.cyan(ctx.activeSandboxId)}`);\n } else if (ctx.sandboxes.size === 0) {\n ctx.activeSandboxId = '';\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(pc.yellow(' No sandboxes remaining. Use /new to create one or /exit to quit.'));\n }\n\n return null;\n}\n\n/**\n * Show help message\n */\nfunction showHelp(): void {\n console.log();\n console.log(pc.bold(' Shell Mode'));\n console.log(pc.gray(' Just type commands - they run in the active sandbox'));\n console.log();\n console.log(pc.white(' ls -la'));\n console.log(pc.white(' cat /etc/os-release'));\n console.log(pc.white(' npm install lodash'));\n console.log();\n console.log(pc.bold(' Sandbox Commands') + pc.gray(' (prefix with /)'));\n console.log();\n console.log(pc.cyan(' /new') + pc.gray(' Create a new sandbox and switch to it'));\n console.log(pc.cyan(' /list') + pc.gray(' List all sandboxes'));\n console.log(pc.cyan(' /switch <id>') + pc.gray(' Switch active sandbox'));\n console.log(pc.cyan(' /destroy <id>') + pc.gray(' Destroy a sandbox by ID'));\n console.log(pc.cyan(' /destroy --all') + pc.gray(' Destroy all sandboxes'));\n console.log();\n console.log(pc.bold(' Other Commands'));\n console.log();\n console.log(pc.cyan(' /info') + pc.gray(' Show active sandbox info'));\n console.log(pc.cyan(' /url <port>') + pc.gray(' Get public URL for port'));\n console.log(pc.cyan(' /help') + pc.gray(' Show this help'));\n console.log(pc.cyan(' /exit') + pc.gray(' Exit the REPL'));\n console.log();\n}\n\n// History file path\nconst HISTORY_FILE = path.join(os.homedir(), '.create_compute_history');\n\n/**\n * Load history from file\n */\nfunction loadHistory(rl: readline.Interface): void {\n try {\n if (fs.existsSync(HISTORY_FILE)) {\n const history = fs.readFileSync(HISTORY_FILE, 'utf-8')\n .split('\\n')\n .filter(line => line.trim())\n .reverse();\n\n for (const line of history.slice(0, 1000)) {\n (rl as unknown as { history: string[] }).history?.push(line);\n }\n }\n } catch {\n // Ignore\n }\n}\n\n/**\n * Save a line to history\n */\nfunction saveToHistory(line: string): void {\n try {\n fs.appendFileSync(HISTORY_FILE, line + '\\n');\n } catch {\n // Ignore\n }\n}\n","#!/usr/bin/env node\n/**\n * Minimal workspace CLI using existing PR #344 infrastructure\n * \n * This is a thin wrapper around sandbox.create() + bootstrap script\n * that adds the workspace concept without SDK changes.\n */\n\nimport { compute } from 'computesdk';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as os from 'node:os';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { startREPL } from './repl.js';\n\nconst WORKSPACE_STATE_FILE = path.join(os.homedir(), '.computesdk', 'workspaces.json');\n\ninterface Workspace {\n id: string; // repo:branch\n repo: string;\n branch: string;\n sandboxId: string;\n provider: string;\n worktreePath: string;\n createdAt: string;\n lastUsed: string;\n}\n\ninterface WorkspaceState {\n workspaces: Record<string, Workspace>;\n}\n\n// Export Workspace interface\nexport type { Workspace, WorkspaceState };\n\n// Shell escape helper to prevent command injection\nfunction shellEscape(arg: string): string {\n if (/^[a-zA-Z0-9._\\-/:=@]+$/.test(arg)) return arg;\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n// Load workspace state\nexport function loadState(): WorkspaceState {\n try {\n if (!fs.existsSync(WORKSPACE_STATE_FILE)) {\n return { workspaces: {} };\n }\n const raw = fs.readFileSync(WORKSPACE_STATE_FILE, 'utf-8');\n return JSON.parse(raw);\n } catch {\n return { workspaces: {} };\n }\n}\n\n// Export alias for index.ts\nexport const loadWorkspaceState = loadState;\n\n// Save workspace state\nexport function saveState(state: WorkspaceState): void {\n const dir = path.dirname(WORKSPACE_STATE_FILE);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n fs.writeFileSync(WORKSPACE_STATE_FILE, JSON.stringify(state, null, 2) + '\\n', { mode: 0o600 });\n}\n\n// Get workspace ID from repo and branch\nfunction getWorkspaceId(repo: string, branch: string): string {\n return `${repo}:${branch}`;\n}\n\n// Create or attach to workspace\nexport async function workspaceCreate(options: {\n repo: string;\n branch: string;\n provider?: string;\n}): Promise<Workspace> {\n const { repo, branch, provider } = options;\n const id = getWorkspaceId(repo, branch);\n const state = loadState();\n \n // Check if workspace already exists\n if (state.workspaces[id]) {\n const existing = state.workspaces[id];\n \n // Verify sandbox still exists\n try {\n const sandbox = await compute.sandbox.getById(existing.sandboxId);\n if (!sandbox) {\n throw new Error('Sandbox not found');\n }\n \n // Just update last used\n existing.lastUsed = new Date().toISOString();\n saveState(state);\n \n p.log.info(`Attaching to existing workspace: ${pc.cyan(id)}`);\n return existing;\n } catch {\n // Sandbox is gone, remove from state and recreate\n delete state.workspaces[id];\n }\n }\n \n // Create new sandbox\n p.log.info('Creating sandbox...');\n const spinner = p.spinner();\n spinner.start('Provisioning via ComputeSDK...');\n \n let sandbox;\n try {\n // TODO: Configure compute with provider\n sandbox = await compute.sandbox.create();\n spinner.stop(`Sandbox ready: ${pc.cyan(sandbox.sandboxId)}`);\n } catch (error) {\n spinner.stop(pc.red('Failed to create sandbox'));\n throw error;\n }\n \n // Run bootstrap script\n spinner.start('Bootstrapping workspace (installing gh CLI, cloning repo)...');\n \n // Read bootstrap script\n const bootstrapScript = fs.readFileSync(\n new URL('./bootstrap.sh', import.meta.url),\n 'utf-8'\n );\n \n // Write and execute bootstrap script in sandbox\n try {\n // Write script to sandbox\n await sandbox.filesystem.writeFile('/tmp/bootstrap.sh', bootstrapScript);\n \n // Make executable and run\n await sandbox.runCommand('chmod +x /tmp/bootstrap.sh');\n \n // Run bootstrap with repo and branch\n // Note: This is interactive for device flow auth\n spinner.stop('Running bootstrap (you may need to authenticate with GitHub)...');\n \n const result = await sandbox.runCommand(\n `/tmp/bootstrap.sh ${shellEscape(repo)} ${shellEscape(branch)}`,\n { timeout: 300000 } // 5 min timeout for auth\n );\n \n // Parse bootstrap output for paths\n const output = result.stdout || '';\n const jsonMatch = output.match(/\\{[\\s\\S]*\\}/);\n let worktreePath = `/workspaces/${path.basename(repo)}-${branch}`;\n \n if (jsonMatch) {\n try {\n const bootstrapInfo = JSON.parse(jsonMatch[0]);\n worktreePath = bootstrapInfo.worktree_path || worktreePath;\n } catch {\n // Use default path\n }\n }\n \n // Create workspace record\n const workspace: Workspace = {\n id,\n repo,\n branch,\n sandboxId: sandbox.sandboxId,\n provider: provider || 'e2b', // TODO: Get actual provider\n worktreePath,\n createdAt: new Date().toISOString(),\n lastUsed: new Date().toISOString(),\n };\n \n state.workspaces[id] = workspace;\n saveState(state);\n \n p.log.success(`Workspace ready: ${pc.cyan(id)}`);\n p.log.info(`Sandbox: ${pc.dim(sandbox.sandboxId)}`);\n p.log.info(`Worktree: ${pc.dim(worktreePath)}`);\n \n return workspace;\n \n } catch (error) {\n spinner.stop(pc.red('Bootstrap failed'));\n // Cleanup sandbox on failure\n try {\n await sandbox.destroy();\n } catch {\n // Ignore cleanup errors\n }\n throw error;\n }\n}\n\n// Attach to existing workspace\nexport async function workspaceAttach(id: string): Promise<void> {\n const state = loadState();\n const workspace = state.workspaces[id];\n \n if (!workspace) {\n p.log.error(`Workspace not found: ${id}`);\n p.log.info(`Run: compute workspace create --repo owner/repo --branch ${id.split(':')[1] || 'main'}`);\n process.exit(1);\n }\n \n // Get sandbox\n const sandbox = await compute.sandbox.getById(workspace.sandboxId);\n if (!sandbox) {\n p.log.error(`Sandbox no longer exists: ${workspace.sandboxId}`);\n delete state.workspaces[id];\n saveState(state);\n process.exit(1);\n }\n \n // Update last used\n workspace.lastUsed = new Date().toISOString();\n saveState(state);\n \n p.log.info(`Attaching to workspace: ${pc.cyan(id)}`);\n p.log.info(`Worktree: ${pc.dim(workspace.worktreePath)}`);\n console.log(pc.gray(`Tip: commands run at sandbox root; use { cwd: \"${workspace.worktreePath}\" } on runCommand to scope them.`));\n\n try {\n await startREPL(sandbox, workspace.provider);\n } catch (error) {\n p.log.error(`Failed to attach: ${(error as Error).message}`);\n process.exit(1);\n }\n}\n\n// List all sandboxes (via workspaces)\nexport async function sandboxList(): Promise<void> {\n const state = loadState();\n const workspaces = Object.values(state.workspaces);\n \n if (workspaces.length === 0) {\n p.log.info('No sandboxes found.');\n p.log.info('Create one with: compute owner/repo --branch main');\n return;\n }\n \n console.log();\n console.log(pc.bold('Sandboxes'));\n console.log();\n \n for (const ws of workspaces) {\n const age = Math.round((Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24));\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n const status = age > 7 ? pc.red('stale') : age > 1 ? pc.yellow('idle') : pc.green('active');\n \n console.log(` ${status} ${pc.cyan(ws.sandboxId)}`);\n console.log(` Workspace: ${pc.dim(ws.id)}`);\n console.log(` Provider: ${ws.provider}`);\n console.log(` Last active: ${pc.gray(ageStr)}`);\n console.log();\n }\n \n console.log(pc.gray('Tip: Use \"compute workspaces\" to see full workspace details'));\n}\n\n// List all workspaces\nexport async function workspaceList(): Promise<void> {\n const state = loadState();\n const workspaces = Object.values(state.workspaces);\n \n if (workspaces.length === 0) {\n p.log.info('No workspaces found.');\n p.log.info('Create one with: compute owner/repo --branch main');\n return;\n }\n \n console.log();\n console.log(pc.bold('Workspaces'));\n console.log();\n \n for (const ws of workspaces) {\n const age = Math.round((Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24));\n const ageStr = age === 0 ? 'today' : `${age}d ago`;\n \n console.log(` ${pc.cyan(ws.id)}`);\n console.log(` Sandbox: ${pc.dim(ws.sandboxId)} (${ws.provider})`);\n console.log(` Path: ${pc.dim(ws.worktreePath)}`);\n console.log(` Last used: ${pc.gray(ageStr)}`);\n console.log();\n }\n}\n\n// Save a simple sandbox (without workspace/repo info)\nexport async function saveSandbox(sandbox: {\n id: string;\n sandboxId: string;\n provider: string;\n createdAt: string;\n lastUsed: string;\n}): Promise<void> {\n const state = loadState();\n \n // Store as a minimal \"workspace\" with just sandbox info\n state.workspaces[sandbox.id] = {\n id: sandbox.id,\n repo: '(no repo)',\n branch: '(raw sandbox)',\n sandboxId: sandbox.sandboxId,\n provider: sandbox.provider,\n worktreePath: '/',\n createdAt: sandbox.createdAt,\n lastUsed: sandbox.lastUsed,\n };\n \n saveState(state);\n}\n\n// Destroy workspace\nexport async function workspaceDestroy(id?: string): Promise<void> {\n const state = loadState();\n \n if (id) {\n // Destroy specific workspace\n const workspace = state.workspaces[id];\n if (!workspace) {\n p.log.error(`Workspace not found: ${id}`);\n return;\n }\n \n p.log.info(`Destroying workspace: ${pc.cyan(id)}`);\n \n try {\n await compute.sandbox.destroy(workspace.sandboxId);\n delete state.workspaces[id];\n saveState(state);\n p.log.success('Workspace destroyed');\n } catch (error) {\n p.log.error(`Failed to destroy: ${(error as Error).message}`);\n }\n } else {\n // Interactive selection\n const choices = Object.values(state.workspaces).map(ws => ({\n value: ws.id,\n label: `${ws.id} (${ws.provider}, last used ${Math.round((Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24))}d ago)`\n }));\n \n if (choices.length === 0) {\n p.log.info('No workspaces to destroy');\n return;\n }\n \n const selected = await p.select({\n message: 'Select workspace to destroy',\n options: choices,\n });\n \n if (p.isCancel(selected)) {\n return;\n }\n \n await workspaceDestroy(selected as string);\n }\n}\n","/**\n * @computesdk/cli\n *\n * ComputeSDK CLI - Cloud-native workspace management.\n *\n * Usage:\n * compute # interactive workspace creation\n * compute owner/repo # create workspace for repo\n * compute --repo owner/repo --branch fix-auth\n * compute workspace # manage existing workspaces\n * compute exec <id> <cmd...> # run command in sandbox\n * compute connect <id> # open REPL against sandbox\n * compute destroy <id...> # destroy sandboxes\n * compute run -- <cmd...> # create + exec + optional destroy\n * compute providers # list configured providers\n */\n\nimport 'dotenv/config';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { compute, type SandboxInterface } from 'computesdk';\nimport { getProviderStatus } from './providers.js';\nimport { registerActionsCommands } from './actions.js';\nimport { registerMarketCommands } from './market.js';\nimport { registerSandboxesCommands } from './sandboxes.js';\nimport { startREPL } from './repl.js';\nimport { clearStoredCredentials } from './auth.js';\nimport { ensureAuth, resolveProvider, configureCompute } from './setup.js';\nimport {\n workspaceCreate,\n workspaceAttach,\n workspaceList,\n workspaceDestroy,\n sandboxList,\n loadWorkspaceState,\n type Workspace,\n} from './workspace-cli.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\nconst program = new Command();\n\nprogram\n .name('compute')\n .description('Cloud-native workspace management')\n .version(VERSION)\n .enablePositionalOptions()\n .passThroughOptions();\n\n// ─── Default action: Show help ─────────────────────────────────────────────\n\nprogram\n .option('--login', 'force re-authentication')\n .option('--logout', 'clear stored credentials')\n .action(async (opts) => {\n if (opts.logout) {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n clearStoredCredentials();\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 ensureAuth({ forceLogin: true });\n p.outro(pc.green('Authenticated!'));\n process.exit(0);\n }\n\n // Show help by default\n program.help();\n });\n\n// ─── Create Command (like create-compute) ─────────────────────────────────\n\nprogram\n .command('create')\n .description('Create a new workspace (same as create-compute)')\n .argument('[repo]', 'Repository in owner/repo format')\n .option('-b, --branch <branch>', 'Branch name', 'main')\n .option('-p, --provider <provider>', 'provider to use')\n .option('--no-attach', 'Create workspace but do not attach')\n .action(async (repo, options) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n await ensureAuth();\n\n if (!repo) {\n const state = loadWorkspaceState();\n const workspaceIds = Object.keys(state.workspaces);\n\n if (workspaceIds.length > 0) {\n // Show existing workspaces to attach to\n const choices = workspaceIds.map((id) => {\n const ws = state.workspaces[id];\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : `${age}d ago`;\n return {\n value: id,\n label: `${id} (${ws.provider}, ${ageStr})`,\n };\n });\n\n const selected = await p.select({\n message: 'Select workspace to attach (or create new)',\n options: [\n ...choices,\n { value: '__new__', label: pc.gray('+ Create new workspace') },\n ],\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n if (selected !== '__new__') {\n await workspaceAttach(selected as string);\n return;\n }\n\n // Fall through to create new\n }\n\n // Prompt for repo\n const repoInput = await p.text({\n message: 'Repository to work on?',\n placeholder: 'owner/repo',\n validate: (value) => {\n if (!value || !value.includes('/')) {\n return 'Please enter a repository in owner/repo format';\n }\n },\n });\n\n if (p.isCancel(repoInput)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n repo = repoInput as string;\n }\n\n // Validate repo format\n if (!repo.includes('/')) {\n p.log.error('Invalid repository format. Use: owner/repo');\n process.exit(1);\n }\n\n const provider = await resolveProvider(options.provider, { interactive: true });\n configureCompute(provider);\n\n const spinner = p.spinner();\n spinner.start('Creating workspace...');\n\n try {\n const workspace = await workspaceCreate({\n repo,\n branch: options.branch,\n provider,\n });\n\n spinner.stop(`Workspace ready: ${pc.cyan(workspace.id)}`);\n\n if (options.attach !== false) {\n console.log();\n await workspaceAttach(workspace.id);\n } else {\n p.outro(pc.green('Workspace created!'));\n }\n } catch (error) {\n spinner.stop(pc.red('Failed to create workspace'));\n p.log.error((error as Error).message);\n process.exit(1);\n }\n });\n\n// ─── Sandbox Commands ───────────────────────────────────────────────────────\n\nconst sandboxCmd = program\n .command('sandbox')\n .alias('sb')\n .description('Manage raw sandboxes (VMs without git/worktree)');\n\nsandboxCmd\n .command('create')\n .description('Create a new sandbox')\n .option('-p, --provider <provider>', 'provider to use')\n .option('--timeout <duration>', 'sandbox timeout (e.g. 5m, 1h)')\n .option('--name <name>', 'sandbox name')\n .option('--connect', 'drop into the REPL after creation')\n .option('--silent', 'only output the sandbox ID')\n .action(async (opts) => {\n if (!opts.silent) {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n }\n\n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n if (!opts.silent) {\n const spinner = p.spinner();\n spinner.start('Creating sandbox...');\n try {\n const sandbox = await compute.sandbox.create(\n buildCreateOptions(opts),\n );\n spinner.stop(`Sandbox ready: ${pc.cyan(sandbox.sandboxId)}`);\n\n // Track the sandbox in local state\n const { saveSandbox } = await import('./workspace-cli.js');\n await saveSandbox({\n id: sandbox.sandboxId,\n sandboxId: sandbox.sandboxId,\n provider: provider,\n createdAt: new Date().toISOString(),\n lastUsed: new Date().toISOString(),\n });\n\n if (opts.connect) {\n await startREPL(sandbox, provider);\n }\n } catch (error) {\n spinner.stop(pc.red('Failed to create sandbox'));\n p.log.error((error as Error).message);\n process.exit(1);\n }\n } else {\n try {\n const sandbox = await compute.sandbox.create(\n buildCreateOptions(opts),\n );\n // Silent mode: only print sandbox ID for scripting\n process.stdout.write(sandbox.sandboxId);\n\n // Track the sandbox in local state (even in silent mode)\n const { saveSandbox } = await import('./workspace-cli.js');\n await saveSandbox({\n id: sandbox.sandboxId,\n sandboxId: sandbox.sandboxId,\n provider: provider,\n createdAt: new Date().toISOString(),\n lastUsed: new Date().toISOString(),\n });\n\n if (opts.connect) {\n await startREPL(sandbox, provider);\n }\n } catch (error) {\n process.stderr.write((error as Error).message + '\\n');\n process.exit(1);\n }\n }\n });\n\nsandboxCmd\n .command('destroy')\n .description('Destroy one or more sandboxes')\n .aliases(['rm', 'stop'])\n .argument('[sandbox_id...]', 'sandbox IDs to destroy (optional - will show picker if not provided)')\n .option('-p, --provider <provider>', 'provider to use')\n .action(async (sandboxIds: string[] | undefined, opts) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n \n // Load state\n const { loadState, saveState } = await import('./workspace-cli.js');\n const state = loadState();\n \n // If no IDs provided, show interactive picker\n if (!sandboxIds || sandboxIds.length === 0) {\n const workspaces = Object.values(state.workspaces);\n\n if (workspaces.length === 0) {\n p.log.info('No sandboxes to destroy.');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const choices = workspaces.map((ws) => {\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n const status = age > 7 ? pc.red('stale') : age > 1 ? pc.yellow('idle') : pc.green('active');\n return {\n value: ws.sandboxId,\n label: `${status} ${ws.sandboxId} (${ws.provider}, last active ${ageStr})`,\n };\n });\n\n // Allow multi-select with space, or single select with enter\n const selected = await p.multiselect({\n message: 'Select sandboxes to destroy (space to select, enter to confirm)',\n options: choices,\n });\n\n if (p.isCancel(selected) || (selected as string[]).length === 0) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n sandboxIds = selected as string[];\n }\n \n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n const results = await Promise.allSettled(\n sandboxIds.map(async (id) => {\n await compute.sandbox.destroy(id);\n return id;\n }),\n );\n\n for (const result of results) {\n if (result.status === 'fulfilled') {\n const sandboxId = result.value;\n console.log(pc.green(`Destroyed ${sandboxId}`));\n \n // Remove from state if tracked\n const workspaceId = Object.keys(state.workspaces).find(\n key => state.workspaces[key].sandboxId === sandboxId\n );\n if (workspaceId) {\n delete state.workspaces[workspaceId];\n }\n } else {\n console.error(pc.red(`Failed to destroy: ${result.reason?.message || result.reason}`));\n }\n }\n \n // Save updated state\n saveState(state);\n });\n\nsandboxCmd\n .command('list')\n .alias('ls')\n .description('List all sandboxes')\n .action(async () => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await sandboxList();\n });\n\nsandboxCmd\n .command('connect')\n .description('Connect to a sandbox (opens REPL; same as compute connect)')\n .aliases(['ssh', 'shell'])\n .argument('[sandbox_id]', 'sandbox ID (optional - will show picker if not provided)')\n .option('-p, --provider <provider>', 'provider to use')\n .action(async (sandboxId: string | undefined, opts) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n // If no sandbox_id provided, show interactive picker\n if (!sandboxId) {\n const { loadState } = await import('./workspace-cli.js');\n const state = loadState();\n const workspaces = Object.values(state.workspaces);\n\n if (workspaces.length === 0) {\n p.log.info('No sandboxes found.');\n p.log.info('Create one with: compute sandbox create');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const choices = workspaces.map((ws) => {\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n const status = age > 7 ? pc.red('stale') : age > 1 ? pc.yellow('idle') : pc.green('active');\n return {\n value: ws.sandboxId,\n label: `${status} ${ws.sandboxId} (${ws.provider}, last active ${ageStr})`,\n };\n });\n\n const selected = await p.select({\n message: 'Select sandbox to connect',\n options: choices,\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n sandboxId = selected as string;\n }\n\n const spinner = p.spinner();\n spinner.start('Connecting...');\n const sandbox = await compute.sandbox.getById(sandboxId);\n if (!sandbox) {\n spinner.stop(pc.red(`Sandbox not found: ${sandboxId}`));\n process.exit(1);\n }\n\n spinner.stop('');\n\n await startREPL(sandbox, provider);\n });\n\nsandboxCmd\n .command('exec')\n .description('Execute a command in a sandbox')\n .argument('<sandbox_id>', 'sandbox ID')\n .argument('<command...>', 'command to run')\n .option('-p, --provider <provider>', 'provider to use')\n .option('-e, --env <key=value...>', 'environment variables')\n .option('-w, --workdir <directory>', 'working directory')\n .passThroughOptions()\n .action(async (sandboxId: string, command: string[], opts) => {\n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n const sandbox = await compute.sandbox.getById(sandboxId);\n if (!sandbox) {\n console.error(pc.red(`Sandbox not found: ${sandboxId}`));\n process.exit(1);\n }\n\n const cmd = buildExecCommand(command, opts);\n const result = await sandbox.runCommand(cmd);\n\n if (result.stdout) {\n process.stdout.write(result.stdout);\n }\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n process.exit(result.exitCode);\n });\n\n// ─── Connect Command (top-level alias) ───────────────────────────────────────\n\nprogram\n .command('connect')\n .description('Connect to a sandbox (opens REPL)')\n .aliases(['ssh', 'shell']) // Keep aliases but document connect as primary\n .argument('[sandbox_id]', 'sandbox ID (optional - will show picker if not provided)')\n .option('-p, --provider <provider>', 'provider to use')\n .action(async (sandboxId: string | undefined, opts) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n // If no sandbox_id provided, show interactive picker\n if (!sandboxId) {\n const { loadState } = await import('./workspace-cli.js');\n const state = loadState();\n const workspaces = Object.values(state.workspaces);\n\n if (workspaces.length === 0) {\n p.log.info('No sandboxes found.');\n p.log.info('Create one with: compute sandbox create');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const choices = workspaces.map((ws) => {\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n const status = age > 7 ? pc.red('stale') : age > 1 ? pc.yellow('idle') : pc.green('active');\n return {\n value: ws.sandboxId,\n label: `${status} ${ws.sandboxId} (${ws.provider}, last active ${ageStr})`,\n };\n });\n\n const selected = await p.select({\n message: 'Select sandbox to connect',\n options: choices,\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n sandboxId = selected as string;\n }\n\n const spinner = p.spinner();\n spinner.start('Connecting...');\n const sandbox = await compute.sandbox.getById(sandboxId);\n if (!sandbox) {\n spinner.stop(pc.red(`Sandbox not found: ${sandboxId}`));\n process.exit(1);\n }\n\n spinner.stop('');\n\n await startREPL(sandbox, provider);\n });\n\n// ─── Workspace Commands ─────────────────────────────────────────────────────\n\nconst workspaceCmd = program\n .command('workspace')\n .alias('ws')\n .description('Manage workspaces (sandbox + git + worktree)');\n\nworkspaceCmd\n .command('create')\n .description('Create a new workspace')\n .argument('[repo]', 'Repository in owner/repo format')\n .option('-b, --branch <branch>', 'Branch name', 'main')\n .option('-p, --provider <provider>', 'provider to use')\n .option('--no-attach', 'Create workspace but do not attach')\n .action(async (repo, options) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n await ensureAuth();\n\n if (!repo) {\n p.log.info('Usage: compute workspace create owner/repo --branch main');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const provider = await resolveProvider(options.provider, { interactive: true });\n configureCompute(provider);\n\n const spinner = p.spinner();\n spinner.start('Creating workspace...');\n\n try {\n const workspace = await workspaceCreate({\n repo,\n branch: options.branch,\n provider,\n });\n\n spinner.stop(`Workspace ready: ${pc.cyan(workspace.id)}`);\n\n if (options.attach !== false) {\n console.log();\n await workspaceAttach(workspace.id);\n } else {\n p.outro(pc.green('Workspace created!'));\n }\n } catch (error) {\n spinner.stop(pc.red('Failed to create workspace'));\n p.log.error((error as Error).message);\n process.exit(1);\n }\n });\n\nworkspaceCmd\n .command('list')\n .alias('ls')\n .description('List all workspaces')\n .action(async () => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await workspaceList();\n });\n\nworkspaceCmd\n .command('destroy')\n .alias('rm')\n .description('Destroy a workspace')\n .argument('[id]', 'Workspace ID (repo:branch format, optional - will show picker if not provided)')\n .action(async (id: string | undefined) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n // If no ID provided, show interactive picker\n if (!id) {\n const state = loadWorkspaceState();\n const workspaceIds = Object.keys(state.workspaces);\n\n if (workspaceIds.length === 0) {\n p.log.info('No workspaces to destroy.');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const choices = workspaceIds.map((key) => {\n const ws = state.workspaces[key];\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n return {\n value: key,\n label: `${pc.cyan(key)} (${ws.provider}, last used ${ageStr})`,\n };\n });\n\n // Allow multi-select\n const selected = await p.multiselect({\n message: 'Select workspaces to destroy (space to select, enter to confirm)',\n options: choices,\n });\n\n if (p.isCancel(selected) || (selected as string[]).length === 0) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n // Destroy each selected workspace\n for (const workspaceId of selected as string[]) {\n await workspaceDestroy(workspaceId);\n }\n } else {\n // Direct destroy with provided ID\n await workspaceDestroy(id);\n }\n });\n\nworkspaceCmd\n .command('connect')\n .alias('attach') // Keep attach as alias\n .description('Connect to an existing workspace (with git context)')\n .argument('[id]', 'Workspace ID (optional - will show picker if not provided)')\n .action(async (id: string | undefined) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n // If no ID provided, show interactive picker\n if (!id) {\n const state = loadWorkspaceState();\n const workspaceIds = Object.keys(state.workspaces);\n\n if (workspaceIds.length === 0) {\n p.log.info('No workspaces found.');\n p.log.info('Create one with: compute create owner/repo');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const choices = workspaceIds.map((key) => {\n const ws = state.workspaces[key];\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n return {\n value: key,\n label: `${pc.cyan(key)} (${ws.provider}, last used ${ageStr})`,\n };\n });\n\n const selected = await p.select({\n message: 'Select workspace to connect',\n options: choices,\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n id = selected as string;\n }\n\n await workspaceAttach(id);\n });\n\n// ─── run ─────────────────────────────────────────────────────────────────────\n\nprogram\n .command('run')\n .description('Create a sandbox, run a command, then optionally destroy it')\n .argument('<command...>', 'command to run')\n .option('-p, --provider <provider>', 'provider to use')\n .option('-e, --env <key=value...>', 'environment variables')\n .option('-w, --workdir <directory>', 'working directory')\n .passThroughOptions()\n .option('--rm', 'destroy sandbox after command finishes')\n .option('--timeout <duration>', 'sandbox timeout (e.g. 5m, 1h)')\n .option('--name <name>', 'sandbox name')\n .action(async (command: string[], opts) => {\n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n let sandbox: SandboxInterface;\n try {\n sandbox = await compute.sandbox.create(\n buildCreateOptions(opts),\n );\n } catch (error) {\n console.error(pc.red(`Failed to create sandbox: ${(error as Error).message}`));\n process.exit(1);\n }\n\n try {\n const cmd = buildExecCommand(command, opts);\n const result = await sandbox.runCommand(cmd);\n\n if (result.stdout) {\n process.stdout.write(result.stdout);\n }\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n\n if (opts.rm) {\n await sandbox.destroy();\n }\n\n process.exit(result.exitCode);\n } catch (error) {\n if (opts.rm) {\n try { await sandbox.destroy(); } catch { /* ignore cleanup errors */ }\n }\n console.error(pc.red((error as Error).message));\n process.exit(1);\n }\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')\n .action(async () => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await ensureAuth({ forceLogin: true });\n p.outro(pc.green('Authenticated!'));\n });\n\nprogram\n .command('logout')\n .description('Clear stored credentials')\n .action(() => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n clearStoredCredentials();\n p.log.success('Logged out. Stored credentials removed.');\n p.outro(pc.green('Done!'));\n });\n\n// ─── actions ─────────────────────────────────────────────────────────────────\n\nregisterActionsCommands(program);\n\n// ─── market ──────────────────────────────────────────────────────────────────\n// `compute market` is the sell side of the compute market — same platform\n// API and auth as `compute actions`, for orgs flagged `market_provider`.\n\nregisterMarketCommands(program);\n\n// ─── sandboxes ───────────────────────────────────────────────────────────────\n// `compute sandboxes` drives /api/v1/sandboxes — the customer-facing sandbox\n// control plane (create/exec/processes/files/urls). Same auth as actions.\n\nregisterSandboxesCommands(program);\n\n// ─── bench ───────────────────────────────────────────────────────────────────\n// `compute bench` is the benchmarks-platform CLI (@benchsdk/runner's `bench`\n// binary) folded under compute: run/check/auth/org/benchmarks/runs/results/\n// iterations/artifacts/logs/export all dispatch through it.\n\nprogram\n .command('bench')\n .description('Benchmarks platform CLI (run, auth, org, benchmarks, runs, results, artifacts, export, ...)')\n .allowUnknownOption()\n .helpOption(false)\n .action(() => {\n // Never reached: bench args are dispatched pre-parse below.\n });\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction buildCreateOptions(opts: { timeout?: string; name?: string }) {\n const options: Record<string, unknown> = {};\n if (opts.timeout) {\n options.timeout = parseDuration(opts.timeout);\n }\n if (opts.name) {\n options.name = opts.name;\n }\n return options;\n}\n\nexport function shellEscape(arg: string): string {\n if (/^[a-zA-Z0-9._\\-/:=@]+$/.test(arg)) return arg;\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nfunction buildExecCommand(\n command: string[],\n opts: { env?: string[]; workdir?: string },\n): string {\n let cmd = command.map(shellEscape).join(' ');\n\n // Prepend cd if workdir is specified\n if (opts.workdir) {\n cmd = `cd ${shellEscape(opts.workdir)} && ${cmd}`;\n }\n\n // Prepend env vars if specified\n if (opts.env && opts.env.length > 0) {\n const envPrefix = opts.env\n .map((entry) => {\n const eqIndex = entry.indexOf('=');\n if (eqIndex === -1) {\n throw new Error(\n `Invalid environment entry \"${entry}\". Expected format KEY=VALUE.`,\n );\n }\n const key = entry.slice(0, eqIndex);\n const val = entry.slice(eqIndex + 1);\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {\n throw new Error(\n `Invalid environment variable name \"${key}\" in entry \"${entry}\".`,\n );\n }\n return `${key}=${shellEscape(val)}`;\n })\n .join(' ');\n cmd = `${envPrefix} ${cmd}`;\n }\n\n return cmd;\n}\n\n/**\n * Parse a human-friendly duration string to milliseconds.\n * Supports: 30s, 5m, 1h, 2h30m\n */\nfunction parseDuration(input: string): number {\n let total = 0;\n const pattern = /(\\d+)\\s*(s|m|h)/gi;\n let match;\n\n while ((match = pattern.exec(input)) !== null) {\n const value = parseInt(match[1], 10);\n const unit = match[2].toLowerCase();\n switch (unit) {\n case 's': total += value * 1000; break;\n case 'm': total += value * 60 * 1000; break;\n case 'h': total += value * 60 * 60 * 1000; break;\n }\n }\n\n if (total === 0) {\n // Try as plain number (seconds)\n const num = parseInt(input, 10);\n if (!isNaN(num)) return num * 1000;\n throw new Error(`Invalid duration: ${input}. Use formats like 30s, 5m, 1h`);\n }\n\n return total;\n}\n\n// ─── Run ─────────────────────────────────────────────────────────────────────\n\n// Bench args are opaque to commander (its own --flags, `--` separators, file\n// paths), so they dispatch before parsing. `@benchsdk/runner`'s run() owns the\n// process — it exits itself after dispatch.\nasync function main() {\n if (process.argv[2] === 'bench' || process.argv[2] === 'benchmark') {\n const { run: benchRun } = await import('@benchsdk/runner');\n await benchRun(process.argv.slice(3));\n return;\n }\n await program.parseAsync(process.argv);\n}\n\nmain().catch((error) => {\n console.error(pc.red(`\\nError: ${error.message}`));\n process.exit(1);\n});\n","/**\n * Provider detection and validation\n *\n * Detection is local: each provider declares the env vars its credentials come\n * from, and \"ready\" means all of them are set. This used to import helpers from\n * `computesdk` that the package no longer exports, which made every `compute`\n * invocation fail at module load.\n */\n\ninterface ProviderEnvSpec {\n /**\n * Alternative complete credential sets — the provider is usable when every\n * var in any one set is present (e.g. Vercel: the traditional tuple OR\n * VERCEL_OIDC_TOKEN; Namespace: NSC_TOKEN or NSC_TOKEN_FILE).\n */\n authOptions: string[][];\n /**\n * Maps each env var to the provider's nested config key (the field names in\n * the provider package's config interface, e.g. `apiKey`, `tokenId`).\n */\n configKeys: Record<string, string>;\n}\n\nconst PROVIDER_ENV: Record<string, ProviderEnvSpec> = {\n e2b: { authOptions: [['E2B_API_KEY']], configKeys: { E2B_API_KEY: 'apiKey' } },\n railway: { authOptions: [['RAILWAY_API_TOKEN']], configKeys: { RAILWAY_API_TOKEN: 'token' } },\n modal: {\n authOptions: [['MODAL_TOKEN_ID', 'MODAL_TOKEN_SECRET']],\n configKeys: { MODAL_TOKEN_ID: 'tokenId', MODAL_TOKEN_SECRET: 'tokenSecret' },\n },\n vercel: {\n authOptions: [['VERCEL_TOKEN', 'VERCEL_TEAM_ID', 'VERCEL_PROJECT_ID'], ['VERCEL_OIDC_TOKEN']],\n configKeys: {\n VERCEL_TOKEN: 'token',\n VERCEL_TEAM_ID: 'teamId',\n VERCEL_PROJECT_ID: 'projectId',\n },\n },\n daytona: { authOptions: [['DAYTONA_API_KEY']], configKeys: { DAYTONA_API_KEY: 'apiKey' } },\n namespace: {\n authOptions: [['NSC_TOKEN'], ['NSC_TOKEN_FILE']],\n configKeys: { NSC_TOKEN: 'token', NSC_TOKEN_FILE: 'tokenFile' },\n },\n blaxel: {\n authOptions: [['BL_API_KEY', 'BL_WORKSPACE']],\n configKeys: { BL_API_KEY: 'apiKey', BL_WORKSPACE: 'workspace' },\n },\n codesandbox: { authOptions: [['CSB_API_KEY']], configKeys: { CSB_API_KEY: 'apiKey' } },\n render: { authOptions: [['RENDER_API_KEY']], configKeys: { RENDER_API_KEY: 'apiKey' } },\n};\n\nconst PROVIDER_NAMES = Object.keys(PROVIDER_ENV);\n\n/** Missing vars from whichever auth option is closest to complete. */\nfunction missingEnvVars(provider: string): string[] {\n const spec = PROVIDER_ENV[provider];\n if (!spec) return [];\n let best: string[] | null = null;\n for (const option of spec.authOptions) {\n const missing = option.filter((name) => !process.env[name]);\n if (missing.length === 0) return [];\n if (!best || missing.length < best.length) best = missing;\n }\n return best ?? [];\n}\n\nfunction isProviderAuthComplete(provider: string): boolean {\n return missingEnvVars(provider).length === 0;\n}\n\n/**\n * Provider status info\n */\nexport interface ProviderStatus {\n name: string;\n ready: boolean;\n missing: string[];\n}\n\n/**\n * Detect all available providers from environment variables\n * Only includes providers supported by the ComputeSDK gateway\n */\nexport function detectAvailableProviders(): string[] {\n const available: string[] = [];\n\n // Check for computesdk first (ComputeSDK native - just needs gateway key)\n if (process.env.COMPUTESDK_API_KEY) {\n available.push('computesdk');\n }\n\n // Then check for individual cloud providers (need their own creds)\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 * Only includes providers supported by the ComputeSDK gateway\n */\nexport function getProviderStatus(): ProviderStatus[] {\n const statuses: ProviderStatus[] = [];\n\n // Add computesdk status (ComputeSDK native)\n const hasGatewayKey = !!process.env.COMPUTESDK_API_KEY;\n statuses.push({\n name: 'computesdk',\n ready: hasGatewayKey,\n missing: hasGatewayKey ? [] : ['COMPUTESDK_API_KEY'],\n });\n\n // Add individual cloud providers (need their own creds)\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/**\n * Check if gateway mode is available\n */\nexport function isGatewayAvailable(): boolean {\n return !!process.env.COMPUTESDK_API_KEY;\n}\n\n/**\n * Build the full compute config for a provider from env vars\n */\nexport function buildProviderConfig(provider: string): Record<string, unknown> {\n const config: Record<string, unknown> = {\n provider,\n apiKey: process.env.COMPUTESDK_API_KEY, // Gateway API key (top-level)\n };\n\n // For 'computesdk' provider, nest the API key under the provider config too\n if (provider === 'computesdk') {\n config.computesdk = {\n computesdk_api_key: process.env.COMPUTESDK_API_KEY,\n };\n return config;\n }\n\n // Add provider-specific config from env vars\n const spec = PROVIDER_ENV[provider];\n if (spec) {\n const providerConfig: Record<string, string> = {};\n for (const [envVar, key] of Object.entries(spec.configKeys)) {\n const value = process.env[envVar];\n if (value) providerConfig[key] = value;\n }\n if (Object.keys(providerConfig).length > 0) {\n config[provider] = providerConfig;\n }\n }\n\n return config;\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 bench auth login` stored (refreshed silently, never prompts). The\n * gateway key from `compute login` is not used. --base-url overrides the\n * https://platform.computesdk.com default; a non-computesdk host needs\n * --allow-untrusted-host and an explicit key — stored OAuth is never sent there.\n * Every subcommand takes --json for machine-readable output — on success the\n * data, on failure the `{ ok: false, error: {...} }` envelope on stderr.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { basename, join } from 'path';\nimport {\n ActionsApiError,\n ActionsCliError,\n ActionsClient,\n encodeWatchCursor,\n isTrustedActionsHost,\n resolveActionsAuth,\n toErrorEnvelope,\n type ActionsAuth,\n type CiArtifactListItem,\n type CiJob,\n type CiLogSlice,\n type CiProviderInfo,\n type CiProviderKeyResponse,\n type CiProvidersResponse,\n type CiRepo,\n type CiRepoConnectResponse,\n type CiRepoPatchResponse,\n type CiReposResponse,\n type CiRun,\n type CiRunHistory,\n type CiRunInspection,\n type CiRunSummary,\n type CiVaultDeleteResponse,\n type CiVaultItem,\n type CiVaultKind,\n type CiVaultListResponse,\n type CiVaultRevealResponse,\n type CiVaultSaveResponse,\n type CiWorkflow,\n} from './actions-client.js';\n\n/** The jobs inside a `/state` response — a subset of CiJob, no name/steps. */\ninterface CiLiveStateJob {\n id: string;\n state: CiJob['state'];\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n placementAttempts: CiJob['placementAttempts'];\n}\n\nexport type JsonOpts = { json?: boolean };\n\nexport interface CommonOpts extends JsonOpts {\n apiKey?: string;\n baseUrl?: string;\n allowUntrustedHost?: boolean;\n}\n\n/** The platform API client behind both `compute actions` and `compute market`. */\nexport async function client(opts: CommonOpts): Promise<ActionsClient> {\n return new ActionsClient(await resolveActionsAuth(opts));\n}\n\n/**\n * Commands that send or read a local secret value (vault set/get, market\n * credential connect) only ever talk to a trusted host: --allow-untrusted-host\n * opts an explicit API key into a host, not the secrets themselves.\n */\nexport function assertSecretValueHost(auth: ActionsAuth, what: string): void {\n if (!isTrustedActionsHost(auth.baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host',\n `Refusing to send or read ${what} at ${auth.baseUrl} — only computesdk.com and localhost hosts are allowed, even with --allow-untrusted-host.`,\n );\n }\n}\n\nexport function assertVaultValueHost(auth: ActionsAuth): void {\n assertSecretValueHost(auth, 'vault values');\n}\n\n/** A client for commands carrying a local secret value — trusted hosts only. */\nexport async function secretValueClient(opts: CommonOpts, what: string): Promise<ActionsClient> {\n const auth = await resolveActionsAuth(opts);\n assertSecretValueHost(auth, what);\n return new ActionsClient(auth);\n}\n\nasync function vaultValueClient(opts: CommonOpts): Promise<ActionsClient> {\n return secretValueClient(opts, 'vault values');\n}\n\n/** Print `data` as JSON when --json was passed; otherwise call `render`. */\nexport function output<T>(opts: JsonOpts, data: T, render: (data: T) => void): void {\n if (opts.json) {\n process.stdout.write(JSON.stringify(data, null, 2) + '\\n');\n } else {\n render(data);\n }\n}\n\n/** The run's job list: full detail when the runs detail route exists, else the\n * live-state route (which predates it and lists jobs without names). */\nasync function listRunJobs(c: ActionsClient, runId: string): Promise<CiJob[]> {\n try {\n const run = await c.get<CiRun>(`/api/v1/actions/runs/${runId}`);\n return run.jobs;\n } catch (e) {\n if (!(e instanceof ActionsApiError) || e.status !== 404) throw e;\n }\n const state = await c.get<{ jobs: CiLiveStateJob[] }>(`/api/v1/actions/runs/${runId}/state`);\n return state.jobs.map((j) => ({\n id: j.id,\n name: j.id.slice(0, 8), // the live-state route does not carry job names\n needs: [],\n workflowJobId: null,\n matrix: null,\n state: j.state,\n provider: j.provider,\n region: j.region,\n sandboxId: j.sandboxId,\n placementAttempts: j.placementAttempts,\n durationMs: null,\n steps: [],\n }));\n}\n\n/** The run's failure digest; null when the summary cannot be fetched. */\nasync function fetchRunSummary(c: ActionsClient, runId: string): Promise<CiRunSummary | null> {\n try {\n return await c.get<CiRunSummary>(`/api/v1/actions/runs/${runId}/summary`);\n } catch (e) {\n // The digest rides along with `actions run`; a deployment without the\n // route or a summary error must not hide the run detail itself. The\n // `summary` command fetches directly so its own errors still surface.\n if (!(e instanceof ActionsApiError && e.status === 404)) {\n console.error(\n pc.dim(`summary unavailable: ${e instanceof Error ? e.message : String(e)}`),\n );\n }\n return null;\n }\n}\n\n/**\n * Report an error and exit 1. With --json the stderr line is the stable\n * envelope from `toErrorEnvelope` (stdout stays empty, so a consumer can parse\n * either stream without guessing); otherwise a one-line human message.\n */\nexport function fail(error: unknown, opts: JsonOpts = {}): never {\n if (opts.json) {\n process.stderr.write(JSON.stringify(toErrorEnvelope(error)) + '\\n');\n } else if (error instanceof ActionsApiError) {\n console.error(pc.red(`Error (${error.status}): ${error.message}`));\n } else {\n console.error(pc.red(`Error: ${error instanceof Error ? error.message : String(error)}`));\n }\n process.exit(1);\n}\n\n/**\n * Commander's own usage errors (unknown option, missing required option or\n * argument) are raised before any action runs, so `fail` never sees them.\n * Route them through the same envelope when --json is among the raw args.\n */\nexport function usageErrorOutput(str: string, write: (str: string) => void, argv: string[] = process.argv): void {\n if (argv.includes('--json')) {\n const message = str.replace(/^error:\\s*/i, '').trim();\n write(JSON.stringify(toErrorEnvelope(new ActionsCliError('invalid_argument', message))) + '\\n');\n } else {\n write(str);\n }\n}\n\n// ─── Formatting (pure, exported for tests) ──────────────────────────────────\n\nexport function formatDuration(ms: number | null | undefined): string {\n if (ms === null || ms === undefined) return '-';\n if (ms < 1000) return `${ms}ms`;\n const s = Math.round(ms / 1000);\n if (s < 60) return `${s}s`;\n const m = Math.floor(s / 60);\n if (m < 60) return `${m}m${s % 60}s`;\n const h = Math.floor(m / 60);\n return `${h}h${m % 60}m`;\n}\n\nexport function shortSha(sha: string): string {\n return sha.slice(0, 8);\n}\n\nexport function conclusionLabel(conclusion: string): string {\n switch (conclusion) {\n case 'passed': return pc.green('passed');\n case 'failed': return pc.red('failed');\n case 'running': return pc.yellow('running');\n case 'cancelled': return pc.gray('cancelled');\n case 'none': return pc.yellow('queued');\n default: return conclusion;\n }\n}\n\nexport function formatRunRow(run: CiRun): string {\n const num = run.runNumber === null ? '-' : `#${run.runNumber}`;\n return [\n run.id,\n pc.dim(num),\n run.workflowName || run.workflowPath,\n conclusionLabel(run.conclusion),\n pc.dim(`${run.repoFullName}@${run.ref}`),\n shortSha(run.headSha),\n formatDuration(run.durationMs),\n run.startedAt,\n ].join(' ');\n}\n\nexport function formatRunDetail(run: CiRun, runUrl?: string): string {\n const lines: string[] = [];\n lines.push(`${pc.bold(run.workflowName || run.workflowPath)} ${conclusionLabel(run.conclusion)}`);\n lines.push(pc.dim(`run ${run.id}${run.runNumber === null ? '' : ` #${run.runNumber}`}`));\n lines.push(`${run.repoFullName} @ ${run.ref} ${shortSha(run.headSha)} ${run.event}${run.prNumber ? ` PR #${run.prNumber}` : ''}`);\n lines.push(`title: ${run.title}`);\n lines.push(`started: ${run.startedAt} duration: ${formatDuration(run.durationMs)}`);\n if (run.cancellationReason) lines.push(`cancelled: ${run.cancellationReason}`);\n if (run.providerOverride) lines.push(`dispatched to: ${run.providerOverride}`);\n if (run.supersededByRunId) lines.push(`superseded by: ${run.supersededByRunId}`);\n if (runUrl) lines.push(`url: ${runUrl}`);\n if (run.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of run.jobs) {\n const placement = job.provider\n ? `${job.provider}${job.region ? `:${job.region}` : ''}`\n : '-';\n lines.push(` ${job.id} ${job.name} ${conclusionLabel(job.state)} ${placement} ${formatDuration(job.durationMs)}`);\n for (const attempt of job.placementAttempts) {\n lines.push(pc.dim(` placement failed on ${attempt.provider}${attempt.region ? `:${attempt.region}` : ''}: ${attempt.error}`));\n }\n for (const step of job.steps) {\n const exit = step.exitCode === null ? '' : ` (exit ${step.exitCode})`;\n lines.push(pc.dim(` ${step.name} ${step.state}${exit} ${formatDuration(step.durationMs)}`));\n }\n }\n }\n return lines.join('\\n');\n}\n\n/** `compute actions inspect` — the run plus everything that shaped it. */\nexport function formatRunInspection(run: CiRunInspection): string {\n const lines: string[] = [];\n lines.push(`${pc.bold('run')} ${conclusionLabel(run.conclusion)}${run.runNumber === null ? '' : ` #${run.runNumber}`}`);\n lines.push(pc.dim(run.id));\n lines.push(`${safeTerm(run.ref)} ${shortSha(run.headSha)} ${safeTerm(run.event)}`);\n lines.push(`queued: ${run.queuedAt} started: ${run.startedAt} finished: ${run.finishedAt}`);\n if (run.cancellationReason) lines.push(`cancelled: ${run.cancellationReason}`);\n if (run.supersededByRunId) lines.push(`superseded by: ${run.supersededByRunId}`);\n if (run.blockedReason) lines.push(pc.red(`blocked: ${safeTerm(run.blockedReason)}`));\n if (run.concurrencyGroup) lines.push(`concurrency: ${safeTerm(run.concurrencyGroup)}`);\n if (run.providerOverride) lines.push(`dispatched to: ${safeTerm(run.providerOverride)}`);\n if (run.definitionStale) {\n const parsed = run.workflowParsedFromSha ? shortSha(run.workflowParsedFromSha) : 'unknown';\n lines.push(pc.yellow(`definition: stored parse is from ${parsed}, not this head — context may be newer than the run`));\n }\n if (run.dispatchInputs && Object.keys(run.dispatchInputs).length > 0) {\n lines.push(`inputs: ${Object.entries(run.dispatchInputs).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(' ')}`);\n }\n if (run.secrets) {\n const names = run.secrets.names.length > 0 ? run.secrets.names.map(safeTerm).join(', ') : 'none';\n lines.push(`secrets (${run.secrets.access}${run.secrets.env ? ', exported to env' : ''}): ${names}`);\n }\n if (run.caches.length > 0) {\n lines.push('');\n lines.push(pc.bold('caches'));\n for (const cache of run.caches) {\n const action = [cache.restoredAt ? 'restored' : null, cache.savedAt ? 'saved' : null]\n .filter(Boolean)\n .join('+');\n lines.push(` ${safeTerm(cache.key)} ${pc.dim(`${action} ${safeTerm(cache.scopeRef)} ${cache.sizeBytes}B`)}`);\n }\n }\n if (run.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of run.jobs) {\n const placement = job.provider\n ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ''}`\n : '-';\n lines.push(` ${safeTerm(job.name)} ${conclusionLabel(job.state)} ${placement}`);\n lines.push(pc.dim(` ${job.id}`));\n if (job.runsOn.length > 0 || job.resolvedRunsOn !== null) {\n const resolved =\n job.resolvedRunsOn !== null && job.resolvedRunsOn.join(',') !== job.runsOn.join(',')\n ? ` → ${job.resolvedRunsOn.map(safeTerm).join(', ')}`\n : '';\n lines.push(` runs-on: ${job.runsOn.map(safeTerm).join(', ') || '(none)'}${resolved}`);\n }\n if (job.runsOnHasExpression) lines.push(pc.dim(' runs-on resolves at runtime (expression)'));\n if (job.container) lines.push(` container: ${safeTerm(job.container)}`);\n if (job.runnerImage) lines.push(` image: ${safeTerm(job.runnerImage)}`);\n if (job.placementHint) {\n lines.push(` pinned: ${safeTerm(job.placementHint.label)}`);\n }\n if (job.concurrencyGroup) {\n lines.push(` concurrency: ${safeTerm(job.concurrencyGroup)}${job.concurrencyCancelInProgress ? ' (cancel-in-progress)' : ''}`);\n }\n const overrides = [\n job.timeoutMinutes !== null ? `timeout ${job.timeoutMinutes}m` : null,\n job.fetchDepth !== null ? `fetch-depth ${job.fetchDepth}` : null,\n ].filter(Boolean);\n if (overrides.length > 0) lines.push(` ${overrides.join(' ')}`);\n if (job.matrix) {\n lines.push(` matrix: ${Object.entries(job.matrix).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(' ')}`);\n }\n if (job.failureReason) lines.push(pc.red(` failed: ${safeTerm(job.failureReason)}`));\n for (const attempt of job.placementAttempts) {\n lines.push(pc.dim(` placement failed on ${safeTerm(attempt.provider)}${attempt.region ? `:${safeTerm(attempt.region)}` : ''}: ${safeTerm(attempt.error)}`));\n }\n }\n }\n return lines.join('\\n');\n}\n\n/** The failure digest rendered for humans — shared by `run` and `summary`. */\nexport function formatRunSummary(summary: CiRunSummary): string {\n const lines: string[] = [];\n lines.push(pc.bold(`failures — run ${summary.runId} ${conclusionLabel(summary.conclusion)}`));\n if (summary.failures.length === 0) {\n lines.push(' no failed jobs');\n return lines.join('\\n');\n }\n for (const job of summary.failures) {\n const placement = job.provider\n ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ''}`\n : '-';\n lines.push(` ${job.id} ${safeTerm(job.name)} ${conclusionLabel(job.conclusion)} ${placement}`);\n if (job.failureReason) lines.push(pc.dim(` ${safeTerm(job.failureReason)}`));\n for (const step of job.failedSteps) {\n const exit = step.exitCode === null ? '' : ` (exit ${step.exitCode})`;\n lines.push(` step ${step.ordinal} ${safeTerm(step.name)}${exit}`);\n }\n if (job.excerpt) {\n const scope = job.excerpt.stepOrdinal === null ? 'job log' : `step ${job.excerpt.stepOrdinal}`;\n const cut = job.excerpt.truncated ? ', truncated' : '';\n lines.push(pc.dim(` ── ${scope} tail${cut} ──`));\n for (const line of job.excerpt.text.split('\\n')) lines.push(` ${safeTerm(line)}`);\n }\n }\n return lines.join('\\n');\n}\n\n// ─── Parsing helpers (pure, exported for tests) ─────────────────────────────\n\n/** `--inputs k=v` pairs → a dispatch inputs object. `k=v` with no `=` is an error. */\nexport function parseInputs(pairs: string[] | undefined): Record<string, string> {\n const inputs: Record<string, string> = {};\n for (const pair of pairs ?? []) {\n const eq = pair.indexOf('=');\n if (eq === -1) {\n throw new ActionsCliError('invalid_argument', `Invalid --inputs entry \"${pair}\". Expected key=value.`);\n }\n inputs[pair.slice(0, eq)] = pair.slice(eq + 1);\n }\n return inputs;\n}\n\n/** Match `--workflow` to a workflow by path first, then by name. */\nexport function matchWorkflow(\n workflows: CiWorkflow[],\n selector: string,\n): CiWorkflow | undefined {\n return (\n workflows.find((w) => w.path === selector) ??\n workflows.find((w) => w.name === selector) ??\n workflows.find((w) => w.id === selector)\n );\n}\n\n/** Match `--job` to a run's job by id, then by name. */\nexport function matchJob(jobs: CiJob[], selector: string): CiJob | undefined {\n return jobs.find((j) => j.id === selector) ?? jobs.find((j) => j.name === selector);\n}\n\n// ─── Logs ───────────────────────────────────────────────────────────────────\n\nasync function readWholeJobLog(client: ActionsClient, jobId: string, step?: string): Promise<CiLogSlice> {\n const segments: CiLogSlice['segments'] = [];\n let offset = 0;\n let slice: CiLogSlice;\n do {\n slice = await client.get<CiLogSlice>(`/api/v1/actions/jobs/${jobId}/logs`, {\n offset: String(offset),\n step,\n });\n segments.push(...slice.segments);\n offset = slice.nextOffset;\n } while (slice.truncated);\n return { ...slice, segments };\n}\n\n/** Follow one job's log over the SSE `follow=1` slice stream, resuming on reconnect. */\nasync function* followJobLog(client: ActionsClient, jobId: string, step?: string): AsyncGenerator<CiLogSlice> {\n let offset = 0;\n for (;;) {\n let terminal = false;\n for await (const raw of client.sse(`/api/v1/actions/jobs/${jobId}/logs`, {\n offset: String(offset),\n follow: '1',\n step,\n })) {\n const slice = raw as CiLogSlice;\n offset = slice.nextOffset;\n if (slice.segments.length > 0 || slice.state !== 'running') yield slice;\n if (slice.state !== 'running' && slice.state !== 'pending' && !slice.truncated) {\n terminal = true;\n }\n }\n if (terminal) return;\n // The connection ended (server-side ceiling or a drop): resume from the\n // offset we hold — resumable cursors make this a continuation, not a replay.\n }\n}\n\n/** `--step` CLI value → the watch-cursor step field. */\nexport function parseStep(step: string | undefined): number | 'runner' | null {\n if (step === undefined) return null;\n if (step === 'runner') return 'runner';\n const n = Number(step);\n if (!Number.isInteger(n) || n < 0) {\n throw new ActionsCliError('invalid_argument', `Invalid --step \"${step}\". Expected a step ordinal or \"runner\".`);\n }\n return n;\n}\n\n/** Follow a run's logs across jobs via the multiplexed run stream. */\nasync function* followRunLogs(\n client: ActionsClient,\n runId: string,\n jobs: CiJob[],\n step?: string,\n): AsyncGenerator<{ job: CiJob; slice: CiLogSlice }> {\n const cursorStep = parseStep(step);\n const offsets = new Map<string, number>(jobs.map((j) => [j.id, 0]));\n const byCursor = new Map<string, CiJob>(jobs.map((j, i) => [`j${i}`, j]));\n for (;;) {\n let done = false;\n const watch = jobs.map((j, i) =>\n encodeWatchCursor(`j${i}`, j.id, cursorStep, offsets.get(j.id) ?? 0),\n );\n for await (const raw of client.sse(`/api/v1/actions/runs/${runId}/stream`, { watch })) {\n const msg = raw as\n | { type: 'state'; state: unknown }\n | { type: 'log'; cursor: string; slice: CiLogSlice }\n | { type: 'done' }\n | { type: 'reconnect' };\n if (msg.type === 'log') {\n const job = byCursor.get(msg.cursor);\n if (job) {\n offsets.set(msg.slice.jobId, msg.slice.nextOffset);\n yield { job, slice: msg.slice };\n }\n } else if (msg.type === 'done') {\n done = true;\n break;\n } else if (msg.type === 'reconnect') {\n break;\n }\n }\n if (done) return;\n // Both an explicit `reconnect` event and an unexpected EOF resume from the\n // offsets we hold; back off briefly so a repeatedly-closing server doesn't\n // spin the loop.\n await new Promise((r) => setTimeout(r, 1000));\n }\n}\n\n// Job and step names come from workflow files — potentially attacker-controlled\n// in a PR context — so strip control characters before writing to the terminal.\nexport function safeTerm(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/[\\u0000-\\u001F\\u007F-\\u009F]/g, '�');\n}\n\nexport function formatRunHistory(history: CiRunHistory): string {\n const lines: string[] = [];\n const parts = (Object.entries(history.conclusions) as [string, number][])\n .map(([c, n]) => `${n} ${c}`)\n .join(', ');\n lines.push(`last ${history.runCount} runs: ${parts || 'none'}`);\n if (history.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of history.jobs) {\n const rate = job.runs > 0 ? Math.round((job.failedRuns / job.runs) * 100) : 0;\n const platform = job.failedBeforeSteps > 0 ? pc.dim(` (${job.failedBeforeSteps} failed before steps)`) : '';\n const count = `${job.failedRuns}/${job.runs} runs failed`;\n const label = job.failedRuns > 0 ? pc.red(count) : pc.green(count);\n lines.push(` ${safeTerm(job.job)} ${label} ${rate}%${platform}`);\n for (const step of job.steps) {\n lines.push(pc.dim(` step \"${safeTerm(step.step)}\" failed in ${step.failedRuns} run${step.failedRuns === 1 ? '' : 's'}`));\n }\n }\n }\n const failed = history.runs.filter(\n (r) => r.conclusion === 'failed' || r.failedJobs.length > 0,\n );\n if (failed.length > 0) {\n lines.push('');\n lines.push(pc.bold('failed runs'));\n for (const run of failed) {\n const blame = run.failedJobs.length > 0\n ? run.failedJobs.map((j) => safeTerm(j.step === null ? j.job : `${j.job}:${j.step}`)).join(', ')\n : pc.dim('(no failed job recorded)');\n lines.push(` ${shortSha(run.headSha)} ${pc.dim(run.startedAt)} ${blame}`);\n }\n }\n return lines.join('\\n');\n}\n\nexport function formatProviderRow(p: CiProviderInfo): string {\n const icon = p.usable ? pc.green('●') : pc.gray('○');\n const name = p.usable ? pc.white(p.provider) : pc.gray(p.provider);\n const flags = [\n p.credential,\n p.actCapable ? pc.green('act') : pc.gray('no-act'),\n p.regions.length > 0 ? `regions: ${p.regions.join(',')}` : 'no region choice',\n p.position === null ? pc.gray('not in provider order') : `order #${p.position}`,\n ].join(' ');\n return ` ${icon} ${name} ${flags}`;\n}\n\nexport function formatVerifyResult(r: CiProviderKeyResponse): string {\n const ok = r.verified === true;\n const head = ok ? pc.green('verified') : pc.red('not verified');\n const detail = r.key.statusDetail ? pc.dim(` ${r.key.statusDetail}`) : '';\n const act = r.key.actCapable ? pc.green(' act-capable') : '';\n return `${head} ${r.key.provider}${act}${detail}`;\n}\n\nfunction formatRepoRow(r: CiRepo): string {\n const head = r.enabled ? pc.green('enabled') : pc.dim('disabled');\n const via = r.authType === 'github_app' ? 'github-app' : r.authType;\n const workflows =\n r.workflowPaths.length > 0\n ? `${r.workflowPaths.length} workflow${r.workflowPaths.length === 1 ? '' : 's'}`\n : 'no workflows yet';\n const error = r.lastPollError ? pc.red(` poll error: ${safeTerm(r.lastPollError)}`) : '';\n return `${head} ${safeTerm(r.fullName)} ${pc.dim(`${safeTerm(via)} · ${safeTerm(r.defaultBranch)} · ${workflows}`)}${error}`;\n}\n\n/** Print what an enable/connect discovered — one dim line, nothing on a clean run. */\nfunction printDiscovery(d: { workflowsFound: boolean; seeded: boolean; error: string | null }): void {\n if (d.error) {\n console.log(pc.yellow(`discovery: ${safeTerm(d.error)} (the poll cron retries)`));\n return;\n }\n console.log(pc.dim(`discovery: ${d.workflowsFound ? 'workflows found' : 'no workflows yet'}${d.seeded ? ', cursors seeded' : ''}`));\n}\n\n// ─── Commands ───────────────────────────────────────────────────────────────\n\n/**\n * The `POST /api/v1/actions/dispatch` body for `dispatch`. Without --manual a\n * workflow must declare `workflow_dispatch`. With it, a workflow that doesn't\n * is run anyway; such a run has no inputs, so any given are refused rather\n * than silently dropped. A dispatchable workflow keeps its inputs either way.\n */\nexport function dispatchBody(\n workflow: CiWorkflow,\n opts: {\n ref?: string;\n inputs?: string[];\n manual?: boolean;\n provider?: string;\n providerRegion?: string;\n maxBid?: string;\n maxBidPer?: string;\n },\n): Record<string, unknown> {\n if (!workflow.dispatchable && !opts.manual) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${workflow.path}\" does not declare workflow_dispatch. Pass --manual to run it anyway (no inputs).`,\n );\n }\n if (!workflow.dispatchable && opts.inputs !== undefined && opts.inputs.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${workflow.path}\" has no workflow_dispatch inputs; --manual runs of it take no --inputs.`,\n );\n }\n const ref = opts.ref ?? workflow.refs[0];\n if (!ref) throw new ActionsCliError('invalid_argument', 'No --ref given and the workflow has no watched refs.');\n if (opts.providerRegion !== undefined && opts.provider === undefined) {\n throw new ActionsCliError('invalid_argument', '--provider-region requires --provider.');\n }\n const maxPrice = maxPriceFields(opts.maxBid, opts.maxBidPer);\n return {\n workflowId: workflow.id,\n ref,\n inputs: parseInputs(opts.inputs),\n ...(opts.manual && { manual: true }),\n ...(opts.provider !== undefined && {\n provider: opts.provider,\n ...(opts.providerRegion !== undefined && { providerRegion: opts.providerRegion }),\n }),\n ...(maxPrice !== undefined && maxPrice),\n };\n}\n\n/**\n * `--max-bid`/`--max-bid-per` → the dispatch body's market price ceiling\n * fields. Undefined when no ceiling is set; the ceiling only applies to a\n * market fill — jobs that can't be filled at the price fall through to the\n * next provider-order entry.\n */\nexport function maxPriceFields(\n maxBid: string | undefined,\n maxBidPer: string | undefined,\n): { maxPriceUsd: number; maxPricePer: 'second' | 'minute' | 'hour' } | undefined {\n if (maxBidPer !== undefined && maxBid === undefined) {\n throw new ActionsCliError('invalid_argument', '--max-bid-per requires --max-bid.');\n }\n if (maxBid === undefined) return undefined;\n const usd = Number(maxBid);\n if (!/^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/.test(maxBid) || !Number.isFinite(usd) || usd <= 0) {\n throw new ActionsCliError('invalid_argument', `Invalid --max-bid \"${maxBid}\". Expected a positive dollar amount (e.g. 0.12).`);\n }\n const per = maxBidPer ?? 'second';\n if (per !== 'second' && per !== 'minute' && per !== 'hour') {\n throw new ActionsCliError('invalid_argument', `--max-bid-per must be second, minute, or hour, got \"${maxBidPer}\".`);\n }\n return { maxPriceUsd: usd, maxPricePer: per };\n}\n\n/** `--kind` for the vault commands: `secret` unless told otherwise. */\nexport function parseVaultKind(kind: string | undefined): CiVaultKind {\n if (kind === undefined || kind === 'secret' || kind === 'variable') return kind ?? 'secret';\n throw new ActionsCliError('invalid_argument', `--kind must be secret or variable, got \"${kind}\".`);\n}\n\n/** A vault route path with its scope in the query string. */\nexport function vaultPath(\n path: string,\n params: { repo?: string; kind?: CiVaultKind; name?: string },\n): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) search.set(key, value);\n }\n const query = search.toString();\n return query ? `${path}?${query}` : path;\n}\n\n/**\n * The `PUT /api/v1/vault` body for `vault set`. The value is sent exactly as\n * read — never trimmed — because whitespace can be part of a key.\n */\nexport function vaultSetBody(\n name: string,\n value: string,\n opts: { kind: CiVaultKind; revealable?: boolean; description?: string; labels?: string[] },\n): Record<string, unknown> {\n if (value === '') throw new ActionsCliError('invalid_argument', 'The value is empty.');\n if (opts.revealable && opts.kind === 'variable') {\n throw new ActionsCliError('invalid_argument', '--revealable applies to secrets; variables are always readable.');\n }\n return {\n name,\n kind: opts.kind,\n value,\n ...(opts.revealable && { revealable: true }),\n ...(opts.description !== undefined && { description: opts.description }),\n ...(opts.labels !== undefined && opts.labels.length > 0 && { labels: opts.labels }),\n };\n}\n\nexport function formatVaultRow(item: CiVaultItem): string {\n const flags = [\n item.kind,\n ...(item.revealable && item.kind === 'secret' ? ['revealable'] : []),\n `v${item.version}`,\n ...(item.source === 'organization' ? ['inherited'] : []),\n ...(item.overridesOrganization ? ['overrides org'] : []),\n ];\n return `${pc.cyan(safeTerm(item.name))} ${pc.dim(flags.join(', '))} ${pc.dim(`updated ${safeTerm(item.updatedAt)}`)}`;\n}\n\nexport function registerActionsCommands(program: Command): void {\n const actions = program\n .command('actions')\n .alias('ci')\n .description('Drive the benchmarks-platform Actions API')\n .configureOutput({ outputError: usageErrorOutput });\n\n const common = (cmd: Command) =>\n cmd\n .option('--api-key <key>', 'API key (default: $COMPUTE_API_KEY)')\n .option('--base-url <url>', 'API base URL (default: https://platform.computesdk.com)')\n .option('--allow-untrusted-host', 'send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)')\n .option('--json', 'print machine-readable JSON');\n\n common(\n actions\n .command('dispatch')\n .description('Dispatch a workflow_dispatch run (or any workflow with --manual)')\n .argument('<repo>', 'repository in owner/repo format')\n .requiredOption('--workflow <path|name>', 'workflow path or name')\n .option('--ref <ref>', 'git ref to run (default: the workflow\\'s first watched ref)')\n .option('--inputs <pairs...>', 'workflow inputs as key=value (workflow_dispatch inputs only)')\n .option('--manual', 'run a workflow even if it does not declare workflow_dispatch (such runs take no --inputs)')\n .option('--provider <id>', 'place the run on one provider (e.g. namespace, vercel:sfo1) instead of the org provider order')\n .option('--provider-region <region>', 'region for --provider (same as --provider <id>:<region>)')\n .option('--max-bid <usd>', 'max price per vCPU for a market fill (e.g. 0.12); unfilled jobs fall through to the next provider')\n .option('--max-bid-per <unit>', 'time unit --max-bid is priced in: second, minute, or hour (default: second)'),\n ).action(async (repo: string, opts: CommonOpts & { workflow: string; ref?: string; inputs?: string[]; manual?: boolean; provider?: string; providerRegion?: string; maxBid?: string; maxBidPer?: string }) => {\n try {\n const c = await client(opts);\n const { workflows } = await c.get<{ workflows: CiWorkflow[] }>(\n '/api/v1/actions/workflows',\n { repo },\n );\n const workflow = matchWorkflow(workflows, opts.workflow);\n if (!workflow) {\n const choices = workflows.map((w) => `${w.path} (${w.name})`).join(', ') || 'none';\n throw new ActionsCliError(\n 'workflow_not_found',\n `No workflow \"${opts.workflow}\" in ${repo}. Available: ${choices}`,\n );\n }\n const body = dispatchBody(workflow, opts);\n const result = await c.post<{ runId: string; created: boolean; headSha: string }>(\n '/api/v1/actions/dispatch',\n body,\n );\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${result.runId}`;\n output(opts, { ...result, url }, (r) => {\n console.log(`${r.created ? 'dispatched' : 'already running'} ${pc.cyan(r.runId)}`);\n console.log(`sha: ${r.headSha}`);\n console.log(`url: ${r.url}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('runs')\n .description('List recent runs for a repo')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--status <status...>', 'filter by conclusion: passed, failed, running, cancelled, none')\n .option('--branch <branch...>', 'filter by branch/ref'),\n ).action(async (repo: string, opts: CommonOpts & { status?: string[]; branch?: string[] }) => {\n try {\n const { runs } = await (await client(opts)).get<{ runs: CiRun[] }>(\n '/api/v1/actions/runs',\n { repo, status: opts.status, branch: opts.branch },\n );\n output(opts, runs, (rs) => {\n if (rs.length === 0) {\n console.log('No runs found.');\n return;\n }\n for (const run of rs) console.log(formatRunRow(run));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('history')\n .description('Recent run history for a workflow — per-job/step failure rates (is this failure flaky?)')\n .argument('<repo>', 'repository in owner/repo format')\n .requiredOption('--workflow <path|name>', 'workflow path or name')\n .option('--branch <branch...>', 'narrow the window to branches/refs')\n .option('--job <job>', 'narrow the rollup to one job name or workflow job id')\n .option('--limit <n>', 'runs in the window (default 10, max 50)'),\n ).action(async (repo: string, opts: CommonOpts & { workflow: string; branch?: string[]; job?: string; limit?: string }) => {\n try {\n const c = await client(opts);\n const { workflows } = await c.get<{ workflows: CiWorkflow[] }>(\n '/api/v1/actions/workflows',\n { repo },\n );\n const workflow = matchWorkflow(workflows, opts.workflow) ?? workflows.find((w) => w.path === opts.workflow);\n const workflowPath = workflow?.path ?? opts.workflow;\n const history = await c.get<CiRunHistory>('/api/v1/actions/history', {\n repo,\n workflow: workflowPath,\n branch: opts.branch,\n job: opts.job,\n limit: opts.limit,\n });\n output(opts, history, (h) => console.log(formatRunHistory(h)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('run')\n .description('Show a run: jobs, provider:region placement, placement attempts')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const run = await c.get<CiRun>(`/api/v1/actions/runs/${runId}`);\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${run.id}`;\n // A failed run's interesting part is its failure digest; on deployments\n // that have the summary route it prints inline, saving a second command.\n const summary = run.conclusion === 'failed' ? await fetchRunSummary(c, runId) : null;\n output(opts, { ...run, url, summary }, (r) => {\n console.log(formatRunDetail(r, r.url));\n if (summary && summary.failures.length > 0) {\n console.log('');\n console.log(formatRunSummary(summary));\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('summary')\n .description('Show a run\\'s failure digest: failed jobs, failed steps, bounded log tails')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const summary = await (await client(opts)).get<CiRunSummary>(`/api/v1/actions/runs/${runId}/summary`);\n output(opts, summary, (s) => console.log(formatRunSummary(s)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('inspect')\n .description('Inspect a run: resolved runner image, caches, secret names, concurrency, placement context')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const inspection = await c.get<CiRunInspection>(\n `/api/v1/actions/runs/${runId}/state`,\n );\n output(opts, inspection, (r) => console.log(formatRunInspection(r)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('logs')\n .description('Print or follow a run\\'s job logs')\n .argument('<run-id>', 'run ID')\n .option('--job <job>', 'job ID or name (default: all jobs)')\n .option('--step <step>', 'step ordinal or \"runner\" (default: whole job)')\n .option('--follow', 'stream logs while the run is live'),\n ).action(async (runId: string, opts: CommonOpts & { job?: string; step?: string; follow?: boolean }) => {\n try {\n const c = await client(opts);\n let jobs = await listRunJobs(c, runId);\n if (opts.job) {\n const job = matchJob(jobs, opts.job);\n if (!job) {\n throw new Error(\n `No job \"${opts.job}\" in run ${runId}. Jobs: ${jobs.map((j) => j.name).join(', ') || 'none'}`,\n );\n }\n jobs = [job];\n }\n if (jobs.length === 0) {\n if (opts.json) output(opts, { segments: [] }, () => {});\n else console.error('Run has no jobs yet.');\n return;\n }\n\n if (!opts.follow) {\n for (const job of jobs) {\n const slice = await readWholeJobLog(c, job.id, opts.step);\n if (opts.json) {\n process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + '\\n');\n } else {\n if (jobs.length > 1) console.log(pc.bold(`── ${job.name} ──`));\n for (const seg of slice.segments) process.stdout.write(seg.text);\n }\n }\n return;\n }\n\n if (jobs.length === 1) {\n // Single job: the slice endpoint's own SSE, resumed on reconnect.\n for await (const slice of followJobLog(c, jobs[0].id, opts.step)) {\n if (opts.json) {\n process.stdout.write(JSON.stringify(slice) + '\\n');\n } else {\n for (const seg of slice.segments) process.stdout.write(seg.text);\n }\n }\n return;\n }\n\n // Multiple jobs: one multiplexed stream, each slice tagged by job.\n for await (const { job, slice } of followRunLogs(c, runId, jobs, opts.step)) {\n if (opts.json) {\n process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + '\\n');\n } else {\n for (const seg of slice.segments) {\n const text = seg.text.replace(/\\n/g, `\\n[${job.name}] `);\n process.stdout.write(`[${job.name}] ${text}`);\n }\n }\n }\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const providers = actions\n .command('providers')\n .description('List the org\\'s registered compute providers (regions, act/usable status)');\n common(providers).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiProvidersResponse>('/api/v1/actions/providers');\n output(opts, data, (d) => {\n for (const p of d.providers) console.log(formatProviderRow(p));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('configure')\n .description('Save the org\\'s credential for a provider (owner/admin API key)')\n .argument('<provider>', 'provider id (e.g. tensorlake, blaxel)')\n .option('--key <key>', 'provider API key (single-field credentials)')\n .option('--field <pair...>', 'credential fields as name=value (multi-field providers)')\n .option('--verify', 'run the placement probe after saving'),\n ).action(async (provider: string, opts: CommonOpts & { key?: string; field?: string[]; verify?: boolean }) => {\n try {\n const c = await client(opts);\n let body: Record<string, unknown>;\n if (opts.field !== undefined) {\n if (opts.key !== undefined) throw new Error('Pass either --key or --field, not both.');\n body = { fields: parseInputs(opts.field) };\n } else if (opts.key !== undefined) {\n body = { key: opts.key };\n } else {\n throw new Error('Pass --key <key> or --field name=value.');\n }\n const saved = await c.put<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/key`,\n body,\n );\n const verification = opts.verify\n ? await c.post<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/verify`,\n )\n : undefined;\n output(opts, verification ? { key: saved.key, verification } : saved, () => {\n console.log(`saved ${saved.key.provider} ${pc.dim(saved.key.keyHint)} ${saved.key.status}`);\n if (verification) console.log(formatVerifyResult(verification));\n });\n if (verification?.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('verify')\n .description('Probe the stored provider key with a real sandbox (\"Test\" in Settings)')\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/verify`,\n );\n output(opts, result, (r) => console.log(formatVerifyResult(r)));\n if (result.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('remove')\n .description('Delete the org\\'s stored credential for a provider')\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ provider: string; deleted: boolean }>(\n `/api/v1/actions/providers/${provider}/key`,\n );\n output(opts, result, (r) => {\n console.log(r.deleted ? `deleted ${r.provider}` : `no key stored for ${r.provider}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const repos = actions\n .command('repos')\n .description('List the org\\'s connected repositories');\n common(repos).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiReposResponse>('/api/v1/actions/repos');\n output(opts, data, (d) => {\n for (const r of d.repos) console.log(formatRepoRow(r));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('connect')\n .description('Connect a git remote (validated by a real ls-remote; lands enabled)')\n .argument('<cloneUrl>', 'http(s) or ssh git remote URL')\n .option('--name <owner/repo>', 'repo name override (default: derived from cloneUrl)')\n .option('--branch <branch>', 'default branch (default: main, else the remote\\'s first)')\n .option('--token <token>', 'credential for private http(s) remotes')\n .option('--username <user>', 'username — with --token, makes auth \"basic\" instead of \"token\"')\n .option('--ssh-key-file <path>', 'OpenSSH/PEM private key file for ssh remotes')\n .option('--known-hosts-file <path>', 'known_hosts pin for ssh remotes'),\n ).action(async (cloneUrl: string, opts: CommonOpts & { name?: string; branch?: string; token?: string; username?: string; sshKeyFile?: string; knownHostsFile?: string }) => {\n try {\n let body: Record<string, unknown>;\n if (opts.sshKeyFile !== undefined) {\n if (opts.token !== undefined || opts.username !== undefined) {\n throw new Error('Pass either --ssh-key-file or --token/--username, not both.');\n }\n body = {\n authType: 'ssh',\n credential: readFileSync(opts.sshKeyFile, 'utf8'),\n ...(opts.knownHostsFile !== undefined && {\n knownHosts: readFileSync(opts.knownHostsFile, 'utf8'),\n }),\n };\n } else if (opts.username !== undefined) {\n if (opts.token === undefined) throw new Error('--username requires --token.');\n body = { authType: 'basic', username: opts.username, credential: opts.token };\n } else if (opts.token !== undefined) {\n body = { authType: 'token', credential: opts.token };\n } else {\n body = { authType: 'none' };\n }\n if (opts.knownHostsFile !== undefined && opts.sshKeyFile === undefined) {\n throw new Error('--known-hosts-file requires --ssh-key-file.');\n }\n const result = await (await client(opts)).post<CiRepoConnectResponse>('/api/v1/actions/repos', {\n cloneUrl,\n ...body,\n ...(opts.name !== undefined && { name: opts.name }),\n ...(opts.branch !== undefined && { defaultBranch: opts.branch }),\n });\n output(opts, result, (r) => {\n console.log(`connected ${pc.cyan(safeTerm(r.fullName))} ${pc.dim(`(${safeTerm(r.authType)}, ${safeTerm(r.defaultBranch)})`)}`);\n printDiscovery(r.discovery);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('enable')\n .description('Enable a repo the org can already see (granted by a GitHub App install, or a connected remote)')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--repo-id <id>', 'scope to one row when two installations grant the same name'),\n ).action(async (repo: string, opts: CommonOpts & { repoId?: string }) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: true,\n ...(opts.repoId !== undefined && { repoId: opts.repoId }),\n });\n output(opts, result, (r) => {\n console.log(`enabled ${pc.cyan(safeTerm(r.fullName))}`);\n if (r.discovery) printDiscovery(r.discovery);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('disable')\n .description('Disable a repo — it stays connected but no runs are scheduled')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--repo-id <id>', 'scope to one row when two installations grant the same name'),\n ).action(async (repo: string, opts: CommonOpts & { repoId?: string }) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: false,\n ...(opts.repoId !== undefined && { repoId: opts.repoId }),\n });\n output(opts, result, (r) => console.log(`disabled ${pc.cyan(safeTerm(r.fullName))}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const vault = actions\n .command('vault')\n .description('The org vault: secrets and variables (owner/admin key)');\n const vaultScope = (cmd: Command) =>\n common(cmd)\n .option('--repo <owner/repo>', 'scope to a repo\\'s own items instead of the org\\'s')\n .option('--kind <kind>', 'secret or variable', 'secret');\n type VaultOpts = CommonOpts & { repo?: string; kind?: string };\n\n vaultScope(\n vault.command('ls').description('List names and metadata (never values)'),\n ).action(async (opts: VaultOpts) => {\n try {\n const path = vaultPath('/api/v1/vault', { repo: opts.repo, kind: parseVaultKind(opts.kind) });\n const data = await (await client(opts)).get<CiVaultListResponse>(path);\n output(opts, data, (d) => {\n for (const item of d.items) console.log(formatVaultRow(item));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('set')\n .description('Store a value, read from stdin (or --from-file) and sent exactly as read')\n .argument('<name>', 'item name, e.g. NPM_TOKEN')\n .option('--from-file <path>', 'read the value from a file instead of stdin')\n .option('--revealable', 'let the value be read back with `vault get` (secrets; fixed at creation)')\n .option('--description <text>', 'what the item is for')\n .option('--labels <labels...>', 'labels (fixed at creation)'),\n ).action(async (name: string, opts: VaultOpts & { fromFile?: string; revealable?: boolean; description?: string; labels?: string[] }) => {\n try {\n if (opts.fromFile === undefined && process.stdin.isTTY) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Pipe the value on stdin (e.g. printf %s \"$VALUE\" | compute actions vault set NAME) or pass --from-file.',\n );\n }\n const value = readFileSync(opts.fromFile ?? 0, 'utf8');\n const kind = parseVaultKind(opts.kind);\n const body = vaultSetBody(name, value, { ...opts, kind });\n const result = await (await vaultValueClient(opts)).put<CiVaultSaveResponse>(\n vaultPath('/api/v1/vault', { repo: opts.repo }),\n body,\n );\n output(opts, result, (r) => {\n const where = opts.repo ? safeTerm(opts.repo) : 'org';\n console.log(`saved ${pc.cyan(safeTerm(r.item.name))} ${pc.dim(`(${r.item.kind}, v${r.item.version}, ${where})`)}`);\n if (/\\r?\\n$/.test(value)) {\n console.error(pc.yellow('note: the stored value ends with a newline; use printf %s rather than echo to avoid one.'));\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('get')\n .description('Print a value: any variable, or a secret created --revealable')\n .argument('<name>', 'item name'),\n ).action(async (name: string, opts: VaultOpts) => {\n try {\n const kind = parseVaultKind(opts.kind);\n const result = await (await vaultValueClient(opts)).post<CiVaultRevealResponse>(\n vaultPath('/api/v1/vault/reveal', { repo: opts.repo }),\n { name, kind },\n );\n output(opts, result, (r) => process.stdout.write(r.value));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('rm')\n .description('Delete an item (with --repo, only the repo\\'s override)')\n .argument('<name>', 'item name'),\n ).action(async (name: string, opts: VaultOpts) => {\n try {\n const path = vaultPath('/api/v1/vault', { repo: opts.repo, kind: parseVaultKind(opts.kind), name });\n const result = await (await client(opts)).del<CiVaultDeleteResponse>(path);\n output(opts, result, (r) => console.log(`deleted ${pc.cyan(safeTerm(r.name))} ${pc.dim(`(${r.kind})`)}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('cancel')\n .description('Cancel a run')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<{ cancelled: boolean }>(\n `/api/v1/actions/runs/${runId}/cancel`,\n );\n output(opts, result, (r) => {\n console.log(r.cancelled ? `Cancelled ${runId}` : `Run ${runId} was already finished`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('rerun')\n .description('Re-run a finished run at the same commit')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const result = await c.post<{ runId: string; created: boolean }>(\n `/api/v1/actions/runs/${runId}/rerun`,\n );\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${result.runId}`;\n output(opts, { ...result, url }, (r) => {\n console.log(`${r.created ? 'rerun dispatched' : 'rerun already running'} ${pc.cyan(r.runId)}`);\n console.log(`url: ${r.url}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('artifacts')\n .description('List or download a run\\'s artifacts')\n .argument('<run-id>', 'run ID')\n .option('--job <job>', 'job ID or name (default: all jobs)')\n .option('--out <dir>', 'download artifacts into this directory instead of listing'),\n ).action(async (runId: string, opts: CommonOpts & { job?: string; out?: string }) => {\n try {\n const c = await client(opts);\n let jobs = await listRunJobs(c, runId);\n if (opts.job) {\n const job = matchJob(jobs, opts.job);\n if (!job) throw new Error(`No job \"${opts.job}\" in run ${runId}.`);\n jobs = [job];\n }\n const entries: { job: CiJob; artifacts: CiArtifactListItem[] }[] = [];\n for (const job of jobs) {\n const artifacts = await c.get<CiArtifactListItem[]>(\n `/api/v1/actions/jobs/${job.id}/artifacts`,\n );\n entries.push({ job, artifacts });\n }\n\n if (opts.out) {\n const written: { jobId: string; id: string; file: string }[] = [];\n for (const { job, artifacts } of entries) {\n // Per-job directory: artifact names are not unique across jobs.\n const jobDir = join(opts.out, sanitizePathPart(job.name || job.id));\n mkdirSync(jobDir, { recursive: true });\n for (const artifact of artifacts) {\n if (artifact.expired || artifact.skippedReason) continue;\n const bytes = await c.download(\n `/api/v1/actions/jobs/${job.id}/artifacts/${artifact.id}`,\n );\n const file = join(jobDir, sanitizePathPart(artifact.fileName || artifact.name));\n writeFileSync(file, bytes);\n written.push({ jobId: job.id, id: artifact.id, file });\n }\n }\n output(opts, written, (ws) => {\n for (const w of ws) console.log(`wrote ${w.file}`);\n if (ws.length === 0) console.log('No downloadable artifacts.');\n });\n return;\n }\n\n output(opts, entries.map((e) => ({ jobId: e.job.id, job: e.job.name, artifacts: e.artifacts })), (es) => {\n let any = false;\n for (const { job, artifacts } of es) {\n for (const a of artifacts) {\n any = true;\n const flags = a.expired ? ' expired' : a.skippedReason ? ` skipped: ${a.skippedReason}` : '';\n console.log(\n `${job} ${a.id} ${a.name} ${a.contentType} ${a.byteLength}B${flags}`,\n );\n }\n }\n if (!any) console.log('No artifacts.');\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * Thin client for the benchmarks-platform Actions v1 API.\n * Types mirror the wire shapes in benchmarks-platform `lib/ci/types.ts` —\n * keep them in sync by hand; the API is the contract.\n */\n\n\nexport const DEFAULT_BASE_URL = 'https://platform.computesdk.com';\n\nexport interface ActionsAuth {\n apiKey: string;\n baseUrl: string;\n}\n\nexport interface CiWorkflowInput {\n name: string;\n description: string;\n type: 'string' | 'number' | 'boolean' | 'choice' | 'environment';\n required: boolean;\n default: string;\n options?: string[];\n}\n\nexport interface CiWorkflow {\n id: string;\n repoFullName: string;\n name: string;\n path: string;\n dispatchable: boolean;\n refs: string[];\n inputs: CiWorkflowInput[];\n schedules: unknown[];\n}\n\nexport type CiConclusion = 'passed' | 'failed' | 'running' | 'cancelled' | 'none';\nexport type CiJobState =\n | 'queued'\n | 'running'\n | 'passed'\n | 'failed'\n | 'skipped'\n | 'cancelled';\n\nexport interface CiPlacementAttempt {\n provider: string;\n region?: string | null;\n error: string;\n}\n\nexport interface CiStep {\n name: string;\n state: CiJobState;\n durationMs: number | null;\n exitCode: number | null;\n}\n\nexport interface CiJob {\n id: string;\n name: string;\n needs: string[];\n workflowJobId: string | null;\n matrix: Record<string, string> | null;\n state: CiJobState;\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n placementAttempts: CiPlacementAttempt[];\n durationMs: number | null;\n steps: CiStep[];\n}\n\nexport interface CiRun {\n id: string;\n repoFullName: string;\n ref: string;\n branchReason: string | null;\n headSha: string;\n event: string;\n prNumber: number | null;\n runNumber: number | null;\n title: string;\n workflowPath: string;\n workflowName: string;\n conclusion: CiConclusion;\n startedAt: string;\n durationMs: number | null;\n supersededByRunId: string | null;\n concurrencyGroup: string | null;\n cancellationReason: string | null;\n /** `provider[:region]` the dispatch pinned this run to, else null. */\n providerOverride?: string | null;\n jobs: CiJob[];\n logTail: string[];\n}\n\n/**\n * One job of `GET /api/v1/actions/runs/{id}/state`: the live fields plus the\n * context that decided how the job ran — resolved runner image, container\n * pin, concurrency group, timeout/fetch-depth overrides.\n */\nexport interface CiJobInspection {\n id: string;\n name: string;\n state: CiJobState;\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n startedAt: string | null;\n finishedAt: string | null;\n placementAttempts: CiPlacementAttempt[];\n /** Why the platform failed the job before steps ran, when it did. */\n failureReason: string | null;\n /** The `runs-on:` labels as declared. */\n runsOn: string[];\n /** The `computesdk:` placement pin the labels carried, when one did. */\n placementHint: { provider: string; region: string | null; label: string } | null;\n /** Labels act actually read (placement labels stripped, default substituted). */\n resolvedRunsOn: string[] | null;\n runsOnHasExpression: boolean;\n /** The image the job's steps ran in: container pin, else the mapped label. */\n runnerImage: string | null;\n /** The literal `container:` image the job declared, if any. */\n container: string | null;\n timeoutMinutes: number | null;\n /** Deepest `fetch-depth` a checkout step pinned (0 = full history). */\n fetchDepth: number | null;\n concurrencyGroup: string | null;\n concurrencyCancelInProgress: boolean;\n matrix: Record<string, string> | null;\n steps: {\n ordinal: number;\n name: string;\n state: CiJobState;\n exitCode: number | null;\n startedAt: string | null;\n finishedAt: string | null;\n }[];\n}\n\n/** A cache entry the run's window touched (saved or restored). */\nexport interface CiRunCacheTouch {\n key: string;\n version: string;\n scopeRef: string;\n sizeBytes: number;\n savedAt: string | null;\n restoredAt: string | null;\n}\n\n/** `GET /api/v1/actions/runs/{id}/state` — a run plus its effective context. */\nexport interface CiRunInspection {\n id: string;\n conclusion: CiConclusion;\n runNumber: number | null;\n ref: string;\n headSha: string;\n event: string;\n queuedAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n supersededByRunId: string | null;\n cancellationReason: string | null;\n /** Why the run was refused before placement, when it was. */\n blockedReason: string | null;\n concurrencyGroup: string | null;\n dispatchInputs: Record<string, string> | null;\n providerOverride: string | null;\n /** The commit the stored workflow definition was parsed from. */\n workflowParsedFromSha: string | null;\n /**\n * True when the stored parse came from a different commit than the run's\n * head — the definition-derived fields may then describe a newer workflow\n * than the run used (a fork pull request always shows this by design).\n */\n definitionStale: boolean;\n /** Secret *names* the jobs could reference — never values. */\n secrets: {\n access: 'declared' | 'all';\n /** Whether named secrets are also exported as job env vars. */\n env: boolean;\n names: string[];\n } | null;\n caches: CiRunCacheTouch[];\n jobs: CiJobInspection[];\n}\n\n/**\n * `GET /api/v1/actions/runs/{runId}/summary` — a run's failure digest.\n * Wire shape mirrors `CiRunSummary` in benchmarks-platform `lib/ci/run-summary.ts`.\n */\nexport interface CiRunSummaryJob {\n id: string;\n name: string;\n conclusion: CiJobState;\n provider: string | null;\n region: string | null;\n}\n\nexport interface CiRunSummaryFailedStep {\n ordinal: number;\n name: string;\n exitCode: number | null;\n}\n\nexport interface CiRunSummaryFailure extends CiRunSummaryJob {\n failureReason: string | null;\n failedSteps: CiRunSummaryFailedStep[];\n excerpt: {\n stepOrdinal: number | null;\n text: string;\n truncated: boolean;\n } | null;\n}\n\nexport interface CiRunSummary {\n runId: string;\n conclusion: CiConclusion;\n jobs: CiRunSummaryJob[];\n failures: CiRunSummaryFailure[];\n}\n\nexport interface CiArtifactListItem {\n id: string;\n name: string;\n fileName: string;\n contentType: string;\n byteLength: number;\n fileCount: number;\n skippedReason: string | null;\n expiresAt: string;\n expired: boolean;\n}\n\nexport interface CiLogSegment {\n byteOffset: number;\n stream: 'stdout' | 'stderr';\n stepOrdinal: number | null;\n text: string;\n}\n\n/** One resumable read of a job log. Resume from `nextOffset`. */\nexport interface CiLogSlice {\n jobId: string;\n fromOffset: number;\n nextOffset: number;\n totalBytes: number;\n segments: CiLogSegment[];\n state: 'running' | 'complete' | 'failed' | 'cancelled' | 'expired' | 'pending';\n truncated: boolean;\n}\n\nexport interface CiProviderInfo {\n provider: string;\n /** Selectable regions for `provider:region` order entries; empty when unknown. */\n regions: string[];\n credential: 'ambient' | 'configured' | 'not-configured';\n /** In the effective act set: built-ins, CI_ACT_PROVIDERS override, act-probe-verified keys. */\n actCapable: boolean;\n /** A placement reaching the provider finds credentials. */\n usable: boolean;\n /** 1-based position in the effective provider order, null when absent. */\n position: number | null;\n}\n\nexport interface CiProvidersResponse {\n providerOrder: string[];\n providers: CiProviderInfo[];\n}\n\n/** A saved provider credential — never carries key material, only the hint. */\nexport interface CiProviderKeyRecord {\n provider: string;\n keyHint: string;\n lastCheckedAt: string | null;\n status: 'connected' | 'error' | 'unconfigured';\n statusDetail: string | null;\n actCapable: boolean;\n credential: 'key';\n fields: unknown[];\n}\n\nexport interface CiProviderKeyResponse {\n key: CiProviderKeyRecord;\n /** Present on the verify response. */\n verified?: boolean;\n}\n\n/** One failed job inside a run-history entry — step is the first failed step. */\nexport interface CiRunJobFailure {\n job: string;\n workflowJobId: string | null;\n step: string | null;\n stepOrdinal: number | null;\n}\n\nexport interface CiRunHistoryEntry {\n id: string;\n ref: string;\n headSha: string;\n runNumber: number | null;\n conclusion: CiConclusion;\n startedAt: string;\n failedJobs: CiRunJobFailure[];\n}\n\nexport interface CiJobHistory {\n job: string;\n /** The workflow job key, when recorded; disambiguates same-named jobs. */\n workflowJobId: string | null;\n /** Runs in the window that contained this job. */\n runs: number;\n failedRuns: number;\n /** Runs where the job failed with no step blamed (platform failures). */\n failedBeforeSteps: number;\n steps: { step: string; ordinal: number; failedRuns: number }[];\n}\n\n/** `GET /api/v1/actions/history` — the window plus the rollup over it. */\nexport interface CiRunHistory {\n runCount: number;\n conclusions: Partial<Record<CiConclusion, number>>;\n jobs: CiJobHistory[];\n runs: CiRunHistoryEntry[];\n}\n\nexport interface ActionsOrg {\n organizationId: string;\n name: string;\n slug: string;\n}\n\n/**\n * One row of `GET /api/v1/actions/repos`: a repo the org can run CI on,\n * GitHub-App-granted or a generic git remote.\n */\nexport interface CiRepo {\n repoId: string;\n fullName: string;\n defaultBranch: string;\n enabled: boolean;\n private: boolean;\n forkPullRequests: boolean;\n /** `github_app` for App-granted repos; `none`/`token`/`basic`/`ssh` for remotes. */\n authType: string;\n cloneUrl: string | null;\n githubInstallationId: number | null;\n workflowPaths: string[];\n disabledWorkflowCount: number;\n lastPolledAt: string | null;\n lastPollError: string | null;\n}\n\nexport interface CiReposResponse {\n repos: CiRepo[];\n}\n\n/** What an enable/remote-connect discovered before answering. */\nexport interface CiRepoDiscovery {\n workflowsFound: boolean;\n seeded: boolean;\n error: string | null;\n}\n\nexport interface CiRepoConnectResponse {\n repoId: string | null;\n fullName: string;\n defaultBranch: string;\n authType: string;\n discovery: CiRepoDiscovery;\n}\n\nexport interface CiRepoPatchResponse {\n fullName: string;\n enabled?: boolean;\n forkPullRequests?: boolean;\n discovery: CiRepoDiscovery | null;\n}\n\nexport type CiVaultKind = 'secret' | 'variable';\n\n/** One row of `GET /api/v1/vault` — metadata only; values never list. */\nexport interface CiVaultItem {\n name: string;\n kind: CiVaultKind;\n description: string | null;\n revealable: boolean;\n labels: string[];\n version: number;\n createdAt: string;\n updatedAt: string;\n /** Present when listing or writing with `?repo=`. */\n source?: 'organization' | 'repository';\n overridesOrganization?: boolean;\n}\n\nexport interface CiVaultListResponse {\n items: CiVaultItem[];\n}\n\nexport interface CiVaultSaveResponse {\n item: CiVaultItem;\n}\n\nexport interface CiVaultRevealResponse {\n name: string;\n kind: CiVaultKind;\n value: string;\n}\n\nexport interface CiVaultDeleteResponse {\n name: string;\n kind: CiVaultKind;\n deleted: true;\n}\n\nexport class ActionsApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public body?: unknown,\n ) {\n super(message);\n this.name = 'ActionsApiError';\n }\n}\n\n/** Stable machine-readable codes for errors raised by the CLI itself. */\nexport type ActionsCliErrorCode =\n | 'no_credentials'\n | 'untrusted_host'\n | 'untrusted_host_stored_auth'\n | 'insecure_transport'\n | 'invalid_argument'\n | 'workflow_not_found';\n\n/** An error the CLI raised before or instead of an API call. */\nexport class ActionsCliError extends Error {\n constructor(\n public code: ActionsCliErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'ActionsCliError';\n }\n}\n\n/** The `--json` error envelope; `code` is stable, `message` is for humans. */\nexport interface ActionsErrorEnvelope {\n ok: false;\n error: {\n code: string;\n message: string;\n /** Present when the platform answered; absent for local/transport failures. */\n httpStatus?: number;\n retryable: boolean;\n /** The platform's `details` object, when its error response carried one. */\n details?: Record<string, unknown>;\n };\n}\n\nfunction codeForStatus(status: number): string {\n switch (status) {\n case 400: return 'bad_request';\n case 401: return 'unauthenticated';\n case 403: return 'forbidden';\n case 404: return 'not_found';\n case 409: return 'conflict';\n case 413: return 'payload_too_large';\n case 429: return 'rate_limited';\n default: return status >= 500 ? 'server_error' : 'http_error';\n }\n}\n\nfunction errorDetails(body: unknown): Record<string, unknown> | undefined {\n if (body && typeof body === 'object' && 'details' in body) {\n const details = (body as { details: unknown }).details;\n if (details && typeof details === 'object' && !Array.isArray(details)) {\n return details as Record<string, unknown>;\n }\n }\n return undefined;\n}\n\n/**\n * Classify any error thrown by an Actions command. API errors carry the HTTP\n * status; CLI errors carry their own code; a fetch rejection (DNS, refused\n * connection, TLS) is `network`; anything else is `unknown`.\n */\nexport function toErrorEnvelope(error: unknown): ActionsErrorEnvelope {\n if (error instanceof ActionsApiError) {\n const details = errorDetails(error.body);\n return {\n ok: false,\n error: {\n code: codeForStatus(error.status),\n message: error.message,\n httpStatus: error.status,\n retryable: error.status === 429 || error.status === 502 || error.status === 503 || error.status === 504,\n ...(details !== undefined && { details }),\n },\n };\n }\n if (error instanceof ActionsCliError) {\n return { ok: false, error: { code: error.code, message: error.message, retryable: false } };\n }\n // undici/Node fetch rejects with a TypeError whose cause is the socket error.\n if (error instanceof TypeError && /fetch failed/i.test(error.message)) {\n const cause = (error as { cause?: unknown }).cause;\n const detail = cause instanceof Error ? `: ${cause.message}` : '';\n return {\n ok: false,\n error: { code: 'network', message: `${error.message}${detail}`, retryable: true },\n };\n }\n return {\n ok: false,\n error: {\n code: 'unknown',\n message: error instanceof Error ? error.message : String(error),\n retryable: false,\n },\n };\n}\n\nexport class ActionsClient {\n private orgPromise: Promise<ActionsOrg> | null = null;\n\n constructor(\n private readonly auth: ActionsAuth,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {}\n\n get baseUrl(): string {\n return this.auth.baseUrl;\n }\n\n /** The credential's org — fetched once, needed for dashboard URLs. */\n org(): Promise<ActionsOrg> {\n this.orgPromise ??= this.get<ActionsOrg>('/api/v1/actions/org');\n return this.orgPromise;\n }\n\n async get<T>(path: string, params?: Record<string, string | string[] | undefined>): Promise<T> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, { headers: this.headers() });\n return this.parse<T>(res);\n }\n\n async post<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'POST',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async put<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'PUT',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async patch<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'PATCH',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async del<T>(path: string): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'DELETE',\n headers: this.headers(),\n });\n return this.parse<T>(res);\n }\n\n /**\n * One `data:` JSON payload per SSE event. `next()` resolves to the payload,\n * or null when the stream ends. Call `close()` to abort.\n */\n async *sse(path: string, params?: Record<string, string | string[] | undefined>): AsyncGenerator<unknown> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, {\n headers: { ...this.headers(), accept: 'text/event-stream' },\n });\n if (!res.ok) {\n await this.parse(res); // throws\n }\n if (!res.body) throw new Error('SSE response has no body');\n yield* readSseEvents(res.body);\n }\n\n /**\n * `sse()` with the frame's `event:` name preserved — for streams whose\n * events are distinguished by name rather than payload shape (process\n * follow: stdout/stderr share a `{chunk}` payload).\n */\n async *sseNamed(\n path: string,\n params?: Record<string, string | string[] | undefined>,\n ): AsyncGenerator<{ event: string; data: unknown }> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, {\n headers: { ...this.headers(), accept: 'text/event-stream' },\n });\n if (!res.ok) {\n await this.parse(res); // throws\n }\n if (!res.body) throw new Error('SSE response has no body');\n yield* readSseNamedEvents(res.body);\n }\n\n /** Download bytes following redirects (artifact URLs 302 to storage). */\n async download(path: string): Promise<Uint8Array> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n headers: this.headers(),\n redirect: 'follow',\n });\n if (!res.ok) {\n const body = await res.json().catch(() => undefined);\n throw new ActionsApiError(res.status, errorMessage(body, res.status), body);\n }\n return new Uint8Array(await res.arrayBuffer());\n }\n\n private headers(): Record<string, string> {\n return { authorization: `Bearer ${this.auth.apiKey}`, accept: 'application/json' };\n }\n\n private async parse<T>(res: Response): Promise<T> {\n const body = await res.json().catch(() => undefined);\n if (!res.ok) throw new ActionsApiError(res.status, errorMessage(body, res.status), body);\n return body as T;\n }\n}\n\nfunction errorMessage(body: unknown, status: number): string {\n if (body && typeof body === 'object' && 'error' in body && typeof (body as { error: unknown }).error === 'string') {\n return (body as { error: string }).error;\n }\n return `Request failed with status ${status}`;\n}\n\n/** Minimal SSE reader: yields the JSON payload of each `data:` event. */\nexport async function* readSseEvents(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<unknown> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let idx;\n while ((idx = buffer.indexOf('\\n\\n')) !== -1) {\n const event = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n for (const line of event.split('\\n')) {\n if (line.startsWith('data: ')) {\n yield JSON.parse(line.slice(6));\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/** `readSseEvents` with the `event:` name preserved alongside the JSON payload. */\nexport async function* readSseNamedEvents(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<{ event: string; data: unknown }> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let idx;\n while ((idx = buffer.indexOf('\\n\\n')) !== -1) {\n const frame = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n let event = 'message';\n const dataLines: string[] = [];\n for (const line of frame.split('\\n')) {\n if (line.startsWith('event: ')) event = line.slice(7);\n else if (line.startsWith('data: ')) dataLines.push(line.slice(6));\n }\n if (dataLines.length > 0) {\n yield { event, data: JSON.parse(dataLines.join('\\n')) };\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/** `id:jobId:step:offset` — the run-stream watch cursor wire format. */\nexport function encodeWatchCursor(\n id: string,\n jobId: string,\n step: number | 'runner' | null,\n offset: number,\n): string {\n const stepPart = step === null ? '-' : step === 'runner' ? 'runner' : String(step);\n return `${id}:${jobId}:${stepPart}:${offset}`;\n}\n\n/** The subset of `@benchsdk/cli`'s `resolveAuth` result Actions needs. */\nexport type StoredPlatformAuth = { apiKey?: string; token?: string };\nexport type StoredPlatformAuthResolver = (opts: { baseUrl: string }) => Promise<StoredPlatformAuth>;\n\nconst NO_CREDENTIALS_HINT =\n 'Set COMPUTE_API_KEY, pass --api-key, or run `compute bench auth login`.';\n\n/**\n * Precedence: `--api-key` > `COMPUTE_API_KEY` > `BENCHMARKS_PLATFORM_API_KEY`\n * (legacy) > platform OAuth credentials stored by `compute bench auth login`\n * (`~/.benchsdk/credentials.json`, via `@benchsdk/cli`'s `resolveAuth`, which\n * refreshes an expired access token but never opens a browser). The gateway\n * key written by `compute login` is a different credential and is not used.\n */\nexport async function resolveActionsAuth(\n opts: {\n apiKey?: string;\n baseUrl?: string;\n allowUntrustedHost?: boolean;\n },\n resolveStored: StoredPlatformAuthResolver = resolveStoredPlatformAuth,\n): Promise<ActionsAuth> {\n const baseUrl = (\n opts.baseUrl ||\n process.env.COMPUTE_PLATFORM_URL ||\n process.env.BENCHMARKS_PLATFORM_URL || // legacy name\n DEFAULT_BASE_URL\n ).replace(/\\/+$/, '');\n\n // The bearer key is attached to every request, so an attacker-controlled\n // --base-url would exfiltrate it. Only trusted hosts are allowed silently;\n // anything else must be opted into with --allow-untrusted-host.\n if (!opts.allowUntrustedHost && !isTrustedActionsHost(baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host',\n `Refusing to send the API key to ${baseUrl} — it is not a computesdk.com or localhost host. ` +\n 'If this is a self-hosted/dev deployment you trust, pass --allow-untrusted-host.',\n );\n }\n // Host trust and transport security are separate: --allow-untrusted-host\n // says who may receive the key, never that it may travel in plaintext.\n if (!isSecureActionsTransport(baseUrl)) {\n throw new ActionsCliError(\n 'insecure_transport',\n `Refusing to send the API key over plaintext HTTP to ${baseUrl}. ` +\n 'Use an https:// base URL; http:// is only allowed for localhost/loopback.',\n );\n }\n\n // `||` not `??`: empty-string env vars (common in CI matrices) should fall\n // through to the next source, not count as configured.\n let apiKey =\n opts.apiKey ||\n process.env.COMPUTE_API_KEY ||\n process.env.BENCHMARKS_PLATFORM_API_KEY || // legacy name\n undefined;\n if (!apiKey) {\n // Stored platform OAuth is only ever resolved (and refreshed) for trusted\n // hosts. --allow-untrusted-host opts an explicit key into a host, not the\n // user's saved session.\n if (!isTrustedActionsHost(baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host_stored_auth',\n `Refusing to use stored platform credentials with untrusted host ${baseUrl}. ` +\n 'Pass --api-key or set COMPUTE_API_KEY to use an explicit key with --allow-untrusted-host.',\n );\n }\n let stored: StoredPlatformAuth;\n try {\n stored = await resolveStored({ baseUrl });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n // `@benchsdk/cli`'s \"nothing stored\" message names `bench` commands and\n // env vars that only apply to that CLI; keep ours for that case and\n // surface the reason only for expired/failed-refresh sessions.\n const detail = reason.startsWith('No credentials found') ? 'No API key.' : reason;\n throw new ActionsCliError('no_credentials', `${detail} ${NO_CREDENTIALS_HINT}`);\n }\n apiKey = stored.apiKey || stored.token || undefined;\n }\n if (!apiKey) {\n throw new ActionsCliError('no_credentials', `No API key. ${NO_CREDENTIALS_HINT}`);\n }\n return { apiKey, baseUrl };\n}\n\nasync function resolveStoredPlatformAuth(opts: { baseUrl: string }): Promise<StoredPlatformAuth> {\n const { resolveAuth } = await import('@benchsdk/cli');\n const auth = await resolveAuth({ baseUrl: opts.baseUrl });\n return { apiKey: auth.apiKey, token: auth.token };\n}\n\nfunction isLoopbackHost(host: string): boolean {\n return host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host === '::1';\n}\n\n/** https://, or http:// to a loopback host only. */\nexport function isSecureActionsTransport(baseUrl: string): boolean {\n let url: URL;\n try {\n url = new URL(baseUrl);\n } catch {\n return false;\n }\n if (url.protocol === 'https:') return true;\n return url.protocol === 'http:' && isLoopbackHost(url.hostname);\n}\n\n/** computesdk.com (and subdomains) or localhost — safe to receive the API key. */\nexport function isTrustedActionsHost(baseUrl: string): boolean {\n let host: string;\n try {\n host = new URL(baseUrl).hostname;\n } catch {\n return false;\n }\n return host === 'computesdk.com' || host.endsWith('.computesdk.com') || isLoopbackHost(host);\n}\n","/**\n * `compute market` — the sell side of the compute market: post listings,\n * reprice/pause/resume/withdraw them, read the book, and read payouts.\n *\n * Auth: identical to `compute actions` — --api-key / COMPUTE_API_KEY / the\n * stored `compute bench auth login` session. The key must belong to an org\n * the platform flags `market_provider`; the seller principal (which\n * executor provider these listings sell) is resolved server-side from the\n * key. Types mirror the wire shapes in benchmarks-platform `lib/market/*`\n * describe functions — keep them in sync by hand; the API is the contract.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { ActionsCliError } from './actions-client.js';\nimport {\n client,\n fail,\n output,\n parseInputs,\n safeTerm,\n secretValueClient,\n usageErrorOutput,\n type CommonOpts,\n} from './actions.js';\n\n// ─── Wire types (mirror benchmarks-platform lib/market describes) ───────────\n\nexport type MarketRatePer = 'second' | 'minute' | 'hour';\nexport type MarketAskStatus = 'live' | 'paused' | 'withdrawn';\n\n/** `describeAsk` — one row of GET /api/v1/market/asks. */\nexport interface MarketAsk {\n id: string;\n provider: string;\n region: string | null;\n size: string;\n 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 /** 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 usd: number;\n per: MarketRatePer;\n takeBps: number;\n maxConcurrent: number;\n expiresAt: string | null;\n rollover: boolean;\n updatedAt: string;\n }[];\n bids: {\n id: string;\n organizationId: string;\n size: string;\n 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 region: string | null;\n usd: number;\n per: MarketRatePer;\n /** 'replaced' = the seller took the capacity back mid-sale. */\n status: 'live' | 'closed' | 'replaced';\n createdAt: string;\n }[];\n prices: { askId: string; usd: number; per: MarketRatePer; changedAt: string }[];\n}\n\n/** One evicted sale — POST /api/v1/market/fills/:id/replace and each entry of the listing replace. */\nexport interface MarketReplacedFill {\n fillId: string;\n askId: string;\n /** Charged to the buyer — the seconds the fill actually lived. */\n settledMicroUsd: number;\n /** An Actions job on the evicted capacity re-places on the buyer's next provider. */\n jobRequeued: boolean;\n}\n\nexport type MarketReplaceFillOutcome =\n | { ok: true; fill: MarketReplacedFill }\n | { ok: false; status: number; error: string };\n\n/** POST /api/v1/market/listings/:id/replace — paused listing + per-fill outcomes. */\nexport interface MarketListingReplaceResult {\n listing: MarketAsk;\n fills: MarketReplaceFillOutcome[];\n}\n\n/** `describeSettlement` — one row of GET /api/v1/market/settlements. */\nexport interface MarketSettlement {\n id: string;\n providerId: string;\n provider?: string;\n periodStart: string;\n periodEnd: string;\n vcpuSeconds: number;\n grossUsd: number;\n netUsd: number;\n grossMicroUsd: number;\n netMicroUsd: number;\n invoiceRef: string | null;\n paidAt: string | null;\n createdAt: string;\n}\n\n// ─── Parsing helpers (pure, exported for tests) ─────────────────────────────\n\nconst USD_RE = /^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/;\nconst RATE_UNITS: MarketRatePer[] = ['second', 'minute', 'hour'];\n\n/**\n * `--price`/`--per` → the body's `usd`/`per`. Providers quote per-second, so\n * an absent --per is 'second', not an error.\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>.');\n }\n const usd = Number(price);\n if (!USD_RE.test(price) || !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).`,\n );\n }\n const unit = per ?? 'second';\n if (!RATE_UNITS.includes(unit as MarketRatePer)) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--per must be second, minute, or hour, got \"${per}\".`,\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}): 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 ...(opts.region !== undefined && { region: opts.region }),\n usd: rate.usd,\n per: rate.per,\n ...(maxConcurrent !== undefined && { maxConcurrent }),\n ...(expiresInHours !== undefined && { expiresInHours }),\n ...(opts.renew && { rollover: true }),\n };\n}\n\n/**\n * The `POST /api/v1/market/asks` update body for `price`/`pause`/`resume`:\n * `{askId, usd?, per?, maxConcurrent?, status?}` — exactly one of the\n * change fields must be present.\n */\nexport function listingPatchBody(\n listingId: string,\n change: {\n price?: string;\n per?: string;\n capacity?: string;\n status?: 'live' | 'paused';\n },\n): Record<string, unknown> {\n const body: Record<string, unknown> = { askId: listingId };\n if (change.price !== undefined || change.per !== undefined) {\n const rate = parseRate(change.price, change.per);\n body.usd = rate.usd;\n body.per = rate.per;\n }\n const maxConcurrent = parseCapacity(change.capacity);\n if (maxConcurrent !== undefined) body.maxConcurrent = maxConcurrent;\n if (change.status !== undefined) body.status = change.status;\n if (body.usd === undefined && body.maxConcurrent === undefined && body.status === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Nothing to change — pass --price, --capacity, or a status command.',\n );\n }\n return body;\n}\n\n/**\n * The env var `credential connect` reads a field from: the provider and\n * field names upper-snake-cased — tensorlake + apiKey → TENSORLAKE_API_KEY,\n * blaxel + workspace → BLAXEL_WORKSPACE, namespace + token → NAMESPACE_TOKEN.\n * Secrets belong here (or a session env), never in argv where shell history\n * keeps them.\n */\nexport function credentialEnvVar(providerId: string, fieldName: string): string {\n const snake = (s: string) =>\n s\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^A-Za-z0-9]+/g, '_')\n .toUpperCase();\n return `${snake(providerId)}_${snake(fieldName)}`;\n}\n\nexport interface CredentialResolution {\n /** Every field's value, declared fields only. */\n values: Record<string, string>;\n /** Required fields with no value from either source. */\n missing: MarketCredentialField[];\n /** Field names taken from --field (visible in shell history). */\n fromFlag: string[];\n /** The env var each declared field was looked up under. */\n envNames: Record<string, string>;\n}\n\n/**\n * Resolve each declared credential field: an explicit `--field name=value`\n * wins, then the `<PROVIDER>_<FIELD>` env var. Empty strings count as\n * missing on both.\n */\nexport function credentialValues(\n providerId: string,\n fields: MarketCredentialField[],\n overrides: Record<string, string>,\n env: Record<string, string | undefined> = process.env,\n): CredentialResolution {\n const declared = new Set(fields.map((f) => f.name));\n const unknown = Object.keys(overrides).filter((name) => !declared.has(name));\n if (unknown.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `${providerId} takes no credential field \"${unknown.join('\", \"')}\" — expected one of ${fields\n .map((f) => f.name)\n .join(', ')}.`,\n );\n }\n const values: Record<string, string> = {};\n const fromFlag: string[] = [];\n const missing: MarketCredentialField[] = [];\n const envNames: Record<string, string> = {};\n for (const field of fields) {\n envNames[field.name] = credentialEnvVar(providerId, field.name);\n const fromOverride = overrides[field.name];\n if (fromOverride !== undefined && fromOverride.trim() !== '') {\n values[field.name] = fromOverride.trim();\n fromFlag.push(field.name);\n continue;\n }\n const fromEnv = env[envNames[field.name]];\n if (fromEnv !== undefined && fromEnv.trim() !== '') {\n values[field.name] = fromEnv.trim();\n continue;\n }\n if (field.required !== false) missing.push(field);\n }\n return { values, missing, fromFlag, envNames };\n}\n\n/**\n * The `POST /api/v1/market/provider/credential` body: `{key}` for a\n * single-field executor, `{fields}` for a multi-field one — the same two\n * shapes the org provider-key routes take.\n */\nexport function credentialBody(\n fields: MarketCredentialField[],\n values: Record<string, string>,\n): Record<string, unknown> {\n if (fields.length === 1) {\n return { key: values[fields[0].name] };\n }\n return { fields: values };\n}\n\n// ─── Formatting (pure, exported for tests) ──────────────────────────────────\n\n/** `$0.12`, `$5` — micro-USD-precision dollars without trailing zeros. */\nexport function formatUsd(usd: number): string {\n return `$${usd.toFixed(6).replace(/\\.?0+$/, '')}`;\n}\n\n/** `$0.12/second` — how a listing (or offer, or sale) is priced. */\nexport function formatRate(usd: number, per: string): string {\n return `${formatUsd(usd)}/${per}`;\n}\n\n/** The human status: withdrawn > paused > expired > live. */\nexport function formatListingStatus(ask: Pick<MarketAsk, 'status' | 'live' | 'pendingUsd' | 'pendingPer'>): string {\n let label: string;\n if (ask.status === 'withdrawn') label = pc.gray('withdrawn');\n else if (ask.status === 'paused') label = pc.yellow('paused');\n else if (!ask.live) label = pc.gray('expired');\n else label = pc.green('live');\n if (ask.pendingUsd !== null && ask.pendingPer !== null) {\n label += pc.dim(` → ${formatRate(ask.pendingUsd, ask.pendingPer)} next window`);\n }\n return label;\n}\n\nexport function formatListingRow(ask: MarketAsk): string {\n const expiry = ask.expiresAt\n ? ask.rollover\n ? `renews ${ask.expiresAt}`\n : `expires ${ask.expiresAt}`\n : 'standing';\n return [\n ask.id,\n formatListingStatus(ask),\n 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 `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 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 ` ${formatRate(ask.usd, ask.per)} ${safeTerm(ask.providerName)} ${safeTerm(ask.size)} ${where} up to ${ask.maxConcurrent} at once${expiry}`,\n );\n }\n lines.push('');\n lines.push(pc.bold('buyer offers'));\n if (book.bids.length === 0) lines.push(pc.dim(' no open offers'));\n for (const bid of book.bids) {\n const where = bid.region ? safeTerm(bid.region) : 'anywhere';\n lines.push(\n ` pays up to ${formatRate(bid.maxUsd, bid.per)} ${safeTerm(bid.size)} ${where} ${pc.dim(`posted ${bid.createdAt}`)}`,\n );\n }\n lines.push('');\n lines.push(pc.bold('recent sales'));\n if (book.fills.length === 0) lines.push(pc.dim(' nothing has sold yet'));\n for (const fill of book.fills) {\n const statusNote =\n fill.status === 'replaced'\n ? pc.yellow(' replaced')\n : fill.status === 'closed'\n ? pc.gray(' closed')\n : '';\n lines.push(\n ` ${pc.dim(fill.id)} ${formatRate(fill.usd, fill.per)} ${safeTerm(fill.provider)} ${safeTerm(fill.size)} ${safeTerm(fill.region ?? '-')} ${pc.dim(fill.createdAt)}${statusNote}`,\n );\n }\n return lines.join('\\n');\n}\n\n/** `replaced f-1 settled $0.0003` (+ a note when an Actions job re-places). */\nexport function formatReplacedFill(fill: MarketReplacedFill): string {\n const settled = formatUsd(fill.settledMicroUsd / 1e6);\n const job = fill.jobRequeued\n ? pc.dim(\" — job re-places on the buyer's next provider\")\n : '';\n return `replaced ${pc.cyan(fill.fillId)} settled ${settled}${job}`;\n}\n\n/**\n * `compute market replace` resolves to exactly one endpoint: `--fill` evicts\n * one sale, a listing ID pauses the listing and evicts every sale on it.\n */\nexport function replaceTarget(\n listingId: string | undefined,\n fillId: string | undefined,\n): { path: string; scope: 'listing' | 'fill' } {\n if (fillId !== undefined) {\n return {\n path: `/api/v1/market/fills/${encodeURIComponent(fillId)}/replace`,\n scope: 'fill',\n };\n }\n if (listingId === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Nothing to replace — pass a listing ID or --fill <fill-id>.',\n );\n }\n return {\n path: `/api/v1/market/listings/${encodeURIComponent(listingId)}/replace`,\n scope: 'listing',\n };\n}\n\nexport function formatSettlementRow(s: MarketSettlement): string {\n const period = `${s.periodStart.slice(0, 10)} → ${s.periodEnd.slice(0, 10)}`;\n const paid = s.paidAt\n ? pc.green(`paid ${s.paidAt.slice(0, 10)}`)\n : s.invoiceRef\n ? pc.yellow(`invoiced ${safeTerm(s.invoiceRef)}`)\n : pc.dim('unpaid');\n return [\n pc.dim(period),\n `${s.vcpuSeconds.toLocaleString('en-US')} vCPU·s`,\n `gross ${formatUsd(s.grossUsd)}`,\n `net ${formatUsd(s.netUsd)}`,\n paid,\n ].join(' ');\n}\n\n// ─── Commands ───────────────────────────────────────────────────────────────\n\nexport function registerMarketCommands(program: Command): void {\n const market = program\n .command('market')\n .description('Sell compute capacity on the compute market')\n .configureOutput({ outputError: usageErrorOutput });\n\n const common = (cmd: Command) =>\n cmd\n .option('--api-key <key>', 'API key (default: $COMPUTE_API_KEY)')\n .option('--base-url <url>', 'API base URL (default: https://platform.computesdk.com)')\n .option('--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>', 'price per unit of time (e.g. 0.12)')\n .option('--per <unit>', 'time unit the price is per: second, minute, or hour (default: second)')\n .option('--size <tier>', 'size tier to sell (default: medium, else the provider\\'s first tier)')\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 }) => {\n try {\n const c = await client(opts);\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 }),\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>', 'new price per unit of time (e.g. 0.08)')\n .option('--per <unit>', 'time unit the price is per: second, minute, or hour (default: second)'),\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 ).action(async (opts: CommonOpts) => {\n try {\n const book = await (await client(opts)).get<MarketOrderBook>(\n '/api/v1/market/book',\n );\n output(opts, book, (b) => console.log(formatBook(b)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('settlements')\n .description('Your monthly payout reports'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { settlements } = await (await client(opts)).get<{\n settlements: MarketSettlement[];\n }>('/api/v1/market/settlements');\n output(opts, settlements, (rows) => {\n if (rows.length === 0) {\n console.log('No settlements yet.');\n return;\n }\n for (const s of rows) console.log(formatSettlementRow(s));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('status')\n .description('Who you are on the market: seller identity, credential, sizes, regions'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { provider } = await (await client(opts)).get<{\n provider: MarketProvider;\n }>('/api/v1/market/provider');\n output(opts, provider, (p) => console.log(formatProviderStatus(p)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const credential = market\n .command('credential')\n .description('Connect the credential your listings fill under');\n\n common(\n credential\n .command('connect')\n .description(\n 'Save the executor credential your sold capacity runs under. Each field is read from\\n' +\n 'a <PROVIDER>_<FIELD> env var (e.g. TENSORLAKE_API_KEY) — never pass secrets in argv;\\n' +\n '--field name=value overrides a field (visible in shell history)',\n )\n .option('--field <pairs...>', 'credential fields as name=value (prefer env vars for secrets)'),\n ).action(async (opts: CommonOpts & { field?: string[] }) => {\n try {\n const c = await secretValueClient(opts, 'credential values');\n const { provider } = await c.get<{ provider: MarketProvider }>(\n '/api/v1/market/provider',\n );\n if (provider.credentialFields.length === 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `${provider.provider} authenticates with the deployment's own identity — there is no credential to connect.`,\n );\n }\n const resolved = credentialValues(\n provider.provider,\n provider.credentialFields,\n parseInputs(opts.field),\n );\n if (resolved.missing.length > 0) {\n const hints = resolved.missing\n .map((f) => ` export ${resolved.envNames[f.name]}=… # ${f.label}`)\n .join('\\n');\n throw new ActionsCliError(\n 'invalid_argument',\n `Missing credential field${resolved.missing.length === 1 ? '' : 's'}. Set:\\n${hints}`,\n );\n }\n if (resolved.fromFlag.some((name) => provider.credentialFields.find((f) => f.name === name)?.secret)) {\n console.error(\n pc.yellow('note: a secret passed via --field stays in your shell history — prefer the env vars.'),\n );\n }\n const result = await c.post<{ provider: MarketProvider }>(\n '/api/v1/market/provider/credential',\n credentialBody(provider.credentialFields, resolved.values),\n );\n output(opts, result, (r) => {\n console.log(`connected ${pc.cyan(safeTerm(r.provider.name))} credential saved`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n credential\n .command('disconnect')\n .description('Remove the stored credential — listings stop filling until a new one connects'),\n ).action(async (opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ provider: MarketProvider }>(\n '/api/v1/market/provider/credential',\n );\n output(opts, result, (r) => {\n console.log(`disconnected ${pc.cyan(safeTerm(r.provider.name))} credential removed`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * `compute sandboxes` — drive sandboxes placed through the platform's\n * `/api/v1/sandboxes` API: create/list/get/destroy, exec commands, spawn and\n * control detached processes, read/write the filesystem, and resolve port\n * URLs.\n *\n * Auth: identical to `compute actions`/`compute market` — --api-key /\n * COMPUTE_API_KEY / the stored `compute bench auth login` session. Types\n * mirror the wire shapes in benchmarks-platform `lib/sandboxes/*` — keep\n * them in sync by hand; the API is the contract.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport type { ActionsClient } from './actions-client.js';\nimport {\n client,\n fail,\n output,\n parseInputs,\n safeTerm,\n usageErrorOutput,\n type CommonOpts,\n} from './actions.js';\n\n// ─── Wire types (mirror benchmarks-platform lib/sandboxes) ──────────────────\n\nexport interface SandboxCost {\n rate: { usd: number; unit: string } | null;\n runtimeSeconds: number;\n costUsd: number | null;\n settled: boolean;\n}\n\n/** `toSummary` — one row of GET /api/v1/sandboxes. */\nexport interface SandboxSummary {\n id: string;\n label: string | null;\n provider: string | null;\n providerSandboxId: string | null;\n status: 'creating' | 'running' | 'destroyed' | string;\n placementAttempts: unknown[];\n commandCount: number;\n secrets: string[];\n createdAt: string;\n lastCommandAt: string | null;\n destroyedAt: string | null;\n destroyError: string | null;\n cost: SandboxCost;\n}\n\n/** `toDetail` — POST /sandboxes and GET /sandboxes/{id}. */\nexport interface SandboxDetail extends SandboxSummary {\n /** BYOK direct-attach descriptor — null on market fills and ambient providers. */\n attach: { provider: string; providerSandboxId: string } | null;\n}\n\nexport interface SandboxProcess {\n id: string;\n jobId: string;\n pid: number | null;\n command: string;\n cwd: string | null;\n envNames: string[];\n status: string;\n exitCode: number | null;\n signal: string | null;\n startedAt: string;\n exitedAt: string | null;\n}\n\nexport interface SandboxProcessStatus extends SandboxProcess {\n stdout: string;\n stderr: string;\n}\n\nexport interface CommandResult {\n commandId: string;\n exitCode: number;\n durationMs: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface FileEntry {\n name: string;\n type: 'file' | 'directory';\n size?: number;\n modified?: string;\n}\n\nexport type PathView =\n | { path: string; type: 'file'; content: string }\n | { path: string; type: 'directory'; entries: FileEntry[] };\n\n/** POSIX single-quote: argv survives intact through the remote `sh -lc`. */\nfunction shellQuote(arg: string): string {\n return `'${arg.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// ─── Rendering ───────────────────────────────────────────────────────────────\n\nfunction printSandbox(s: SandboxSummary): void {\n const attach = 'attach' in s ? (s as SandboxDetail).attach : undefined;\n console.log(`${pc.cyan(s.id)} ${s.status} ${s.provider ?? '—'} ${s.providerSandboxId ?? '—'}`);\n console.log(` label: ${s.label ?? '—'} commands: ${s.commandCount} created: ${s.createdAt}`);\n if (s.destroyError) console.log(` destroyError: ${pc.red(s.destroyError)}`);\n if (attach !== undefined) {\n console.log(\n attach === null\n ? ' attach: none (market fill or ambient provider — platform drive only)'\n : ` attach: ${attach.provider} / ${attach.providerSandboxId}`,\n );\n }\n}\n\nfunction printProcess(p: SandboxProcess | SandboxProcessStatus): void {\n const exit = p.status === 'exited' ? `exit=${p.exitCode ?? '?'}${p.signal ? ` (${p.signal})` : ''}` : '';\n console.log(`${pc.cyan(p.jobId)} ${p.status}${exit ? ' ' + exit : ''} ${p.command}`);\n}\n\n// ─── Commands ────────────────────────────────────────────────────────────────\n\nexport function registerSandboxesCommands(program: Command): void {\n const cmd = program\n .command('sandboxes')\n .alias('sbx')\n .description('Create and drive sandboxes through the platform')\n .configureOutput({ outputError: usageErrorOutput });\n\n cmd\n .command('create')\n .description('Place a sandbox (provider order walks 1,2,3; \"market\" bids first)')\n .option('--order <providers>', 'provider order, comma-separated (e.g. \"market,blaxel,vercel\")')\n .option('--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')\n .option('--memory-mb <n>', 'memory in MB')\n .option('--disk-mb <n>', 'ephemeral disk in MB')\n .option('--timeout-ms <ms>', 'sandbox timeout in ms')\n .option('--secret <name>', 'vault secret name to inject (repeatable)', (v, a: string[]) => a.concat(v), [] as string[])\n .option('--api-key <key>', 'platform API key (or COMPUTE_API_KEY)')\n .option('--base-url <url>', 'platform base URL')\n .option('--allow-untrusted-host', 'allow non-computesdk.com base URLs')\n .option('--json', 'print the raw response')\n .action(async (opts: CommonOpts & {\n order?: string; label?: string; image?: string; snapshotId?: string;\n cpus?: string; memoryMb?: string; diskMb?: string; timeoutMs?: string;\n secret?: string[];\n }) => {\n try {\n const c = await client(opts);\n const resources: Record<string, number> = {};\n if (opts.cpus) resources.cpus = Number(opts.cpus);\n if (opts.memoryMb) resources.memoryMb = Number(opts.memoryMb);\n if (opts.diskMb) resources.ephemeralDiskMb = Number(opts.diskMb);\n const body: Record<string, unknown> = {};\n if (opts.order) body.providerOrder = opts.order.split(',').map((s) => s.trim());\n if (opts.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 res = await c.post<{ sandbox: SandboxDetail }>('/api/v1/sandboxes', body);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('list')\n .description('List sandboxes')\n .option('--status <status>', 'creating | running | destroyed')\n .option('--limit <n>', 'page size')\n .option('--cursor <cursor>', 'page cursor from a previous response')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (opts: CommonOpts & { status?: string; limit?: string; cursor?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ sandboxes: SandboxSummary[]; nextCursor: string | null }>(\n '/api/v1/sandboxes',\n { status: opts.status, limit: opts.limit, cursor: opts.cursor },\n );\n output(opts, res, (page) => {\n page.sandboxes.forEach(printSandbox);\n if (page.nextCursor) console.log(pc.dim(`nextCursor: ${page.nextCursor}`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('get <sandboxId>')\n .description('Show one sandbox (includes the BYOK attach descriptor)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ sandbox: SandboxDetail }>(`/api/v1/sandboxes/${sandboxId}`);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('destroy <sandboxId>')\n .description('Destroy a sandbox (verified teardown + cost settle)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.del<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${sandboxId}`);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('exec <sandboxId> <command...>')\n .description('Run a one-shot command and print its result')\n .option('--timeout-ms <ms>', 'command timeout in ms')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, command: string[], opts: CommonOpts & { timeoutMs?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ commandId: string } & CommandResult>(\n `/api/v1/sandboxes/${sandboxId}/commands`,\n {\n command: command.map(shellQuote).join(' '),\n ...(opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}),\n },\n );\n output(opts, res, (r) => {\n process.stdout.write(r.stdout);\n if (r.stderr) process.stderr.write(r.stderr);\n if (!r.stdout) console.log(`exit ${r.exitCode} (${r.durationMs}ms)`);\n });\n // exitCode, not exit(): a piped stdout flushes before the CLI exits.\n if (res.exitCode !== 0) process.exitCode = res.exitCode;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('spawn <sandboxId> <command...>')\n .description('Start a detached process that outlives this request')\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('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, command: string[], opts: CommonOpts & { cwd?: string; env?: string[] }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${sandboxId}/processes`,\n {\n command: command.map(shellQuote).join(' '),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {}),\n },\n );\n output(opts, res.process, printProcess);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('ps <sandboxId>')\n .description('List the sandbox\\'s tracked processes')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ processes: SandboxProcess[] }>(\n `/api/v1/sandboxes/${sandboxId}/processes`,\n );\n output(opts, res.processes, (list) => list.forEach(printProcess));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('logs <sandboxId> <jobId>')\n .description('Show a process\\'s buffered output (--follow streams until exit)')\n .option('-f, --follow', 'stream output until the process exits')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { follow?: boolean }) => {\n try {\n const c = await client(opts);\n if (opts.follow) {\n await followProcess(c, sandboxId, jobId);\n return;\n }\n const res = await c.get<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`,\n );\n output(opts, res.process, (p) => {\n if (p.stdout) process.stdout.write(p.stdout);\n if (p.stderr) process.stderr.write(p.stderr);\n if (!p.stdout && !p.stderr) printProcess(p);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('wait <sandboxId> <jobId>')\n .description('Block until a process exits')\n .option('--timeout-ms <ms>', 'bound the wait (job keeps running on timeout)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { timeoutMs?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/wait`,\n opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {},\n );\n output(opts, res.process, printProcess);\n if (res.process.status === 'exited') {\n // A null exit code (signal-terminated) is still a failure, not 0.\n process.exitCode = res.process.exitCode ?? 128;\n }\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('kill <sandboxId> <jobId>')\n .description('Signal a process (default SIGTERM)')\n .option('--signal <signal>', 'signal name or number, e.g. SIGKILL or 9')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { signal?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/kill`,\n opts.signal ? { signal: opts.signal } : {},\n );\n output(opts, res.process, printProcess);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('ls <sandboxId> [path]')\n .description('List a directory (or stat a path) inside the sandbox')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string | undefined, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${sandboxId}/files`, {\n path: path ?? '/',\n });\n output(opts, res, (view) => {\n if (view.type === 'directory') {\n for (const e of view.entries) {\n console.log(`${e.type === 'directory' ? pc.blue('d') : ' '} ${e.name}${e.size !== undefined ? ` ${pc.dim(String(e.size))}` : ''}`);\n }\n } else {\n console.log(`${view.path} file ${view.content.length} chars`);\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('cat <sandboxId> <path>')\n .description('Print a file\\'s contents')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${sandboxId}/files`, { path });\n output(opts, res, (view) => {\n if (view.type !== 'file') {\n console.error(pc.red(`${view.path} is a directory`));\n process.exit(1);\n }\n process.stdout.write(view.content);\n if (!view.content.endsWith('\\n')) process.stdout.write('\\n');\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('write <sandboxId> <path>')\n .description('Write a file inside the sandbox (--content or --file <local>, else stdin)')\n .option('--content <text>', 'file contents')\n .option('--file <local>', 'read contents from a local file')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts & { content?: string; file?: string }) => {\n try {\n let content = opts.content;\n if (content === undefined && opts.file) {\n const { readFile } = await import('node:fs/promises');\n content = await readFile(opts.file, 'utf8');\n }\n if (content === undefined && !process.stdin.isTTY) {\n content = await new Promise<string>((resolve) => {\n let data = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk) => (data += chunk));\n process.stdin.on('end', () => resolve(data));\n });\n }\n if (content === undefined) {\n console.error(pc.red('Pass --content, --file, or pipe stdin'));\n process.exit(1);\n }\n const c = await client(opts);\n const res = await c.post<{ path: string; type: string }>(\n `/api/v1/sandboxes/${sandboxId}/files`,\n { path, content },\n );\n output(opts, res, (r) => console.log(`wrote ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('mkdir <sandboxId> <path>')\n .description('Create a directory (parents included)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ path: string }>(`/api/v1/sandboxes/${sandboxId}/files`, {\n path,\n mkdir: true,\n });\n output(opts, res, (r) => console.log(`created ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('rm <sandboxId> <path>')\n .description('Remove a file or directory inside the sandbox')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.del<{ path: string; removed: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/files?path=${encodeURIComponent(path)}`,\n );\n output(opts, res, (r) => console.log(`removed ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('url <sandboxId>')\n .description('Resolve the provider\\'s public URL for a port')\n .requiredOption('--port <n>', 'port the service listens on')\n .option('--protocol <protocol>', 'protocol (default provider-chosen)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts & { port: string; protocol?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ url: string }>(`/api/v1/sandboxes/${sandboxId}/urls`, {\n port: opts.port,\n protocol: opts.protocol,\n });\n output(opts, res, (r) => console.log(safeTerm(r.url)));\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n\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 * Browser-based CLI authentication flow\n *\n * Precedence: env var > stored credentials > browser auth flow\n */\n\nimport * as http from 'node:http';\nimport * as crypto from 'node:crypto';\nimport { exec } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as os from 'os';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\n\nfunction getCredentialsDir(): string {\n return path.join(os.homedir(), '.computesdk');\n}\n\nfunction getCredentialsFile(): string {\n return path.join(getCredentialsDir(), 'credentials.json');\n}\n\nconst AUTH_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes\nconst CONSOLE_AUTH_URL = 'https://console.computesdk.com/cli/auth';\n\nconst SUCCESS_HTML = `<!DOCTYPE html>\n<html>\n<head><title>ComputeSDK CLI</title></head>\n<body style=\"font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0;\">\n <div style=\"text-align: center;\">\n <h1>Authenticated</h1>\n <p>You can close this tab and return to the terminal.</p>\n </div>\n</body>\n</html>`;\n\n/**\n * Load stored credentials from ~/.computesdk/credentials.json.\n * Returns the API key if found and valid, or null.\n */\nexport function loadStoredCredentials(): string | null {\n try {\n if (!fs.existsSync(getCredentialsFile())) {\n return null;\n }\n const raw = fs.readFileSync(getCredentialsFile(), 'utf-8');\n const data = JSON.parse(raw);\n if (typeof data.apiKey === 'string' && data.apiKey.length > 0) {\n return data.apiKey;\n }\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * Store credentials to ~/.computesdk/credentials.json.\n * Creates ~/.computesdk/ directory if it doesn't exist.\n */\nexport function storeCredentials(apiKey: string): void {\n if (!fs.existsSync(getCredentialsDir())) {\n fs.mkdirSync(getCredentialsDir(), { recursive: true, mode: 0o700 });\n }\n fs.writeFileSync(\n getCredentialsFile(),\n JSON.stringify({ apiKey }, null, 2) + '\\n',\n { mode: 0o600 }\n );\n}\n\n/**\n * Delete stored credentials file.\n */\nexport function clearStoredCredentials(): void {\n try {\n if (fs.existsSync(getCredentialsFile())) {\n fs.unlinkSync(getCredentialsFile());\n }\n } catch {\n // Ignore - file may not exist or may not be writable\n }\n}\n\n/**\n * Open a URL in the user's default browser.\n * Falls back to printing the URL if the browser fails to open.\n */\nfunction openBrowser(url: string): void {\n const command =\n process.platform === 'darwin'\n ? `open \"${url}\"`\n : process.platform === 'win32'\n ? `start \"\" \"${url}\"`\n : `xdg-open \"${url}\"`;\n\n exec(command, (err) => {\n if (err) {\n p.log.warn('Could not open browser automatically.');\n p.log.info(`Open this URL manually:\\n ${pc.cyan(url)}`);\n }\n });\n}\n\nexport interface AuthFlowOptions {\n /** Override timeout for tests */\n timeoutMs?: number;\n /** Callback when server is listening (for tests) */\n onServerReady?: (port: number, state: string) => void;\n /** Skip opening browser (for tests) */\n skipBrowserOpen?: boolean;\n}\n\n/**\n * Run the browser-based authentication flow.\n *\n * 1. Start a local HTTP server on a random port\n * 2. Open browser to console.computesdk.com/cli/auth\n * 3. Wait for callback with token and validated state\n * 4. Return the API key\n */\nexport function runBrowserAuthFlow(options?: AuthFlowOptions): Promise<string> {\n const timeoutMs = options?.timeoutMs ?? AUTH_TIMEOUT_MS;\n const state = crypto.randomBytes(32).toString('hex');\n\n return new Promise<string>((resolve, reject) => {\n const server = http.createServer();\n\n const timeout = setTimeout(() => {\n server.close();\n reject(\n new Error('Authentication timed out after 5 minutes. Please try again.')\n );\n }, timeoutMs);\n\n server.on('request', (req, res) => {\n const url = new URL(req.url || '/', 'http://localhost');\n\n if (req.method !== 'GET' || url.pathname !== '/callback') {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n return;\n }\n\n const receivedState = url.searchParams.get('state');\n const token = url.searchParams.get('token');\n\n if (receivedState !== state) {\n res.writeHead(403, { 'Content-Type': 'text/plain' });\n res.end('Error: State mismatch. Please try authenticating again.');\n return;\n }\n\n if (!token) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Error: No token received.');\n return;\n }\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(SUCCESS_HTML);\n\n clearTimeout(timeout);\n server.close();\n resolve(token);\n });\n\n server.listen(0, '127.0.0.1', () => {\n const addr = server.address();\n if (!addr || typeof addr === 'string') {\n clearTimeout(timeout);\n server.close();\n reject(new Error('Failed to start auth server'));\n return;\n }\n\n const port = addr.port;\n const authUrl = `${CONSOLE_AUTH_URL}?port=${port}&state=${state}`;\n\n if (options?.onServerReady) {\n options.onServerReady(port, state);\n }\n\n if (!options?.skipBrowserOpen) {\n openBrowser(authUrl);\n }\n });\n\n server.on('error', (err) => {\n clearTimeout(timeout);\n reject(new Error(`Auth server error: ${err.message}`));\n });\n });\n}\n\n/**\n * Resolve an API key through the precedence chain:\n * env var > stored credentials > browser auth flow\n */\nexport async function resolveApiKey(options?: {\n forceLogin?: boolean;\n}): Promise<string> {\n // 1. Check environment variable (highest precedence)\n if (process.env.COMPUTESDK_API_KEY) {\n return process.env.COMPUTESDK_API_KEY;\n }\n\n // 2. Check stored credentials (skip if forcing re-auth)\n if (!options?.forceLogin) {\n const stored = loadStoredCredentials();\n if (stored) {\n p.log.info(\n `Using stored credentials from ${pc.dim('~/.computesdk/credentials.json')}`\n );\n return stored;\n }\n }\n\n // 3. Run browser auth flow\n p.log.info('No API key found. Starting browser authentication...');\n\n const spinner = p.spinner();\n spinner.start('Waiting for browser authentication...');\n\n try {\n const apiKey = await runBrowserAuthFlow();\n spinner.stop('Authentication successful');\n\n // Store for next time\n try {\n storeCredentials(apiKey);\n p.log.success(\n `Credentials saved to ${pc.dim('~/.computesdk/credentials.json')}`\n );\n } catch {\n p.log.warn('Could not save credentials to disk. You may need to authenticate again next time.');\n }\n\n return apiKey;\n } catch (error) {\n spinner.stop(pc.red('Authentication failed'));\n throw error;\n }\n}\n","/**\n * Shared setup logic for CLI commands\n *\n * Resolves authentication and configures the compute client\n * for a given provider. Used by both subcommands and the REPL.\n */\n\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { compute } from 'computesdk';\nimport { detectAvailableProviders, getProviderStatus, buildProviderConfig, type ProviderStatus } from './providers.js';\nimport { resolveApiKey } from './auth.js';\n\n/**\n * Authenticate and set COMPUTESDK_API_KEY in the environment.\n * Exits the process on failure.\n */\nexport async function ensureAuth(options?: { forceLogin?: boolean }): Promise<void> {\n try {\n const apiKey = await resolveApiKey({ forceLogin: options?.forceLogin });\n process.env.COMPUTESDK_API_KEY = apiKey;\n } catch (error) {\n p.log.error((error as Error).message);\n p.log.info(`Get your API key at ${pc.cyan('https://console.computesdk.com')}`);\n p.outro(pc.red('Setup incomplete'));\n process.exit(1);\n }\n}\n\n/**\n * Resolve which provider to use.\n *\n * If `--provider` is given, validates it's configured and returns it.\n * If `interactive` is true and multiple providers are available, prompts user.\n * In non-interactive mode, requires `--provider` when multiple are configured.\n * Exits the process if no providers are available.\n */\nexport async function resolveProvider(\n providerFlag?: string,\n options?: { interactive?: boolean },\n): Promise<string> {\n const interactive = options?.interactive ?? false;\n const available = detectAvailableProviders();\n const providerStatus = getProviderStatus();\n\n if (providerFlag) {\n const match = providerStatus.find(\n (s: ProviderStatus) => s.name.toLowerCase() === providerFlag.toLowerCase(),\n );\n\n if (!match) {\n p.log.error(`Unknown provider: ${providerFlag}`);\n p.log.info(`Available providers: ${providerStatus.map((s: ProviderStatus) => s.name).join(', ')}`);\n process.exit(1);\n }\n\n if (!match.ready) {\n p.log.error(`Provider ${providerFlag} is not configured`);\n if (match.missing.length > 0) {\n p.log.info(`Missing env vars: ${match.missing.join(', ')}`);\n }\n process.exit(1);\n }\n\n return match.name;\n }\n\n if (available.length === 0) {\n p.log.error('No provider credentials detected');\n p.log.info('Set one of: E2B_API_KEY, MODAL_TOKEN_ID, RAILWAY_API_KEY, etc.');\n p.outro(pc.red('Setup incomplete'));\n process.exit(1);\n }\n\n // Single provider — no ambiguity\n if (available.length === 1) {\n return available[0];\n }\n\n // Multiple providers — interactive mode can prompt, non-interactive must fail\n if (!interactive) {\n p.log.error('Multiple providers configured. Use --provider to specify one.');\n p.log.info(`Available: ${available.join(', ')}`);\n process.exit(1);\n }\n\n const providerOptions = providerStatus\n .filter((status: ProviderStatus) => status.ready)\n .map((status: ProviderStatus) => ({\n value: status.name,\n label: status.name,\n }));\n\n const provider = await p.select({\n message: 'Select provider',\n options: providerOptions,\n });\n\n if (p.isCancel(provider)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n return provider as string;\n}\n\n/**\n * Configure the compute client for a provider.\n * Must be called after ensureAuth().\n */\nexport function configureCompute(provider: string): void {\n const config = buildProviderConfig(provider);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n compute.setConfig(config as any);\n}\n"],"mappings":";;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;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ACnC,UAAM,OAAO,MAAM,CAAC,EAAE,YAAY;AAClC,YAAQ,MAAM;AAAA,MACZ,KAAK;AAAK,iBAAS,QAAQ;AAAM;AAAA,MACjC,KAAK;AAAK,iBAAS,QAAQ,KAAK;AAAM;AAAA,MACtC,KAAK;AAAK,iBAAS,QAAQ,KAAK,KAAK;AAAM;AAAA,IAC7C;AAAA,EACF;AAEA,MAAI,UAAU,GAAG;AAEf,UAAM,MAAM,SAAS,OAAO,EAAE;AAC9B,QAAI,CAAC,MAAM,GAAG,EAAG,QAAO,MAAM;AAC9B,UAAM,IAAI,MAAM,qBAAqB,KAAK,gCAAgC;AAAA,EAC5E;AAEA,SAAO;AACT;AAOA,eAAe,OAAO;AACpB,MAAI,QAAQ,KAAK,CAAC,MAAM,WAAW,QAAQ,KAAK,CAAC,MAAM,aAAa;AAClE,UAAM,EAAE,KAAK,SAAS,IAAI,MAAM,OAAO,kBAAkB;AACzD,UAAM,SAAS,QAAQ,KAAK,MAAM,CAAC,CAAC;AACpC;AAAA,EACF;AACA,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAMN,IAAG,IAAI;AAAA,SAAY,MAAM,OAAO,EAAE,CAAC;AACjD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["path","pc","compute","fs","path","os","p","pc","sandbox","spinner","output","p","pc","readFileSync","fileURLToPath","dirname","join","compute","path","client","p","path","program","text","pc","pc","p","program","pc","pc","p","program","path","fs","path","os","pc","spinner","p","pc","compute","pc","compute","__filename","fileURLToPath","__dirname","dirname","readFileSync","join","pc","spinner","compute","saveSandbox","loadState","saveState","shellEscape"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.pnpm/tsup@8.5.0_jiti@2.6.1_postcss@8.5.6_tsx@4.20.3_typescript@5.8.3_yaml@2.8.2/node_modules/tsup/assets/esm_shims.js","../src/repl.ts","../src/workspace-cli.ts","../src/index.ts","../src/providers.ts","../src/actions.ts","../src/actions-client.ts","../src/market.ts","../src/sandboxes.ts","../src/auth.ts","../src/setup.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 * REPL Mode - Run commands one at a time\n *\n * Shell-like interface where each line is executed as a command.\n * Special commands prefixed with /.\n */\n\nimport * as readline from 'readline';\nimport * as path from 'path';\nimport * as os from 'os';\nimport * as fs from 'fs';\nimport pc from 'picocolors';\nimport { compute, type SandboxInterface } from 'computesdk';\n\ntype SessionResult = 'exit';\n\ninterface ReplContext {\n sandboxes: Map<string, SandboxInterface>;\n activeSandboxId: string;\n}\n\n/**\n * Start REPL mode.\n */\nexport async function startREPL(sandbox: SandboxInterface, provider: string): Promise<void> {\n // Mark provider as used - reserved for future provider-specific REPL behavior\n void provider;\n const ctx: ReplContext = {\n sandboxes: new Map([[sandbox.sandboxId, sandbox]]),\n activeSandboxId: sandbox.sandboxId,\n };\n\n await runSession(ctx);\n}\n\nfunction buildPrompt(sandboxId: string): string {\n if (!sandboxId) return pc.gray('[no sandbox] ') + pc.bold('$ ');\n return pc.cyan(`[${sandboxId}] `) + pc.bold('$ ');\n}\n\n/**\n * Run a single REPL session.\n *\n * Creates a readline interface, processes commands, and returns\n * 'exit' when the user wants to quit.\n */\nfunction runSession(ctx: ReplContext): Promise<SessionResult> {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n prompt: buildPrompt(ctx.activeSandboxId),\n terminal: true,\n historySize: 1000,\n });\n\n // Load history\n loadHistory(rl);\n\n return new Promise<SessionResult>((resolve) => {\n let resolved = false;\n const done = (result: SessionResult) => {\n if (resolved) return;\n resolved = true;\n rl.close();\n resolve(result);\n };\n\n rl.on('SIGINT', () => {\n console.log();\n rl.prompt();\n });\n\n rl.on('close', () => {\n done('exit');\n });\n\n rl.on('line', async (line: string) => {\n const trimmed = line.trim();\n\n if (!trimmed) {\n rl.prompt();\n return;\n }\n\n if (trimmed === '.exit') {\n done('exit');\n return;\n }\n\n // Save to history\n saveToHistory(trimmed);\n\n try {\n if (trimmed.startsWith('/')) {\n const result = await handleSpecialCommand(ctx, trimmed, rl);\n if (result === 'exit') {\n done(result);\n return;\n }\n } else if (ctx.sandboxes.size === 0) {\n console.log(pc.yellow('No active sandbox. Use /new to create one.'));\n } else {\n const sandbox = ctx.sandboxes.get(ctx.activeSandboxId)!;\n await executeCommand(sandbox, trimmed);\n }\n } catch (error) {\n console.log(pc.red(`✗ ${(error as Error).message}`));\n }\n\n if (!resolved) {\n rl.prompt();\n }\n });\n\n rl.prompt();\n });\n}\n\n/**\n * Execute a shell command in the sandbox\n */\nasync function executeCommand(sandbox: SandboxInterface, command: string): Promise<void> {\n const result = await sandbox.runCommand(command);\n\n // Print stdout\n if (result.stdout) {\n process.stdout.write(result.stdout);\n if (!result.stdout.endsWith('\\n')) {\n console.log();\n }\n }\n\n // Print stderr in red\n if (result.stderr) {\n process.stderr.write(pc.red(result.stderr));\n if (!result.stderr.endsWith('\\n')) {\n console.log();\n }\n }\n\n // Show exit code if non-zero\n if (result.exitCode !== 0) {\n console.log(pc.gray(`exit code: ${result.exitCode}`));\n }\n}\n\n/**\n * Handle special commands (prefixed with /)\n * Returns 'exit' to quit, or null to continue\n */\nasync function handleSpecialCommand(\n ctx: ReplContext,\n input: string,\n rl: readline.Interface,\n): Promise<SessionResult | null> {\n const [cmd, ...args] = input.slice(1).split(/\\s+/);\n\n switch (cmd.toLowerCase()) {\n case 'help':\n case 'h':\n case '?':\n showHelp();\n return null;\n\n case 'info':\n case 'i': {\n if (ctx.sandboxes.size === 0) {\n console.log(pc.yellow('No active sandbox. Use /new to create one.'));\n return null;\n }\n const activeSandbox = ctx.sandboxes.get(ctx.activeSandboxId)!;\n console.log();\n console.log(pc.bold(' Sandbox Info'));\n console.log(` ID: ${pc.cyan(activeSandbox.sandboxId)}`);\n console.log();\n return null;\n }\n\n case 'url':\n case 'u': {\n if (ctx.sandboxes.size === 0) {\n console.log(pc.yellow('No active sandbox. Use /new to create one.'));\n return null;\n }\n const activeSandbox = ctx.sandboxes.get(ctx.activeSandboxId)!;\n if (args.length === 0) {\n console.log(pc.gray('Usage: /url <port>'));\n } else {\n const port = parseInt(args[0], 10);\n if (isNaN(port)) {\n console.log(pc.red('Invalid port number'));\n } else {\n const url = await activeSandbox.getUrl({ port });\n console.log(pc.cyan(url));\n }\n }\n return null;\n }\n\n case 'new': {\n console.log(pc.gray(' Creating new sandbox...'));\n const newSandbox = await compute.sandbox.create();\n ctx.sandboxes.set(newSandbox.sandboxId, newSandbox);\n ctx.activeSandboxId = newSandbox.sandboxId;\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(` Sandbox ready: ${pc.cyan(newSandbox.sandboxId)}`);\n console.log(` ${pc.gray(`Active sandboxes: ${ctx.sandboxes.size}`)}`);\n return null;\n }\n\n case 'destroy': {\n if (args.length === 0) {\n console.log(pc.gray('Usage: /destroy <sandbox-id> or /destroy --all'));\n console.log(pc.gray('Use /list to see all sandboxes'));\n return null;\n }\n if (args[0] === '--all') {\n if (ctx.sandboxes.size === 0) {\n console.log(pc.yellow(' No sandboxes to destroy.'));\n return null;\n }\n const count = ctx.sandboxes.size;\n console.log(pc.gray(` Destroying ${count} sandbox${count > 1 ? 'es' : ''}...`));\n await Promise.all(\n Array.from(ctx.sandboxes.values()).map(s => s.destroy()),\n );\n ctx.sandboxes.clear();\n ctx.activeSandboxId = '';\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(` Destroyed ${pc.cyan(String(count))} sandbox${count > 1 ? 'es' : ''}`);\n console.log(pc.yellow(' No sandboxes remaining. Use /new to create one or /exit to quit.'));\n return null;\n }\n const targetId = args[0];\n const target = ctx.sandboxes.get(targetId);\n if (!target) {\n // Try partial match\n const matches = Array.from(ctx.sandboxes.keys()).filter(id => id.startsWith(targetId));\n if (matches.length === 1) {\n return destroySandbox(ctx, matches[0], rl);\n } else if (matches.length > 1) {\n console.log(pc.yellow(' Ambiguous ID. Matches:'));\n for (const id of matches) {\n console.log(` ${pc.cyan(id)}`);\n }\n } else {\n console.log(pc.red(` Sandbox not found: ${targetId}`));\n console.log(pc.gray(' Use /list to see all sandboxes'));\n }\n return null;\n }\n return destroySandbox(ctx, targetId, rl);\n }\n\n case 'list':\n case 'ls': {\n console.log();\n console.log(pc.bold(' Sandboxes'));\n for (const id of ctx.sandboxes.keys()) {\n const marker = id === ctx.activeSandboxId ? pc.green(' ●') : ' ';\n console.log(` ${marker} ${pc.cyan(id)}`);\n }\n console.log();\n return null;\n }\n\n case 'switch':\n case 'sw': {\n if (args.length === 0) {\n console.log(pc.gray('Usage: /switch <sandbox-id>'));\n console.log(pc.gray('Use /list to see all sandboxes'));\n return null;\n }\n const switchId = args[0];\n if (ctx.sandboxes.has(switchId)) {\n ctx.activeSandboxId = switchId;\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(` Switched to ${pc.cyan(switchId)}`);\n return null;\n }\n // Try partial match\n const matches = Array.from(ctx.sandboxes.keys()).filter(id => id.startsWith(switchId));\n if (matches.length === 1) {\n ctx.activeSandboxId = matches[0];\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(` Switched to ${pc.cyan(matches[0])}`);\n } else if (matches.length > 1) {\n console.log(pc.yellow(' Ambiguous ID. Matches:'));\n for (const id of matches) {\n console.log(` ${pc.cyan(id)}`);\n }\n } else {\n console.log(pc.red(` Sandbox not found: ${switchId}`));\n console.log(pc.gray(' Use /list to see all sandboxes'));\n }\n return null;\n }\n\n case 'exit':\n case 'quit':\n case 'q':\n return 'exit';\n\n default:\n console.log(pc.yellow(`Unknown command: /${cmd}`));\n console.log(pc.gray('Type /help for available commands'));\n return null;\n }\n}\n\n/**\n * Destroy a sandbox by ID and update context\n */\nasync function destroySandbox(\n ctx: ReplContext,\n sandboxId: string,\n rl: readline.Interface,\n): Promise<null> {\n const target = ctx.sandboxes.get(sandboxId)!;\n console.log(pc.gray(` Destroying ${sandboxId}...`));\n await target.destroy();\n ctx.sandboxes.delete(sandboxId);\n console.log(` Destroyed ${pc.cyan(sandboxId)}`);\n\n // If we destroyed the active sandbox, switch to another\n if (ctx.activeSandboxId === sandboxId && ctx.sandboxes.size > 0) {\n ctx.activeSandboxId = ctx.sandboxes.keys().next().value!;\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(` Switched to ${pc.cyan(ctx.activeSandboxId)}`);\n } else if (ctx.sandboxes.size === 0) {\n ctx.activeSandboxId = '';\n rl.setPrompt(buildPrompt(ctx.activeSandboxId));\n console.log(pc.yellow(' No sandboxes remaining. Use /new to create one or /exit to quit.'));\n }\n\n return null;\n}\n\n/**\n * Show help message\n */\nfunction showHelp(): void {\n console.log();\n console.log(pc.bold(' Shell Mode'));\n console.log(pc.gray(' Just type commands - they run in the active sandbox'));\n console.log();\n console.log(pc.white(' ls -la'));\n console.log(pc.white(' cat /etc/os-release'));\n console.log(pc.white(' npm install lodash'));\n console.log();\n console.log(pc.bold(' Sandbox Commands') + pc.gray(' (prefix with /)'));\n console.log();\n console.log(pc.cyan(' /new') + pc.gray(' Create a new sandbox and switch to it'));\n console.log(pc.cyan(' /list') + pc.gray(' List all sandboxes'));\n console.log(pc.cyan(' /switch <id>') + pc.gray(' Switch active sandbox'));\n console.log(pc.cyan(' /destroy <id>') + pc.gray(' Destroy a sandbox by ID'));\n console.log(pc.cyan(' /destroy --all') + pc.gray(' Destroy all sandboxes'));\n console.log();\n console.log(pc.bold(' Other Commands'));\n console.log();\n console.log(pc.cyan(' /info') + pc.gray(' Show active sandbox info'));\n console.log(pc.cyan(' /url <port>') + pc.gray(' Get public URL for port'));\n console.log(pc.cyan(' /help') + pc.gray(' Show this help'));\n console.log(pc.cyan(' /exit') + pc.gray(' Exit the REPL'));\n console.log();\n}\n\n// History file path\nconst HISTORY_FILE = path.join(os.homedir(), '.create_compute_history');\n\n/**\n * Load history from file\n */\nfunction loadHistory(rl: readline.Interface): void {\n try {\n if (fs.existsSync(HISTORY_FILE)) {\n const history = fs.readFileSync(HISTORY_FILE, 'utf-8')\n .split('\\n')\n .filter(line => line.trim())\n .reverse();\n\n for (const line of history.slice(0, 1000)) {\n (rl as unknown as { history: string[] }).history?.push(line);\n }\n }\n } catch {\n // Ignore\n }\n}\n\n/**\n * Save a line to history\n */\nfunction saveToHistory(line: string): void {\n try {\n fs.appendFileSync(HISTORY_FILE, line + '\\n');\n } catch {\n // Ignore\n }\n}\n","#!/usr/bin/env node\n/**\n * Minimal workspace CLI using existing PR #344 infrastructure\n * \n * This is a thin wrapper around sandbox.create() + bootstrap script\n * that adds the workspace concept without SDK changes.\n */\n\nimport { compute } from 'computesdk';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as os from 'node:os';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { startREPL } from './repl.js';\n\nconst WORKSPACE_STATE_FILE = path.join(os.homedir(), '.computesdk', 'workspaces.json');\n\ninterface Workspace {\n id: string; // repo:branch\n repo: string;\n branch: string;\n sandboxId: string;\n provider: string;\n worktreePath: string;\n createdAt: string;\n lastUsed: string;\n}\n\ninterface WorkspaceState {\n workspaces: Record<string, Workspace>;\n}\n\n// Export Workspace interface\nexport type { Workspace, WorkspaceState };\n\n// Shell escape helper to prevent command injection\nfunction shellEscape(arg: string): string {\n if (/^[a-zA-Z0-9._\\-/:=@]+$/.test(arg)) return arg;\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n\n// Load workspace state\nexport function loadState(): WorkspaceState {\n try {\n if (!fs.existsSync(WORKSPACE_STATE_FILE)) {\n return { workspaces: {} };\n }\n const raw = fs.readFileSync(WORKSPACE_STATE_FILE, 'utf-8');\n return JSON.parse(raw);\n } catch {\n return { workspaces: {} };\n }\n}\n\n// Export alias for index.ts\nexport const loadWorkspaceState = loadState;\n\n// Save workspace state\nexport function saveState(state: WorkspaceState): void {\n const dir = path.dirname(WORKSPACE_STATE_FILE);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n fs.writeFileSync(WORKSPACE_STATE_FILE, JSON.stringify(state, null, 2) + '\\n', { mode: 0o600 });\n}\n\n// Get workspace ID from repo and branch\nfunction getWorkspaceId(repo: string, branch: string): string {\n return `${repo}:${branch}`;\n}\n\n// Create or attach to workspace\nexport async function workspaceCreate(options: {\n repo: string;\n branch: string;\n provider?: string;\n}): Promise<Workspace> {\n const { repo, branch, provider } = options;\n const id = getWorkspaceId(repo, branch);\n const state = loadState();\n \n // Check if workspace already exists\n if (state.workspaces[id]) {\n const existing = state.workspaces[id];\n \n // Verify sandbox still exists\n try {\n const sandbox = await compute.sandbox.getById(existing.sandboxId);\n if (!sandbox) {\n throw new Error('Sandbox not found');\n }\n \n // Just update last used\n existing.lastUsed = new Date().toISOString();\n saveState(state);\n \n p.log.info(`Attaching to existing workspace: ${pc.cyan(id)}`);\n return existing;\n } catch {\n // Sandbox is gone, remove from state and recreate\n delete state.workspaces[id];\n }\n }\n \n // Create new sandbox\n p.log.info('Creating sandbox...');\n const spinner = p.spinner();\n spinner.start('Provisioning via ComputeSDK...');\n \n let sandbox;\n try {\n // TODO: Configure compute with provider\n sandbox = await compute.sandbox.create();\n spinner.stop(`Sandbox ready: ${pc.cyan(sandbox.sandboxId)}`);\n } catch (error) {\n spinner.stop(pc.red('Failed to create sandbox'));\n throw error;\n }\n \n // Run bootstrap script\n spinner.start('Bootstrapping workspace (installing gh CLI, cloning repo)...');\n \n // Read bootstrap script\n const bootstrapScript = fs.readFileSync(\n new URL('./bootstrap.sh', import.meta.url),\n 'utf-8'\n );\n \n // Write and execute bootstrap script in sandbox\n try {\n // Write script to sandbox\n await sandbox.filesystem.writeFile('/tmp/bootstrap.sh', bootstrapScript);\n \n // Make executable and run\n await sandbox.runCommand('chmod +x /tmp/bootstrap.sh');\n \n // Run bootstrap with repo and branch\n // Note: This is interactive for device flow auth\n spinner.stop('Running bootstrap (you may need to authenticate with GitHub)...');\n \n const result = await sandbox.runCommand(\n `/tmp/bootstrap.sh ${shellEscape(repo)} ${shellEscape(branch)}`,\n { timeout: 300000 } // 5 min timeout for auth\n );\n \n // Parse bootstrap output for paths\n const output = result.stdout || '';\n const jsonMatch = output.match(/\\{[\\s\\S]*\\}/);\n let worktreePath = `/workspaces/${path.basename(repo)}-${branch}`;\n \n if (jsonMatch) {\n try {\n const bootstrapInfo = JSON.parse(jsonMatch[0]);\n worktreePath = bootstrapInfo.worktree_path || worktreePath;\n } catch {\n // Use default path\n }\n }\n \n // Create workspace record\n const workspace: Workspace = {\n id,\n repo,\n branch,\n sandboxId: sandbox.sandboxId,\n provider: provider || 'e2b', // TODO: Get actual provider\n worktreePath,\n createdAt: new Date().toISOString(),\n lastUsed: new Date().toISOString(),\n };\n \n state.workspaces[id] = workspace;\n saveState(state);\n \n p.log.success(`Workspace ready: ${pc.cyan(id)}`);\n p.log.info(`Sandbox: ${pc.dim(sandbox.sandboxId)}`);\n p.log.info(`Worktree: ${pc.dim(worktreePath)}`);\n \n return workspace;\n \n } catch (error) {\n spinner.stop(pc.red('Bootstrap failed'));\n // Cleanup sandbox on failure\n try {\n await sandbox.destroy();\n } catch {\n // Ignore cleanup errors\n }\n throw error;\n }\n}\n\n// Attach to existing workspace\nexport async function workspaceAttach(id: string): Promise<void> {\n const state = loadState();\n const workspace = state.workspaces[id];\n \n if (!workspace) {\n p.log.error(`Workspace not found: ${id}`);\n p.log.info(`Run: compute workspace create --repo owner/repo --branch ${id.split(':')[1] || 'main'}`);\n process.exit(1);\n }\n \n // Get sandbox\n const sandbox = await compute.sandbox.getById(workspace.sandboxId);\n if (!sandbox) {\n p.log.error(`Sandbox no longer exists: ${workspace.sandboxId}`);\n delete state.workspaces[id];\n saveState(state);\n process.exit(1);\n }\n \n // Update last used\n workspace.lastUsed = new Date().toISOString();\n saveState(state);\n \n p.log.info(`Attaching to workspace: ${pc.cyan(id)}`);\n p.log.info(`Worktree: ${pc.dim(workspace.worktreePath)}`);\n console.log(pc.gray(`Tip: commands run at sandbox root; use { cwd: \"${workspace.worktreePath}\" } on runCommand to scope them.`));\n\n try {\n await startREPL(sandbox, workspace.provider);\n } catch (error) {\n p.log.error(`Failed to attach: ${(error as Error).message}`);\n process.exit(1);\n }\n}\n\n// List all sandboxes (via workspaces)\nexport async function sandboxList(): Promise<void> {\n const state = loadState();\n const workspaces = Object.values(state.workspaces);\n \n if (workspaces.length === 0) {\n p.log.info('No sandboxes found.');\n p.log.info('Create one with: compute owner/repo --branch main');\n return;\n }\n \n console.log();\n console.log(pc.bold('Sandboxes'));\n console.log();\n \n for (const ws of workspaces) {\n const age = Math.round((Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24));\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n const status = age > 7 ? pc.red('stale') : age > 1 ? pc.yellow('idle') : pc.green('active');\n \n console.log(` ${status} ${pc.cyan(ws.sandboxId)}`);\n console.log(` Workspace: ${pc.dim(ws.id)}`);\n console.log(` Provider: ${ws.provider}`);\n console.log(` Last active: ${pc.gray(ageStr)}`);\n console.log();\n }\n \n console.log(pc.gray('Tip: Use \"compute workspaces\" to see full workspace details'));\n}\n\n// List all workspaces\nexport async function workspaceList(): Promise<void> {\n const state = loadState();\n const workspaces = Object.values(state.workspaces);\n \n if (workspaces.length === 0) {\n p.log.info('No workspaces found.');\n p.log.info('Create one with: compute owner/repo --branch main');\n return;\n }\n \n console.log();\n console.log(pc.bold('Workspaces'));\n console.log();\n \n for (const ws of workspaces) {\n const age = Math.round((Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24));\n const ageStr = age === 0 ? 'today' : `${age}d ago`;\n \n console.log(` ${pc.cyan(ws.id)}`);\n console.log(` Sandbox: ${pc.dim(ws.sandboxId)} (${ws.provider})`);\n console.log(` Path: ${pc.dim(ws.worktreePath)}`);\n console.log(` Last used: ${pc.gray(ageStr)}`);\n console.log();\n }\n}\n\n// Save a simple sandbox (without workspace/repo info)\nexport async function saveSandbox(sandbox: {\n id: string;\n sandboxId: string;\n provider: string;\n createdAt: string;\n lastUsed: string;\n}): Promise<void> {\n const state = loadState();\n \n // Store as a minimal \"workspace\" with just sandbox info\n state.workspaces[sandbox.id] = {\n id: sandbox.id,\n repo: '(no repo)',\n branch: '(raw sandbox)',\n sandboxId: sandbox.sandboxId,\n provider: sandbox.provider,\n worktreePath: '/',\n createdAt: sandbox.createdAt,\n lastUsed: sandbox.lastUsed,\n };\n \n saveState(state);\n}\n\n// Destroy workspace\nexport async function workspaceDestroy(id?: string): Promise<void> {\n const state = loadState();\n \n if (id) {\n // Destroy specific workspace\n const workspace = state.workspaces[id];\n if (!workspace) {\n p.log.error(`Workspace not found: ${id}`);\n return;\n }\n \n p.log.info(`Destroying workspace: ${pc.cyan(id)}`);\n \n try {\n await compute.sandbox.destroy(workspace.sandboxId);\n delete state.workspaces[id];\n saveState(state);\n p.log.success('Workspace destroyed');\n } catch (error) {\n p.log.error(`Failed to destroy: ${(error as Error).message}`);\n }\n } else {\n // Interactive selection\n const choices = Object.values(state.workspaces).map(ws => ({\n value: ws.id,\n label: `${ws.id} (${ws.provider}, last used ${Math.round((Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24))}d ago)`\n }));\n \n if (choices.length === 0) {\n p.log.info('No workspaces to destroy');\n return;\n }\n \n const selected = await p.select({\n message: 'Select workspace to destroy',\n options: choices,\n });\n \n if (p.isCancel(selected)) {\n return;\n }\n \n await workspaceDestroy(selected as string);\n }\n}\n","/**\n * @computesdk/cli\n *\n * ComputeSDK CLI - Cloud-native workspace management.\n *\n * Usage:\n * compute # interactive workspace creation\n * compute owner/repo # create workspace for repo\n * compute --repo owner/repo --branch fix-auth\n * compute workspace # manage existing workspaces\n * compute exec <id> <cmd...> # run command in sandbox\n * compute connect <id> # open REPL against sandbox\n * compute destroy <id...> # destroy sandboxes\n * compute run -- <cmd...> # create + exec + optional destroy\n * compute providers # list configured providers\n */\n\nimport 'dotenv/config';\nimport { Command } from 'commander';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { dirname, join } from 'path';\nimport { compute, type SandboxInterface } from 'computesdk';\nimport { getProviderStatus } from './providers.js';\nimport { registerActionsCommands } from './actions.js';\nimport { registerMarketCommands } from './market.js';\nimport { registerSandboxesCommands } from './sandboxes.js';\nimport { startREPL } from './repl.js';\nimport { clearStoredCredentials } from './auth.js';\nimport { ensureAuth, resolveProvider, configureCompute } from './setup.js';\nimport {\n workspaceCreate,\n workspaceAttach,\n workspaceList,\n workspaceDestroy,\n sandboxList,\n loadWorkspaceState,\n type Workspace,\n} from './workspace-cli.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\nconst program = new Command();\n\nprogram\n .name('compute')\n .description('Cloud-native workspace management')\n .version(VERSION)\n .enablePositionalOptions()\n .passThroughOptions();\n\n// ─── Default action: Show help ─────────────────────────────────────────────\n\nprogram\n .option('--login', 'force re-authentication')\n .option('--logout', 'clear stored credentials')\n .action(async (opts) => {\n if (opts.logout) {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n clearStoredCredentials();\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 ensureAuth({ forceLogin: true });\n p.outro(pc.green('Authenticated!'));\n process.exit(0);\n }\n\n // Show help by default\n program.help();\n });\n\n// ─── Create Command (like create-compute) ─────────────────────────────────\n\nprogram\n .command('create')\n .description('Create a new workspace (same as create-compute)')\n .argument('[repo]', 'Repository in owner/repo format')\n .option('-b, --branch <branch>', 'Branch name', 'main')\n .option('-p, --provider <provider>', 'provider to use')\n .option('--no-attach', 'Create workspace but do not attach')\n .action(async (repo, options) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n await ensureAuth();\n\n if (!repo) {\n const state = loadWorkspaceState();\n const workspaceIds = Object.keys(state.workspaces);\n\n if (workspaceIds.length > 0) {\n // Show existing workspaces to attach to\n const choices = workspaceIds.map((id) => {\n const ws = state.workspaces[id];\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : `${age}d ago`;\n return {\n value: id,\n label: `${id} (${ws.provider}, ${ageStr})`,\n };\n });\n\n const selected = await p.select({\n message: 'Select workspace to attach (or create new)',\n options: [\n ...choices,\n { value: '__new__', label: pc.gray('+ Create new workspace') },\n ],\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n if (selected !== '__new__') {\n await workspaceAttach(selected as string);\n return;\n }\n\n // Fall through to create new\n }\n\n // Prompt for repo\n const repoInput = await p.text({\n message: 'Repository to work on?',\n placeholder: 'owner/repo',\n validate: (value) => {\n if (!value || !value.includes('/')) {\n return 'Please enter a repository in owner/repo format';\n }\n },\n });\n\n if (p.isCancel(repoInput)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n repo = repoInput as string;\n }\n\n // Validate repo format\n if (!repo.includes('/')) {\n p.log.error('Invalid repository format. Use: owner/repo');\n process.exit(1);\n }\n\n const provider = await resolveProvider(options.provider, { interactive: true });\n configureCompute(provider);\n\n const spinner = p.spinner();\n spinner.start('Creating workspace...');\n\n try {\n const workspace = await workspaceCreate({\n repo,\n branch: options.branch,\n provider,\n });\n\n spinner.stop(`Workspace ready: ${pc.cyan(workspace.id)}`);\n\n if (options.attach !== false) {\n console.log();\n await workspaceAttach(workspace.id);\n } else {\n p.outro(pc.green('Workspace created!'));\n }\n } catch (error) {\n spinner.stop(pc.red('Failed to create workspace'));\n p.log.error((error as Error).message);\n process.exit(1);\n }\n });\n\n// ─── Sandbox Commands ───────────────────────────────────────────────────────\n\nconst sandboxCmd = program\n .command('sandbox')\n .alias('sb')\n .description('Manage raw sandboxes (VMs without git/worktree)');\n\nsandboxCmd\n .command('create')\n .description('Create a new sandbox')\n .option('-p, --provider <provider>', 'provider to use')\n .option('--timeout <duration>', 'sandbox timeout (e.g. 5m, 1h)')\n .option('--name <name>', 'sandbox name')\n .option('--connect', 'drop into the REPL after creation')\n .option('--silent', 'only output the sandbox ID')\n .action(async (opts) => {\n if (!opts.silent) {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n }\n\n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n if (!opts.silent) {\n const spinner = p.spinner();\n spinner.start('Creating sandbox...');\n try {\n const sandbox = await compute.sandbox.create(\n buildCreateOptions(opts),\n );\n spinner.stop(`Sandbox ready: ${pc.cyan(sandbox.sandboxId)}`);\n\n // Track the sandbox in local state\n const { saveSandbox } = await import('./workspace-cli.js');\n await saveSandbox({\n id: sandbox.sandboxId,\n sandboxId: sandbox.sandboxId,\n provider: provider,\n createdAt: new Date().toISOString(),\n lastUsed: new Date().toISOString(),\n });\n\n if (opts.connect) {\n await startREPL(sandbox, provider);\n }\n } catch (error) {\n spinner.stop(pc.red('Failed to create sandbox'));\n p.log.error((error as Error).message);\n process.exit(1);\n }\n } else {\n try {\n const sandbox = await compute.sandbox.create(\n buildCreateOptions(opts),\n );\n // Silent mode: only print sandbox ID for scripting\n process.stdout.write(sandbox.sandboxId);\n\n // Track the sandbox in local state (even in silent mode)\n const { saveSandbox } = await import('./workspace-cli.js');\n await saveSandbox({\n id: sandbox.sandboxId,\n sandboxId: sandbox.sandboxId,\n provider: provider,\n createdAt: new Date().toISOString(),\n lastUsed: new Date().toISOString(),\n });\n\n if (opts.connect) {\n await startREPL(sandbox, provider);\n }\n } catch (error) {\n process.stderr.write((error as Error).message + '\\n');\n process.exit(1);\n }\n }\n });\n\nsandboxCmd\n .command('destroy')\n .description('Destroy one or more sandboxes')\n .aliases(['rm', 'stop'])\n .argument('[sandbox_id...]', 'sandbox IDs to destroy (optional - will show picker if not provided)')\n .option('-p, --provider <provider>', 'provider to use')\n .action(async (sandboxIds: string[] | undefined, opts) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n \n // Load state\n const { loadState, saveState } = await import('./workspace-cli.js');\n const state = loadState();\n \n // If no IDs provided, show interactive picker\n if (!sandboxIds || sandboxIds.length === 0) {\n const workspaces = Object.values(state.workspaces);\n\n if (workspaces.length === 0) {\n p.log.info('No sandboxes to destroy.');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const choices = workspaces.map((ws) => {\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n const status = age > 7 ? pc.red('stale') : age > 1 ? pc.yellow('idle') : pc.green('active');\n return {\n value: ws.sandboxId,\n label: `${status} ${ws.sandboxId} (${ws.provider}, last active ${ageStr})`,\n };\n });\n\n // Allow multi-select with space, or single select with enter\n const selected = await p.multiselect({\n message: 'Select sandboxes to destroy (space to select, enter to confirm)',\n options: choices,\n });\n\n if (p.isCancel(selected) || (selected as string[]).length === 0) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n sandboxIds = selected as string[];\n }\n \n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n const results = await Promise.allSettled(\n sandboxIds.map(async (id) => {\n await compute.sandbox.destroy(id);\n return id;\n }),\n );\n\n for (const result of results) {\n if (result.status === 'fulfilled') {\n const sandboxId = result.value;\n console.log(pc.green(`Destroyed ${sandboxId}`));\n \n // Remove from state if tracked\n const workspaceId = Object.keys(state.workspaces).find(\n key => state.workspaces[key].sandboxId === sandboxId\n );\n if (workspaceId) {\n delete state.workspaces[workspaceId];\n }\n } else {\n console.error(pc.red(`Failed to destroy: ${result.reason?.message || result.reason}`));\n }\n }\n \n // Save updated state\n saveState(state);\n });\n\nsandboxCmd\n .command('list')\n .alias('ls')\n .description('List all sandboxes')\n .action(async () => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await sandboxList();\n });\n\nsandboxCmd\n .command('connect')\n .description('Connect to a sandbox (opens REPL; same as compute connect)')\n .aliases(['ssh', 'shell'])\n .argument('[sandbox_id]', 'sandbox ID (optional - will show picker if not provided)')\n .option('-p, --provider <provider>', 'provider to use')\n .action(async (sandboxId: string | undefined, opts) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n // If no sandbox_id provided, show interactive picker\n if (!sandboxId) {\n const { loadState } = await import('./workspace-cli.js');\n const state = loadState();\n const workspaces = Object.values(state.workspaces);\n\n if (workspaces.length === 0) {\n p.log.info('No sandboxes found.');\n p.log.info('Create one with: compute sandbox create');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const choices = workspaces.map((ws) => {\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n const status = age > 7 ? pc.red('stale') : age > 1 ? pc.yellow('idle') : pc.green('active');\n return {\n value: ws.sandboxId,\n label: `${status} ${ws.sandboxId} (${ws.provider}, last active ${ageStr})`,\n };\n });\n\n const selected = await p.select({\n message: 'Select sandbox to connect',\n options: choices,\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n sandboxId = selected as string;\n }\n\n const spinner = p.spinner();\n spinner.start('Connecting...');\n const sandbox = await compute.sandbox.getById(sandboxId);\n if (!sandbox) {\n spinner.stop(pc.red(`Sandbox not found: ${sandboxId}`));\n process.exit(1);\n }\n\n spinner.stop('');\n\n await startREPL(sandbox, provider);\n });\n\nsandboxCmd\n .command('exec')\n .description('Execute a command in a sandbox')\n .argument('<sandbox_id>', 'sandbox ID')\n .argument('<command...>', 'command to run')\n .option('-p, --provider <provider>', 'provider to use')\n .option('-e, --env <key=value...>', 'environment variables')\n .option('-w, --workdir <directory>', 'working directory')\n .passThroughOptions()\n .action(async (sandboxId: string, command: string[], opts) => {\n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n const sandbox = await compute.sandbox.getById(sandboxId);\n if (!sandbox) {\n console.error(pc.red(`Sandbox not found: ${sandboxId}`));\n process.exit(1);\n }\n\n const cmd = buildExecCommand(command, opts);\n const result = await sandbox.runCommand(cmd);\n\n if (result.stdout) {\n process.stdout.write(result.stdout);\n }\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n process.exit(result.exitCode);\n });\n\n// ─── Connect Command (top-level alias) ───────────────────────────────────────\n\nprogram\n .command('connect')\n .description('Connect to a sandbox (opens REPL)')\n .aliases(['ssh', 'shell']) // Keep aliases but document connect as primary\n .argument('[sandbox_id]', 'sandbox ID (optional - will show picker if not provided)')\n .option('-p, --provider <provider>', 'provider to use')\n .action(async (sandboxId: string | undefined, opts) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n // If no sandbox_id provided, show interactive picker\n if (!sandboxId) {\n const { loadState } = await import('./workspace-cli.js');\n const state = loadState();\n const workspaces = Object.values(state.workspaces);\n\n if (workspaces.length === 0) {\n p.log.info('No sandboxes found.');\n p.log.info('Create one with: compute sandbox create');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const choices = workspaces.map((ws) => {\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n const status = age > 7 ? pc.red('stale') : age > 1 ? pc.yellow('idle') : pc.green('active');\n return {\n value: ws.sandboxId,\n label: `${status} ${ws.sandboxId} (${ws.provider}, last active ${ageStr})`,\n };\n });\n\n const selected = await p.select({\n message: 'Select sandbox to connect',\n options: choices,\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n sandboxId = selected as string;\n }\n\n const spinner = p.spinner();\n spinner.start('Connecting...');\n const sandbox = await compute.sandbox.getById(sandboxId);\n if (!sandbox) {\n spinner.stop(pc.red(`Sandbox not found: ${sandboxId}`));\n process.exit(1);\n }\n\n spinner.stop('');\n\n await startREPL(sandbox, provider);\n });\n\n// ─── Workspace Commands ─────────────────────────────────────────────────────\n\nconst workspaceCmd = program\n .command('workspace')\n .alias('ws')\n .description('Manage workspaces (sandbox + git + worktree)');\n\nworkspaceCmd\n .command('create')\n .description('Create a new workspace')\n .argument('[repo]', 'Repository in owner/repo format')\n .option('-b, --branch <branch>', 'Branch name', 'main')\n .option('-p, --provider <provider>', 'provider to use')\n .option('--no-attach', 'Create workspace but do not attach')\n .action(async (repo, options) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n await ensureAuth();\n\n if (!repo) {\n p.log.info('Usage: compute workspace create owner/repo --branch main');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const provider = await resolveProvider(options.provider, { interactive: true });\n configureCompute(provider);\n\n const spinner = p.spinner();\n spinner.start('Creating workspace...');\n\n try {\n const workspace = await workspaceCreate({\n repo,\n branch: options.branch,\n provider,\n });\n\n spinner.stop(`Workspace ready: ${pc.cyan(workspace.id)}`);\n\n if (options.attach !== false) {\n console.log();\n await workspaceAttach(workspace.id);\n } else {\n p.outro(pc.green('Workspace created!'));\n }\n } catch (error) {\n spinner.stop(pc.red('Failed to create workspace'));\n p.log.error((error as Error).message);\n process.exit(1);\n }\n });\n\nworkspaceCmd\n .command('list')\n .alias('ls')\n .description('List all workspaces')\n .action(async () => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await workspaceList();\n });\n\nworkspaceCmd\n .command('destroy')\n .alias('rm')\n .description('Destroy a workspace')\n .argument('[id]', 'Workspace ID (repo:branch format, optional - will show picker if not provided)')\n .action(async (id: string | undefined) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n // If no ID provided, show interactive picker\n if (!id) {\n const state = loadWorkspaceState();\n const workspaceIds = Object.keys(state.workspaces);\n\n if (workspaceIds.length === 0) {\n p.log.info('No workspaces to destroy.');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const choices = workspaceIds.map((key) => {\n const ws = state.workspaces[key];\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n return {\n value: key,\n label: `${pc.cyan(key)} (${ws.provider}, last used ${ageStr})`,\n };\n });\n\n // Allow multi-select\n const selected = await p.multiselect({\n message: 'Select workspaces to destroy (space to select, enter to confirm)',\n options: choices,\n });\n\n if (p.isCancel(selected) || (selected as string[]).length === 0) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n // Destroy each selected workspace\n for (const workspaceId of selected as string[]) {\n await workspaceDestroy(workspaceId);\n }\n } else {\n // Direct destroy with provided ID\n await workspaceDestroy(id);\n }\n });\n\nworkspaceCmd\n .command('connect')\n .alias('attach') // Keep attach as alias\n .description('Connect to an existing workspace (with git context)')\n .argument('[id]', 'Workspace ID (optional - will show picker if not provided)')\n .action(async (id: string | undefined) => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n\n // If no ID provided, show interactive picker\n if (!id) {\n const state = loadWorkspaceState();\n const workspaceIds = Object.keys(state.workspaces);\n\n if (workspaceIds.length === 0) {\n p.log.info('No workspaces found.');\n p.log.info('Create one with: compute create owner/repo');\n p.outro(pc.green('Done!'));\n return;\n }\n\n const choices = workspaceIds.map((key) => {\n const ws = state.workspaces[key];\n const age = Math.round(\n (Date.now() - new Date(ws.lastUsed).getTime()) / (1000 * 60 * 60 * 24),\n );\n const ageStr = age === 0 ? 'today' : age === 1 ? '1 day ago' : `${age} days ago`;\n return {\n value: key,\n label: `${pc.cyan(key)} (${ws.provider}, last used ${ageStr})`,\n };\n });\n\n const selected = await p.select({\n message: 'Select workspace to connect',\n options: choices,\n });\n\n if (p.isCancel(selected)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n id = selected as string;\n }\n\n await workspaceAttach(id);\n });\n\n// ─── run ─────────────────────────────────────────────────────────────────────\n\nprogram\n .command('run')\n .description('Create a sandbox, run a command, then optionally destroy it')\n .argument('<command...>', 'command to run')\n .option('-p, --provider <provider>', 'provider to use')\n .option('-e, --env <key=value...>', 'environment variables')\n .option('-w, --workdir <directory>', 'working directory')\n .passThroughOptions()\n .option('--rm', 'destroy sandbox after command finishes')\n .option('--timeout <duration>', 'sandbox timeout (e.g. 5m, 1h)')\n .option('--name <name>', 'sandbox name')\n .action(async (command: string[], opts) => {\n await ensureAuth();\n const provider = await resolveProvider(opts.provider);\n configureCompute(provider);\n\n let sandbox: SandboxInterface;\n try {\n sandbox = await compute.sandbox.create(\n buildCreateOptions(opts),\n );\n } catch (error) {\n console.error(pc.red(`Failed to create sandbox: ${(error as Error).message}`));\n process.exit(1);\n }\n\n try {\n const cmd = buildExecCommand(command, opts);\n const result = await sandbox.runCommand(cmd);\n\n if (result.stdout) {\n process.stdout.write(result.stdout);\n }\n if (result.stderr) {\n process.stderr.write(result.stderr);\n }\n\n if (opts.rm) {\n await sandbox.destroy();\n }\n\n process.exit(result.exitCode);\n } catch (error) {\n if (opts.rm) {\n try { await sandbox.destroy(); } catch { /* ignore cleanup errors */ }\n }\n console.error(pc.red((error as Error).message));\n process.exit(1);\n }\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')\n .action(async () => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n await ensureAuth({ forceLogin: true });\n p.outro(pc.green('Authenticated!'));\n });\n\nprogram\n .command('logout')\n .description('Clear stored credentials')\n .action(() => {\n console.log();\n p.intro(pc.cyan(`@computesdk/cli v${VERSION}`));\n clearStoredCredentials();\n p.log.success('Logged out. Stored credentials removed.');\n p.outro(pc.green('Done!'));\n });\n\n// ─── actions ─────────────────────────────────────────────────────────────────\n\nregisterActionsCommands(program);\n\n// ─── market ──────────────────────────────────────────────────────────────────\n// `compute market` is the sell side of the compute market — same platform\n// API and auth as `compute actions`, for orgs flagged `market_provider`.\n\nregisterMarketCommands(program);\n\n// ─── sandboxes ───────────────────────────────────────────────────────────────\n// `compute sandboxes` drives /api/v1/sandboxes — the customer-facing sandbox\n// control plane (create/exec/processes/files/urls). Same auth as actions.\n\nregisterSandboxesCommands(program);\n\n// ─── bench ───────────────────────────────────────────────────────────────────\n// `compute bench` is the benchmarks-platform CLI (@benchsdk/runner's `bench`\n// binary) folded under compute: run/check/auth/org/benchmarks/runs/results/\n// iterations/artifacts/logs/export all dispatch through it.\n\nprogram\n .command('bench')\n .description('Benchmarks platform CLI (run, auth, org, benchmarks, runs, results, artifacts, export, ...)')\n .allowUnknownOption()\n .helpOption(false)\n .action(() => {\n // Never reached: bench args are dispatched pre-parse below.\n });\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction buildCreateOptions(opts: { timeout?: string; name?: string }) {\n const options: Record<string, unknown> = {};\n if (opts.timeout) {\n options.timeout = parseDuration(opts.timeout);\n }\n if (opts.name) {\n options.name = opts.name;\n }\n return options;\n}\n\nexport function shellEscape(arg: string): string {\n if (/^[a-zA-Z0-9._\\-/:=@]+$/.test(arg)) return arg;\n return `'${arg.replace(/'/g, \"'\\\\''\")}'`;\n}\n\nfunction buildExecCommand(\n command: string[],\n opts: { env?: string[]; workdir?: string },\n): string {\n let cmd = command.map(shellEscape).join(' ');\n\n // Prepend cd if workdir is specified\n if (opts.workdir) {\n cmd = `cd ${shellEscape(opts.workdir)} && ${cmd}`;\n }\n\n // Prepend env vars if specified\n if (opts.env && opts.env.length > 0) {\n const envPrefix = opts.env\n .map((entry) => {\n const eqIndex = entry.indexOf('=');\n if (eqIndex === -1) {\n throw new Error(\n `Invalid environment entry \"${entry}\". Expected format KEY=VALUE.`,\n );\n }\n const key = entry.slice(0, eqIndex);\n const val = entry.slice(eqIndex + 1);\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {\n throw new Error(\n `Invalid environment variable name \"${key}\" in entry \"${entry}\".`,\n );\n }\n return `${key}=${shellEscape(val)}`;\n })\n .join(' ');\n cmd = `${envPrefix} ${cmd}`;\n }\n\n return cmd;\n}\n\n/**\n * Parse a human-friendly duration string to milliseconds.\n * Supports: 30s, 5m, 1h, 2h30m\n */\nfunction parseDuration(input: string): number {\n let total = 0;\n const pattern = /(\\d+)\\s*(s|m|h)/gi;\n let match;\n\n while ((match = pattern.exec(input)) !== null) {\n const value = parseInt(match[1], 10);\n const unit = match[2].toLowerCase();\n switch (unit) {\n case 's': total += value * 1000; break;\n case 'm': total += value * 60 * 1000; break;\n case 'h': total += value * 60 * 60 * 1000; break;\n }\n }\n\n if (total === 0) {\n // Try as plain number (seconds)\n const num = parseInt(input, 10);\n if (!isNaN(num)) return num * 1000;\n throw new Error(`Invalid duration: ${input}. Use formats like 30s, 5m, 1h`);\n }\n\n return total;\n}\n\n// ─── Run ─────────────────────────────────────────────────────────────────────\n\n// Bench args are opaque to commander (its own --flags, `--` separators, file\n// paths), so they dispatch before parsing. `@benchsdk/runner`'s run() owns the\n// process — it exits itself after dispatch.\nasync function main() {\n if (process.argv[2] === 'bench' || process.argv[2] === 'benchmark') {\n const { run: benchRun } = await import('@benchsdk/runner');\n await benchRun(process.argv.slice(3));\n return;\n }\n await program.parseAsync(process.argv);\n}\n\nmain().catch((error) => {\n console.error(pc.red(`\\nError: ${error.message}`));\n process.exit(1);\n});\n","/**\n * Provider detection and validation\n *\n * Detection is local: each provider declares the env vars its credentials come\n * from, and \"ready\" means all of them are set. This used to import helpers from\n * `computesdk` that the package no longer exports, which made every `compute`\n * invocation fail at module load.\n */\n\ninterface ProviderEnvSpec {\n /**\n * Alternative complete credential sets — the provider is usable when every\n * var in any one set is present (e.g. Vercel: the traditional tuple OR\n * VERCEL_OIDC_TOKEN; Namespace: NSC_TOKEN or NSC_TOKEN_FILE).\n */\n authOptions: string[][];\n /**\n * Maps each env var to the provider's nested config key (the field names in\n * the provider package's config interface, e.g. `apiKey`, `tokenId`).\n */\n configKeys: Record<string, string>;\n}\n\nconst PROVIDER_ENV: Record<string, ProviderEnvSpec> = {\n e2b: { authOptions: [['E2B_API_KEY']], configKeys: { E2B_API_KEY: 'apiKey' } },\n railway: { authOptions: [['RAILWAY_API_TOKEN']], configKeys: { RAILWAY_API_TOKEN: 'token' } },\n modal: {\n authOptions: [['MODAL_TOKEN_ID', 'MODAL_TOKEN_SECRET']],\n configKeys: { MODAL_TOKEN_ID: 'tokenId', MODAL_TOKEN_SECRET: 'tokenSecret' },\n },\n vercel: {\n authOptions: [['VERCEL_TOKEN', 'VERCEL_TEAM_ID', 'VERCEL_PROJECT_ID'], ['VERCEL_OIDC_TOKEN']],\n configKeys: {\n VERCEL_TOKEN: 'token',\n VERCEL_TEAM_ID: 'teamId',\n VERCEL_PROJECT_ID: 'projectId',\n },\n },\n daytona: { authOptions: [['DAYTONA_API_KEY']], configKeys: { DAYTONA_API_KEY: 'apiKey' } },\n namespace: {\n authOptions: [['NSC_TOKEN'], ['NSC_TOKEN_FILE']],\n configKeys: { NSC_TOKEN: 'token', NSC_TOKEN_FILE: 'tokenFile' },\n },\n blaxel: {\n authOptions: [['BL_API_KEY', 'BL_WORKSPACE']],\n configKeys: { BL_API_KEY: 'apiKey', BL_WORKSPACE: 'workspace' },\n },\n codesandbox: { authOptions: [['CSB_API_KEY']], configKeys: { CSB_API_KEY: 'apiKey' } },\n render: { authOptions: [['RENDER_API_KEY']], configKeys: { RENDER_API_KEY: 'apiKey' } },\n};\n\nconst PROVIDER_NAMES = Object.keys(PROVIDER_ENV);\n\n/** Missing vars from whichever auth option is closest to complete. */\nfunction missingEnvVars(provider: string): string[] {\n const spec = PROVIDER_ENV[provider];\n if (!spec) return [];\n let best: string[] | null = null;\n for (const option of spec.authOptions) {\n const missing = option.filter((name) => !process.env[name]);\n if (missing.length === 0) return [];\n if (!best || missing.length < best.length) best = missing;\n }\n return best ?? [];\n}\n\nfunction isProviderAuthComplete(provider: string): boolean {\n return missingEnvVars(provider).length === 0;\n}\n\n/**\n * Provider status info\n */\nexport interface ProviderStatus {\n name: string;\n ready: boolean;\n missing: string[];\n}\n\n/**\n * Detect all available providers from environment variables\n * Only includes providers supported by the ComputeSDK gateway\n */\nexport function detectAvailableProviders(): string[] {\n const available: string[] = [];\n\n // Check for computesdk first (ComputeSDK native - just needs gateway key)\n if (process.env.COMPUTESDK_API_KEY) {\n available.push('computesdk');\n }\n\n // Then check for individual cloud providers (need their own creds)\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 * Only includes providers supported by the ComputeSDK gateway\n */\nexport function getProviderStatus(): ProviderStatus[] {\n const statuses: ProviderStatus[] = [];\n\n // Add computesdk status (ComputeSDK native)\n const hasGatewayKey = !!process.env.COMPUTESDK_API_KEY;\n statuses.push({\n name: 'computesdk',\n ready: hasGatewayKey,\n missing: hasGatewayKey ? [] : ['COMPUTESDK_API_KEY'],\n });\n\n // Add individual cloud providers (need their own creds)\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/**\n * Check if gateway mode is available\n */\nexport function isGatewayAvailable(): boolean {\n return !!process.env.COMPUTESDK_API_KEY;\n}\n\n/**\n * Build the full compute config for a provider from env vars\n */\nexport function buildProviderConfig(provider: string): Record<string, unknown> {\n const config: Record<string, unknown> = {\n provider,\n apiKey: process.env.COMPUTESDK_API_KEY, // Gateway API key (top-level)\n };\n\n // For 'computesdk' provider, nest the API key under the provider config too\n if (provider === 'computesdk') {\n config.computesdk = {\n computesdk_api_key: process.env.COMPUTESDK_API_KEY,\n };\n return config;\n }\n\n // Add provider-specific config from env vars\n const spec = PROVIDER_ENV[provider];\n if (spec) {\n const providerConfig: Record<string, string> = {};\n for (const [envVar, key] of Object.entries(spec.configKeys)) {\n const value = process.env[envVar];\n if (value) providerConfig[key] = value;\n }\n if (Object.keys(providerConfig).length > 0) {\n config[provider] = providerConfig;\n }\n }\n\n return config;\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 bench auth login` stored (refreshed silently, never prompts). The\n * gateway key from `compute login` is not used. --base-url overrides the\n * https://platform.computesdk.com default; a non-computesdk host needs\n * --allow-untrusted-host and an explicit key — stored OAuth is never sent there.\n * Every subcommand takes --json for machine-readable output — on success the\n * data, on failure the `{ ok: false, error: {...} }` envelope on stderr.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { basename, join } from 'path';\nimport {\n ActionsApiError,\n ActionsCliError,\n ActionsClient,\n encodeWatchCursor,\n isTrustedActionsHost,\n resolveActionsAuth,\n toErrorEnvelope,\n type ActionsAuth,\n type CiArtifactListItem,\n type CiJob,\n type CiLogSlice,\n type CiProviderInfo,\n type CiProviderKeyResponse,\n type CiProvidersResponse,\n type CiRepo,\n type CiRepoConnectResponse,\n type CiRepoPatchResponse,\n type CiReposResponse,\n type CiRun,\n type CiRunHistory,\n type CiRunInspection,\n type CiRunSummary,\n type CiVaultDeleteResponse,\n type CiVaultItem,\n type CiVaultKind,\n type CiVaultListResponse,\n type CiVaultRevealResponse,\n type CiVaultSaveResponse,\n type CiWorkflow,\n} from './actions-client.js';\n\n/** The jobs inside a `/state` response — a subset of CiJob, no name/steps. */\ninterface CiLiveStateJob {\n id: string;\n state: CiJob['state'];\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n placementAttempts: CiJob['placementAttempts'];\n}\n\nexport type JsonOpts = { json?: boolean };\n\nexport interface CommonOpts extends JsonOpts {\n apiKey?: string;\n baseUrl?: string;\n allowUntrustedHost?: boolean;\n}\n\n/** The platform API client behind both `compute actions` and `compute market`. */\nexport async function client(opts: CommonOpts): Promise<ActionsClient> {\n return new ActionsClient(await resolveActionsAuth(opts));\n}\n\n/**\n * Commands that send or read a local secret value (vault set/get, market\n * credential connect) only ever talk to a trusted host: --allow-untrusted-host\n * opts an explicit API key into a host, not the secrets themselves.\n */\nexport function assertSecretValueHost(auth: ActionsAuth, what: string): void {\n if (!isTrustedActionsHost(auth.baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host',\n `Refusing to send or read ${what} at ${auth.baseUrl} — only computesdk.com and localhost hosts are allowed, even with --allow-untrusted-host.`,\n );\n }\n}\n\nexport function assertVaultValueHost(auth: ActionsAuth): void {\n assertSecretValueHost(auth, 'vault values');\n}\n\n/** A client for commands carrying a local secret value — trusted hosts only. */\nexport async function secretValueClient(opts: CommonOpts, what: string): Promise<ActionsClient> {\n const auth = await resolveActionsAuth(opts);\n assertSecretValueHost(auth, what);\n return new ActionsClient(auth);\n}\n\nasync function vaultValueClient(opts: CommonOpts): Promise<ActionsClient> {\n return secretValueClient(opts, 'vault values');\n}\n\n/** Print `data` as JSON when --json was passed; otherwise call `render`. */\nexport function output<T>(opts: JsonOpts, data: T, render: (data: T) => void): void {\n if (opts.json) {\n process.stdout.write(JSON.stringify(data, null, 2) + '\\n');\n } else {\n render(data);\n }\n}\n\n/** The run's job list: full detail when the runs detail route exists, else the\n * live-state route (which predates it and lists jobs without names). */\nasync function listRunJobs(c: ActionsClient, runId: string): Promise<CiJob[]> {\n try {\n const run = await c.get<CiRun>(`/api/v1/actions/runs/${runId}`);\n return run.jobs;\n } catch (e) {\n if (!(e instanceof ActionsApiError) || e.status !== 404) throw e;\n }\n const state = await c.get<{ jobs: CiLiveStateJob[] }>(`/api/v1/actions/runs/${runId}/state`);\n return state.jobs.map((j) => ({\n id: j.id,\n name: j.id.slice(0, 8), // the live-state route does not carry job names\n needs: [],\n workflowJobId: null,\n matrix: null,\n state: j.state,\n provider: j.provider,\n region: j.region,\n sandboxId: j.sandboxId,\n placementAttempts: j.placementAttempts,\n durationMs: null,\n steps: [],\n }));\n}\n\n/** The run's failure digest; null when the summary cannot be fetched. */\nasync function fetchRunSummary(c: ActionsClient, runId: string): Promise<CiRunSummary | null> {\n try {\n return await c.get<CiRunSummary>(`/api/v1/actions/runs/${runId}/summary`);\n } catch (e) {\n // The digest rides along with `actions run`; a deployment without the\n // route or a summary error must not hide the run detail itself. The\n // `summary` command fetches directly so its own errors still surface.\n if (!(e instanceof ActionsApiError && e.status === 404)) {\n console.error(\n pc.dim(`summary unavailable: ${e instanceof Error ? e.message : String(e)}`),\n );\n }\n return null;\n }\n}\n\n/**\n * Report an error and exit 1. With --json the stderr line is the stable\n * envelope from `toErrorEnvelope` (stdout stays empty, so a consumer can parse\n * either stream without guessing); otherwise a one-line human message.\n */\nexport function fail(error: unknown, opts: JsonOpts = {}): never {\n if (opts.json) {\n process.stderr.write(JSON.stringify(toErrorEnvelope(error)) + '\\n');\n } else if (error instanceof ActionsApiError) {\n console.error(pc.red(`Error (${error.status}): ${error.message}`));\n } else {\n console.error(pc.red(`Error: ${error instanceof Error ? error.message : String(error)}`));\n }\n process.exit(1);\n}\n\n/**\n * Commander's own usage errors (unknown option, missing required option or\n * argument) are raised before any action runs, so `fail` never sees them.\n * Route them through the same envelope when --json is among the raw args.\n */\nexport function usageErrorOutput(str: string, write: (str: string) => void, argv: string[] = process.argv): void {\n if (argv.includes('--json')) {\n const message = str.replace(/^error:\\s*/i, '').trim();\n write(JSON.stringify(toErrorEnvelope(new ActionsCliError('invalid_argument', message))) + '\\n');\n } else {\n write(str);\n }\n}\n\n// ─── Formatting (pure, exported for tests) ──────────────────────────────────\n\nexport function formatDuration(ms: number | null | undefined): string {\n if (ms === null || ms === undefined) return '-';\n if (ms < 1000) return `${ms}ms`;\n const s = Math.round(ms / 1000);\n if (s < 60) return `${s}s`;\n const m = Math.floor(s / 60);\n if (m < 60) return `${m}m${s % 60}s`;\n const h = Math.floor(m / 60);\n return `${h}h${m % 60}m`;\n}\n\nexport function shortSha(sha: string): string {\n return sha.slice(0, 8);\n}\n\nexport function conclusionLabel(conclusion: string): string {\n switch (conclusion) {\n case 'passed': return pc.green('passed');\n case 'failed': return pc.red('failed');\n case 'running': return pc.yellow('running');\n case 'cancelled': return pc.gray('cancelled');\n case 'none': return pc.yellow('queued');\n default: return conclusion;\n }\n}\n\nexport function formatRunRow(run: CiRun): string {\n const num = run.runNumber === null ? '-' : `#${run.runNumber}`;\n return [\n run.id,\n pc.dim(num),\n run.workflowName || run.workflowPath,\n conclusionLabel(run.conclusion),\n pc.dim(`${run.repoFullName}@${run.ref}`),\n shortSha(run.headSha),\n formatDuration(run.durationMs),\n run.startedAt,\n ].join(' ');\n}\n\nexport function formatRunDetail(run: CiRun, runUrl?: string): string {\n const lines: string[] = [];\n lines.push(`${pc.bold(run.workflowName || run.workflowPath)} ${conclusionLabel(run.conclusion)}`);\n lines.push(pc.dim(`run ${run.id}${run.runNumber === null ? '' : ` #${run.runNumber}`}`));\n lines.push(`${run.repoFullName} @ ${run.ref} ${shortSha(run.headSha)} ${run.event}${run.prNumber ? ` PR #${run.prNumber}` : ''}`);\n lines.push(`title: ${run.title}`);\n lines.push(`started: ${run.startedAt} duration: ${formatDuration(run.durationMs)}`);\n if (run.cancellationReason) lines.push(`cancelled: ${run.cancellationReason}`);\n if (run.providerOverride) lines.push(`dispatched to: ${run.providerOverride}`);\n if (run.supersededByRunId) lines.push(`superseded by: ${run.supersededByRunId}`);\n if (runUrl) lines.push(`url: ${runUrl}`);\n if (run.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of run.jobs) {\n const placement = job.provider\n ? `${job.provider}${job.region ? `:${job.region}` : ''}`\n : '-';\n lines.push(` ${job.id} ${job.name} ${conclusionLabel(job.state)} ${placement} ${formatDuration(job.durationMs)}`);\n for (const attempt of job.placementAttempts) {\n lines.push(pc.dim(` placement failed on ${attempt.provider}${attempt.region ? `:${attempt.region}` : ''}: ${attempt.error}`));\n }\n for (const step of job.steps) {\n const exit = step.exitCode === null ? '' : ` (exit ${step.exitCode})`;\n lines.push(pc.dim(` ${step.name} ${step.state}${exit} ${formatDuration(step.durationMs)}`));\n }\n }\n }\n return lines.join('\\n');\n}\n\n/** `compute actions inspect` — the run plus everything that shaped it. */\nexport function formatRunInspection(run: CiRunInspection): string {\n const lines: string[] = [];\n lines.push(`${pc.bold('run')} ${conclusionLabel(run.conclusion)}${run.runNumber === null ? '' : ` #${run.runNumber}`}`);\n lines.push(pc.dim(run.id));\n lines.push(`${safeTerm(run.ref)} ${shortSha(run.headSha)} ${safeTerm(run.event)}`);\n lines.push(`queued: ${run.queuedAt} started: ${run.startedAt} finished: ${run.finishedAt}`);\n if (run.cancellationReason) lines.push(`cancelled: ${run.cancellationReason}`);\n if (run.supersededByRunId) lines.push(`superseded by: ${run.supersededByRunId}`);\n if (run.blockedReason) lines.push(pc.red(`blocked: ${safeTerm(run.blockedReason)}`));\n if (run.concurrencyGroup) lines.push(`concurrency: ${safeTerm(run.concurrencyGroup)}`);\n if (run.providerOverride) lines.push(`dispatched to: ${safeTerm(run.providerOverride)}`);\n if (run.definitionStale) {\n const parsed = run.workflowParsedFromSha ? shortSha(run.workflowParsedFromSha) : 'unknown';\n lines.push(pc.yellow(`definition: stored parse is from ${parsed}, not this head — context may be newer than the run`));\n }\n if (run.dispatchInputs && Object.keys(run.dispatchInputs).length > 0) {\n lines.push(`inputs: ${Object.entries(run.dispatchInputs).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(' ')}`);\n }\n if (run.secrets) {\n const names = run.secrets.names.length > 0 ? run.secrets.names.map(safeTerm).join(', ') : 'none';\n lines.push(`secrets (${run.secrets.access}${run.secrets.env ? ', exported to env' : ''}): ${names}`);\n }\n if (run.caches.length > 0) {\n lines.push('');\n lines.push(pc.bold('caches'));\n for (const cache of run.caches) {\n const action = [cache.restoredAt ? 'restored' : null, cache.savedAt ? 'saved' : null]\n .filter(Boolean)\n .join('+');\n lines.push(` ${safeTerm(cache.key)} ${pc.dim(`${action} ${safeTerm(cache.scopeRef)} ${cache.sizeBytes}B`)}`);\n }\n }\n if (run.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of run.jobs) {\n const placement = job.provider\n ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ''}`\n : '-';\n lines.push(` ${safeTerm(job.name)} ${conclusionLabel(job.state)} ${placement}`);\n lines.push(pc.dim(` ${job.id}`));\n if (job.runsOn.length > 0 || job.resolvedRunsOn !== null) {\n const resolved =\n job.resolvedRunsOn !== null && job.resolvedRunsOn.join(',') !== job.runsOn.join(',')\n ? ` → ${job.resolvedRunsOn.map(safeTerm).join(', ')}`\n : '';\n lines.push(` runs-on: ${job.runsOn.map(safeTerm).join(', ') || '(none)'}${resolved}`);\n }\n if (job.runsOnHasExpression) lines.push(pc.dim(' runs-on resolves at runtime (expression)'));\n if (job.container) lines.push(` container: ${safeTerm(job.container)}`);\n if (job.runnerImage) lines.push(` image: ${safeTerm(job.runnerImage)}`);\n if (job.placementHint) {\n lines.push(` pinned: ${safeTerm(job.placementHint.label)}`);\n }\n if (job.concurrencyGroup) {\n lines.push(` concurrency: ${safeTerm(job.concurrencyGroup)}${job.concurrencyCancelInProgress ? ' (cancel-in-progress)' : ''}`);\n }\n const overrides = [\n job.timeoutMinutes !== null ? `timeout ${job.timeoutMinutes}m` : null,\n job.fetchDepth !== null ? `fetch-depth ${job.fetchDepth}` : null,\n ].filter(Boolean);\n if (overrides.length > 0) lines.push(` ${overrides.join(' ')}`);\n if (job.matrix) {\n lines.push(` matrix: ${Object.entries(job.matrix).map(([k, v]) => `${safeTerm(k)}=${safeTerm(v)}`).join(' ')}`);\n }\n if (job.failureReason) lines.push(pc.red(` failed: ${safeTerm(job.failureReason)}`));\n for (const attempt of job.placementAttempts) {\n lines.push(pc.dim(` placement failed on ${safeTerm(attempt.provider)}${attempt.region ? `:${safeTerm(attempt.region)}` : ''}: ${safeTerm(attempt.error)}`));\n }\n }\n }\n return lines.join('\\n');\n}\n\n/** The failure digest rendered for humans — shared by `run` and `summary`. */\nexport function formatRunSummary(summary: CiRunSummary): string {\n const lines: string[] = [];\n lines.push(pc.bold(`failures — run ${summary.runId} ${conclusionLabel(summary.conclusion)}`));\n if (summary.failures.length === 0) {\n lines.push(' no failed jobs');\n return lines.join('\\n');\n }\n for (const job of summary.failures) {\n const placement = job.provider\n ? `${safeTerm(job.provider)}${job.region ? `:${safeTerm(job.region)}` : ''}`\n : '-';\n lines.push(` ${job.id} ${safeTerm(job.name)} ${conclusionLabel(job.conclusion)} ${placement}`);\n if (job.failureReason) lines.push(pc.dim(` ${safeTerm(job.failureReason)}`));\n for (const step of job.failedSteps) {\n const exit = step.exitCode === null ? '' : ` (exit ${step.exitCode})`;\n lines.push(` step ${step.ordinal} ${safeTerm(step.name)}${exit}`);\n }\n if (job.excerpt) {\n const scope = job.excerpt.stepOrdinal === null ? 'job log' : `step ${job.excerpt.stepOrdinal}`;\n const cut = job.excerpt.truncated ? ', truncated' : '';\n lines.push(pc.dim(` ── ${scope} tail${cut} ──`));\n for (const line of job.excerpt.text.split('\\n')) lines.push(` ${safeTerm(line)}`);\n }\n }\n return lines.join('\\n');\n}\n\n// ─── Parsing helpers (pure, exported for tests) ─────────────────────────────\n\n/** `--inputs k=v` pairs → a dispatch inputs object. `k=v` with no `=` is an error. */\nexport function parseInputs(pairs: string[] | undefined): Record<string, string> {\n const inputs: Record<string, string> = {};\n for (const pair of pairs ?? []) {\n const eq = pair.indexOf('=');\n if (eq === -1) {\n throw new ActionsCliError('invalid_argument', `Invalid --inputs entry \"${pair}\". Expected key=value.`);\n }\n inputs[pair.slice(0, eq)] = pair.slice(eq + 1);\n }\n return inputs;\n}\n\n/** Match `--workflow` to a workflow by path first, then by name. */\nexport function matchWorkflow(\n workflows: CiWorkflow[],\n selector: string,\n): CiWorkflow | undefined {\n return (\n workflows.find((w) => w.path === selector) ??\n workflows.find((w) => w.name === selector) ??\n workflows.find((w) => w.id === selector)\n );\n}\n\n/** Match `--job` to a run's job by id, then by name. */\nexport function matchJob(jobs: CiJob[], selector: string): CiJob | undefined {\n return jobs.find((j) => j.id === selector) ?? jobs.find((j) => j.name === selector);\n}\n\n// ─── Logs ───────────────────────────────────────────────────────────────────\n\nasync function readWholeJobLog(client: ActionsClient, jobId: string, step?: string): Promise<CiLogSlice> {\n const segments: CiLogSlice['segments'] = [];\n let offset = 0;\n let slice: CiLogSlice;\n do {\n slice = await client.get<CiLogSlice>(`/api/v1/actions/jobs/${jobId}/logs`, {\n offset: String(offset),\n step,\n });\n segments.push(...slice.segments);\n offset = slice.nextOffset;\n } while (slice.truncated);\n return { ...slice, segments };\n}\n\n/** Follow one job's log over the SSE `follow=1` slice stream, resuming on reconnect. */\nasync function* followJobLog(client: ActionsClient, jobId: string, step?: string): AsyncGenerator<CiLogSlice> {\n let offset = 0;\n for (;;) {\n let terminal = false;\n for await (const raw of client.sse(`/api/v1/actions/jobs/${jobId}/logs`, {\n offset: String(offset),\n follow: '1',\n step,\n })) {\n const slice = raw as CiLogSlice;\n offset = slice.nextOffset;\n if (slice.segments.length > 0 || slice.state !== 'running') yield slice;\n if (slice.state !== 'running' && slice.state !== 'pending' && !slice.truncated) {\n terminal = true;\n }\n }\n if (terminal) return;\n // The connection ended (server-side ceiling or a drop): resume from the\n // offset we hold — resumable cursors make this a continuation, not a replay.\n }\n}\n\n/** `--step` CLI value → the watch-cursor step field. */\nexport function parseStep(step: string | undefined): number | 'runner' | null {\n if (step === undefined) return null;\n if (step === 'runner') return 'runner';\n const n = Number(step);\n if (!Number.isInteger(n) || n < 0) {\n throw new ActionsCliError('invalid_argument', `Invalid --step \"${step}\". Expected a step ordinal or \"runner\".`);\n }\n return n;\n}\n\n/** Follow a run's logs across jobs via the multiplexed run stream. */\nasync function* followRunLogs(\n client: ActionsClient,\n runId: string,\n jobs: CiJob[],\n step?: string,\n): AsyncGenerator<{ job: CiJob; slice: CiLogSlice }> {\n const cursorStep = parseStep(step);\n const offsets = new Map<string, number>(jobs.map((j) => [j.id, 0]));\n const byCursor = new Map<string, CiJob>(jobs.map((j, i) => [`j${i}`, j]));\n for (;;) {\n let done = false;\n const watch = jobs.map((j, i) =>\n encodeWatchCursor(`j${i}`, j.id, cursorStep, offsets.get(j.id) ?? 0),\n );\n for await (const raw of client.sse(`/api/v1/actions/runs/${runId}/stream`, { watch })) {\n const msg = raw as\n | { type: 'state'; state: unknown }\n | { type: 'log'; cursor: string; slice: CiLogSlice }\n | { type: 'done' }\n | { type: 'reconnect' };\n if (msg.type === 'log') {\n const job = byCursor.get(msg.cursor);\n if (job) {\n offsets.set(msg.slice.jobId, msg.slice.nextOffset);\n yield { job, slice: msg.slice };\n }\n } else if (msg.type === 'done') {\n done = true;\n break;\n } else if (msg.type === 'reconnect') {\n break;\n }\n }\n if (done) return;\n // Both an explicit `reconnect` event and an unexpected EOF resume from the\n // offsets we hold; back off briefly so a repeatedly-closing server doesn't\n // spin the loop.\n await new Promise((r) => setTimeout(r, 1000));\n }\n}\n\n// Job and step names come from workflow files — potentially attacker-controlled\n// in a PR context — so strip control characters before writing to the terminal.\nexport function safeTerm(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/[\\u0000-\\u001F\\u007F-\\u009F]/g, '�');\n}\n\nexport function formatRunHistory(history: CiRunHistory): string {\n const lines: string[] = [];\n const parts = (Object.entries(history.conclusions) as [string, number][])\n .map(([c, n]) => `${n} ${c}`)\n .join(', ');\n lines.push(`last ${history.runCount} runs: ${parts || 'none'}`);\n if (history.jobs.length > 0) {\n lines.push('');\n lines.push(pc.bold('jobs'));\n for (const job of history.jobs) {\n const rate = job.runs > 0 ? Math.round((job.failedRuns / job.runs) * 100) : 0;\n const platform = job.failedBeforeSteps > 0 ? pc.dim(` (${job.failedBeforeSteps} failed before steps)`) : '';\n const count = `${job.failedRuns}/${job.runs} runs failed`;\n const label = job.failedRuns > 0 ? pc.red(count) : pc.green(count);\n lines.push(` ${safeTerm(job.job)} ${label} ${rate}%${platform}`);\n for (const step of job.steps) {\n lines.push(pc.dim(` step \"${safeTerm(step.step)}\" failed in ${step.failedRuns} run${step.failedRuns === 1 ? '' : 's'}`));\n }\n }\n }\n const failed = history.runs.filter(\n (r) => r.conclusion === 'failed' || r.failedJobs.length > 0,\n );\n if (failed.length > 0) {\n lines.push('');\n lines.push(pc.bold('failed runs'));\n for (const run of failed) {\n const blame = run.failedJobs.length > 0\n ? run.failedJobs.map((j) => safeTerm(j.step === null ? j.job : `${j.job}:${j.step}`)).join(', ')\n : pc.dim('(no failed job recorded)');\n lines.push(` ${shortSha(run.headSha)} ${pc.dim(run.startedAt)} ${blame}`);\n }\n }\n return lines.join('\\n');\n}\n\nexport function formatProviderRow(p: CiProviderInfo): string {\n const icon = p.usable ? pc.green('●') : pc.gray('○');\n const name = p.usable ? pc.white(p.provider) : pc.gray(p.provider);\n const flags = [\n p.credential,\n p.actCapable ? pc.green('act') : pc.gray('no-act'),\n p.regions.length > 0 ? `regions: ${p.regions.join(',')}` : 'no region choice',\n p.position === null ? pc.gray('not in provider order') : `order #${p.position}`,\n ].join(' ');\n return ` ${icon} ${name} ${flags}`;\n}\n\nexport function formatVerifyResult(r: CiProviderKeyResponse): string {\n const ok = r.verified === true;\n const head = ok ? pc.green('verified') : pc.red('not verified');\n const detail = r.key.statusDetail ? pc.dim(` ${r.key.statusDetail}`) : '';\n const act = r.key.actCapable ? pc.green(' act-capable') : '';\n return `${head} ${r.key.provider}${act}${detail}`;\n}\n\nfunction formatRepoRow(r: CiRepo): string {\n const head = r.enabled ? pc.green('enabled') : pc.dim('disabled');\n const via = r.authType === 'github_app' ? 'github-app' : r.authType;\n const workflows =\n r.workflowPaths.length > 0\n ? `${r.workflowPaths.length} workflow${r.workflowPaths.length === 1 ? '' : 's'}`\n : 'no workflows yet';\n const error = r.lastPollError ? pc.red(` poll error: ${safeTerm(r.lastPollError)}`) : '';\n return `${head} ${safeTerm(r.fullName)} ${pc.dim(`${safeTerm(via)} · ${safeTerm(r.defaultBranch)} · ${workflows}`)}${error}`;\n}\n\n/** Print what an enable/connect discovered — one dim line, nothing on a clean run. */\nfunction printDiscovery(d: { workflowsFound: boolean; seeded: boolean; error: string | null }): void {\n if (d.error) {\n console.log(pc.yellow(`discovery: ${safeTerm(d.error)} (the poll cron retries)`));\n return;\n }\n console.log(pc.dim(`discovery: ${d.workflowsFound ? 'workflows found' : 'no workflows yet'}${d.seeded ? ', cursors seeded' : ''}`));\n}\n\n// ─── Commands ───────────────────────────────────────────────────────────────\n\n/**\n * The `POST /api/v1/actions/dispatch` body for `dispatch`. Without --manual a\n * workflow must declare `workflow_dispatch`. With it, a workflow that doesn't\n * is run anyway; such a run has no inputs, so any given are refused rather\n * than silently dropped. A dispatchable workflow keeps its inputs either way.\n */\nexport function dispatchBody(\n workflow: CiWorkflow,\n opts: {\n ref?: string;\n inputs?: string[];\n manual?: boolean;\n provider?: string;\n providerRegion?: string;\n maxBid?: string;\n maxBidPer?: string;\n },\n): Record<string, unknown> {\n if (!workflow.dispatchable && !opts.manual) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${workflow.path}\" does not declare workflow_dispatch. Pass --manual to run it anyway (no inputs).`,\n );\n }\n if (!workflow.dispatchable && opts.inputs !== undefined && opts.inputs.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `Workflow \"${workflow.path}\" has no workflow_dispatch inputs; --manual runs of it take no --inputs.`,\n );\n }\n const ref = opts.ref ?? workflow.refs[0];\n if (!ref) throw new ActionsCliError('invalid_argument', 'No --ref given and the workflow has no watched refs.');\n if (opts.providerRegion !== undefined && opts.provider === undefined) {\n throw new ActionsCliError('invalid_argument', '--provider-region requires --provider.');\n }\n const maxPrice = maxPriceFields(opts.maxBid, opts.maxBidPer);\n return {\n workflowId: workflow.id,\n ref,\n inputs: parseInputs(opts.inputs),\n ...(opts.manual && { manual: true }),\n ...(opts.provider !== undefined && {\n provider: opts.provider,\n ...(opts.providerRegion !== undefined && { providerRegion: opts.providerRegion }),\n }),\n ...(maxPrice !== undefined && maxPrice),\n };\n}\n\n/**\n * `--max-bid`/`--max-bid-per` → the dispatch body's market price ceiling\n * fields. Undefined when no ceiling is set; the ceiling only applies to a\n * market fill — jobs that can't be filled at the price fall through to the\n * next provider-order entry.\n */\nexport function maxPriceFields(\n maxBid: string | undefined,\n maxBidPer: string | undefined,\n): { maxPriceUsd: number; maxPricePer: 'second' | 'minute' | 'hour' } | undefined {\n if (maxBidPer !== undefined && maxBid === undefined) {\n throw new ActionsCliError('invalid_argument', '--max-bid-per requires --max-bid.');\n }\n if (maxBid === undefined) return undefined;\n const usd = Number(maxBid);\n if (!/^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/.test(maxBid) || !Number.isFinite(usd) || usd <= 0) {\n throw new ActionsCliError('invalid_argument', `Invalid --max-bid \"${maxBid}\". Expected a positive dollar amount (e.g. 0.12).`);\n }\n const per = maxBidPer ?? 'second';\n if (per !== 'second' && per !== 'minute' && per !== 'hour') {\n throw new ActionsCliError('invalid_argument', `--max-bid-per must be second, minute, or hour, got \"${maxBidPer}\".`);\n }\n return { maxPriceUsd: usd, maxPricePer: per };\n}\n\n/** `--kind` for the vault commands: `secret` unless told otherwise. */\nexport function parseVaultKind(kind: string | undefined): CiVaultKind {\n if (kind === undefined || kind === 'secret' || kind === 'variable') return kind ?? 'secret';\n throw new ActionsCliError('invalid_argument', `--kind must be secret or variable, got \"${kind}\".`);\n}\n\n/** A vault route path with its scope in the query string. */\nexport function vaultPath(\n path: string,\n params: { repo?: string; kind?: CiVaultKind; name?: string },\n): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) search.set(key, value);\n }\n const query = search.toString();\n return query ? `${path}?${query}` : path;\n}\n\n/**\n * The `PUT /api/v1/vault` body for `vault set`. The value is sent exactly as\n * read — never trimmed — because whitespace can be part of a key.\n */\nexport function vaultSetBody(\n name: string,\n value: string,\n opts: { kind: CiVaultKind; revealable?: boolean; description?: string; labels?: string[] },\n): Record<string, unknown> {\n if (value === '') throw new ActionsCliError('invalid_argument', 'The value is empty.');\n if (opts.revealable && opts.kind === 'variable') {\n throw new ActionsCliError('invalid_argument', '--revealable applies to secrets; variables are always readable.');\n }\n return {\n name,\n kind: opts.kind,\n value,\n ...(opts.revealable && { revealable: true }),\n ...(opts.description !== undefined && { description: opts.description }),\n ...(opts.labels !== undefined && opts.labels.length > 0 && { labels: opts.labels }),\n };\n}\n\nexport function formatVaultRow(item: CiVaultItem): string {\n const flags = [\n item.kind,\n ...(item.revealable && item.kind === 'secret' ? ['revealable'] : []),\n `v${item.version}`,\n ...(item.source === 'organization' ? ['inherited'] : []),\n ...(item.overridesOrganization ? ['overrides org'] : []),\n ];\n return `${pc.cyan(safeTerm(item.name))} ${pc.dim(flags.join(', '))} ${pc.dim(`updated ${safeTerm(item.updatedAt)}`)}`;\n}\n\nexport function registerActionsCommands(program: Command): void {\n const actions = program\n .command('actions')\n .alias('ci')\n .description('Drive the benchmarks-platform Actions API')\n .configureOutput({ outputError: usageErrorOutput });\n\n const common = (cmd: Command) =>\n cmd\n .option('--api-key <key>', 'API key (default: $COMPUTE_API_KEY)')\n .option('--base-url <url>', 'API base URL (default: https://platform.computesdk.com)')\n .option('--allow-untrusted-host', 'send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)')\n .option('--json', 'print machine-readable JSON');\n\n common(\n actions\n .command('dispatch')\n .description('Dispatch a workflow_dispatch run (or any workflow with --manual)')\n .argument('<repo>', 'repository in owner/repo format')\n .requiredOption('--workflow <path|name>', 'workflow path or name')\n .option('--ref <ref>', 'git ref to run (default: the workflow\\'s first watched ref)')\n .option('--inputs <pairs...>', 'workflow inputs as key=value (workflow_dispatch inputs only)')\n .option('--manual', 'run a workflow even if it does not declare workflow_dispatch (such runs take no --inputs)')\n .option('--provider <id>', 'place the run on one provider (e.g. namespace, vercel:sfo1) instead of the org provider order')\n .option('--provider-region <region>', 'region for --provider (same as --provider <id>:<region>)')\n .option('--max-bid <usd>', 'max price per vCPU for a market fill (e.g. 0.12); unfilled jobs fall through to the next provider')\n .option('--max-bid-per <unit>', 'time unit --max-bid is priced in: second, minute, or hour (default: second)'),\n ).action(async (repo: string, opts: CommonOpts & { workflow: string; ref?: string; inputs?: string[]; manual?: boolean; provider?: string; providerRegion?: string; maxBid?: string; maxBidPer?: string }) => {\n try {\n const c = await client(opts);\n const { workflows } = await c.get<{ workflows: CiWorkflow[] }>(\n '/api/v1/actions/workflows',\n { repo },\n );\n const workflow = matchWorkflow(workflows, opts.workflow);\n if (!workflow) {\n const choices = workflows.map((w) => `${w.path} (${w.name})`).join(', ') || 'none';\n throw new ActionsCliError(\n 'workflow_not_found',\n `No workflow \"${opts.workflow}\" in ${repo}. Available: ${choices}`,\n );\n }\n const body = dispatchBody(workflow, opts);\n const result = await c.post<{ runId: string; created: boolean; headSha: string }>(\n '/api/v1/actions/dispatch',\n body,\n );\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${result.runId}`;\n output(opts, { ...result, url }, (r) => {\n console.log(`${r.created ? 'dispatched' : 'already running'} ${pc.cyan(r.runId)}`);\n console.log(`sha: ${r.headSha}`);\n console.log(`url: ${r.url}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('runs')\n .description('List recent runs for a repo')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--status <status...>', 'filter by conclusion: passed, failed, running, cancelled, none')\n .option('--branch <branch...>', 'filter by branch/ref'),\n ).action(async (repo: string, opts: CommonOpts & { status?: string[]; branch?: string[] }) => {\n try {\n const { runs } = await (await client(opts)).get<{ runs: CiRun[] }>(\n '/api/v1/actions/runs',\n { repo, status: opts.status, branch: opts.branch },\n );\n output(opts, runs, (rs) => {\n if (rs.length === 0) {\n console.log('No runs found.');\n return;\n }\n for (const run of rs) console.log(formatRunRow(run));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('history')\n .description('Recent run history for a workflow — per-job/step failure rates (is this failure flaky?)')\n .argument('<repo>', 'repository in owner/repo format')\n .requiredOption('--workflow <path|name>', 'workflow path or name')\n .option('--branch <branch...>', 'narrow the window to branches/refs')\n .option('--job <job>', 'narrow the rollup to one job name or workflow job id')\n .option('--limit <n>', 'runs in the window (default 10, max 50)'),\n ).action(async (repo: string, opts: CommonOpts & { workflow: string; branch?: string[]; job?: string; limit?: string }) => {\n try {\n const c = await client(opts);\n const { workflows } = await c.get<{ workflows: CiWorkflow[] }>(\n '/api/v1/actions/workflows',\n { repo },\n );\n const workflow = matchWorkflow(workflows, opts.workflow) ?? workflows.find((w) => w.path === opts.workflow);\n const workflowPath = workflow?.path ?? opts.workflow;\n const history = await c.get<CiRunHistory>('/api/v1/actions/history', {\n repo,\n workflow: workflowPath,\n branch: opts.branch,\n job: opts.job,\n limit: opts.limit,\n });\n output(opts, history, (h) => console.log(formatRunHistory(h)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('run')\n .description('Show a run: jobs, provider:region placement, placement attempts')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const run = await c.get<CiRun>(`/api/v1/actions/runs/${runId}`);\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${run.id}`;\n // A failed run's interesting part is its failure digest; on deployments\n // that have the summary route it prints inline, saving a second command.\n const summary = run.conclusion === 'failed' ? await fetchRunSummary(c, runId) : null;\n output(opts, { ...run, url, summary }, (r) => {\n console.log(formatRunDetail(r, r.url));\n if (summary && summary.failures.length > 0) {\n console.log('');\n console.log(formatRunSummary(summary));\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('summary')\n .description('Show a run\\'s failure digest: failed jobs, failed steps, bounded log tails')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const summary = await (await client(opts)).get<CiRunSummary>(`/api/v1/actions/runs/${runId}/summary`);\n output(opts, summary, (s) => console.log(formatRunSummary(s)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('inspect')\n .description('Inspect a run: resolved runner image, caches, secret names, concurrency, placement context')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const inspection = await c.get<CiRunInspection>(\n `/api/v1/actions/runs/${runId}/state`,\n );\n output(opts, inspection, (r) => console.log(formatRunInspection(r)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('logs')\n .description('Print or follow a run\\'s job logs')\n .argument('<run-id>', 'run ID')\n .option('--job <job>', 'job ID or name (default: all jobs)')\n .option('--step <step>', 'step ordinal or \"runner\" (default: whole job)')\n .option('--follow', 'stream logs while the run is live'),\n ).action(async (runId: string, opts: CommonOpts & { job?: string; step?: string; follow?: boolean }) => {\n try {\n const c = await client(opts);\n let jobs = await listRunJobs(c, runId);\n if (opts.job) {\n const job = matchJob(jobs, opts.job);\n if (!job) {\n throw new Error(\n `No job \"${opts.job}\" in run ${runId}. Jobs: ${jobs.map((j) => j.name).join(', ') || 'none'}`,\n );\n }\n jobs = [job];\n }\n if (jobs.length === 0) {\n if (opts.json) output(opts, { segments: [] }, () => {});\n else console.error('Run has no jobs yet.');\n return;\n }\n\n if (!opts.follow) {\n for (const job of jobs) {\n const slice = await readWholeJobLog(c, job.id, opts.step);\n if (opts.json) {\n process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + '\\n');\n } else {\n if (jobs.length > 1) console.log(pc.bold(`── ${job.name} ──`));\n for (const seg of slice.segments) process.stdout.write(seg.text);\n }\n }\n return;\n }\n\n if (jobs.length === 1) {\n // Single job: the slice endpoint's own SSE, resumed on reconnect.\n for await (const slice of followJobLog(c, jobs[0].id, opts.step)) {\n if (opts.json) {\n process.stdout.write(JSON.stringify(slice) + '\\n');\n } else {\n for (const seg of slice.segments) process.stdout.write(seg.text);\n }\n }\n return;\n }\n\n // Multiple jobs: one multiplexed stream, each slice tagged by job.\n for await (const { job, slice } of followRunLogs(c, runId, jobs, opts.step)) {\n if (opts.json) {\n process.stdout.write(JSON.stringify({ jobId: job.id, name: job.name, slice }) + '\\n');\n } else {\n for (const seg of slice.segments) {\n const text = seg.text.replace(/\\n/g, `\\n[${job.name}] `);\n process.stdout.write(`[${job.name}] ${text}`);\n }\n }\n }\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const providers = actions\n .command('providers')\n .description('List the org\\'s registered compute providers (regions, act/usable status)');\n common(providers).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiProvidersResponse>('/api/v1/actions/providers');\n output(opts, data, (d) => {\n for (const p of d.providers) console.log(formatProviderRow(p));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('configure')\n .description('Save the org\\'s credential for a provider (owner/admin API key)')\n .argument('<provider>', 'provider id (e.g. tensorlake, blaxel)')\n .option('--key <key>', 'provider API key (single-field credentials)')\n .option('--field <pair...>', 'credential fields as name=value (multi-field providers)')\n .option('--verify', 'run the placement probe after saving'),\n ).action(async (provider: string, opts: CommonOpts & { key?: string; field?: string[]; verify?: boolean }) => {\n try {\n const c = await client(opts);\n let body: Record<string, unknown>;\n if (opts.field !== undefined) {\n if (opts.key !== undefined) throw new Error('Pass either --key or --field, not both.');\n body = { fields: parseInputs(opts.field) };\n } else if (opts.key !== undefined) {\n body = { key: opts.key };\n } else {\n throw new Error('Pass --key <key> or --field name=value.');\n }\n const saved = await c.put<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/key`,\n body,\n );\n const verification = opts.verify\n ? await c.post<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/verify`,\n )\n : undefined;\n output(opts, verification ? { key: saved.key, verification } : saved, () => {\n console.log(`saved ${saved.key.provider} ${pc.dim(saved.key.keyHint)} ${saved.key.status}`);\n if (verification) console.log(formatVerifyResult(verification));\n });\n if (verification?.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('verify')\n .description('Probe the stored provider key with a real sandbox (\"Test\" in Settings)')\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<CiProviderKeyResponse>(\n `/api/v1/actions/providers/${provider}/verify`,\n );\n output(opts, result, (r) => console.log(formatVerifyResult(r)));\n if (result.verified === false) process.exitCode = 1;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n providers\n .command('remove')\n .description('Delete the org\\'s stored credential for a provider')\n .argument('<provider>', 'provider id'),\n ).action(async (provider: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ provider: string; deleted: boolean }>(\n `/api/v1/actions/providers/${provider}/key`,\n );\n output(opts, result, (r) => {\n console.log(r.deleted ? `deleted ${r.provider}` : `no key stored for ${r.provider}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const repos = actions\n .command('repos')\n .description('List the org\\'s connected repositories');\n common(repos).action(async (opts: CommonOpts) => {\n try {\n const data = await (await client(opts)).get<CiReposResponse>('/api/v1/actions/repos');\n output(opts, data, (d) => {\n for (const r of d.repos) console.log(formatRepoRow(r));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('connect')\n .description('Connect a git remote (validated by a real ls-remote; lands enabled)')\n .argument('<cloneUrl>', 'http(s) or ssh git remote URL')\n .option('--name <owner/repo>', 'repo name override (default: derived from cloneUrl)')\n .option('--branch <branch>', 'default branch (default: main, else the remote\\'s first)')\n .option('--token <token>', 'credential for private http(s) remotes')\n .option('--username <user>', 'username — with --token, makes auth \"basic\" instead of \"token\"')\n .option('--ssh-key-file <path>', 'OpenSSH/PEM private key file for ssh remotes')\n .option('--known-hosts-file <path>', 'known_hosts pin for ssh remotes'),\n ).action(async (cloneUrl: string, opts: CommonOpts & { name?: string; branch?: string; token?: string; username?: string; sshKeyFile?: string; knownHostsFile?: string }) => {\n try {\n let body: Record<string, unknown>;\n if (opts.sshKeyFile !== undefined) {\n if (opts.token !== undefined || opts.username !== undefined) {\n throw new Error('Pass either --ssh-key-file or --token/--username, not both.');\n }\n body = {\n authType: 'ssh',\n credential: readFileSync(opts.sshKeyFile, 'utf8'),\n ...(opts.knownHostsFile !== undefined && {\n knownHosts: readFileSync(opts.knownHostsFile, 'utf8'),\n }),\n };\n } else if (opts.username !== undefined) {\n if (opts.token === undefined) throw new Error('--username requires --token.');\n body = { authType: 'basic', username: opts.username, credential: opts.token };\n } else if (opts.token !== undefined) {\n body = { authType: 'token', credential: opts.token };\n } else {\n body = { authType: 'none' };\n }\n if (opts.knownHostsFile !== undefined && opts.sshKeyFile === undefined) {\n throw new Error('--known-hosts-file requires --ssh-key-file.');\n }\n const result = await (await client(opts)).post<CiRepoConnectResponse>('/api/v1/actions/repos', {\n cloneUrl,\n ...body,\n ...(opts.name !== undefined && { name: opts.name }),\n ...(opts.branch !== undefined && { defaultBranch: opts.branch }),\n });\n output(opts, result, (r) => {\n console.log(`connected ${pc.cyan(safeTerm(r.fullName))} ${pc.dim(`(${safeTerm(r.authType)}, ${safeTerm(r.defaultBranch)})`)}`);\n printDiscovery(r.discovery);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('enable')\n .description('Enable a repo the org can already see (granted by a GitHub App install, or a connected remote)')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--repo-id <id>', 'scope to one row when two installations grant the same name'),\n ).action(async (repo: string, opts: CommonOpts & { repoId?: string }) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: true,\n ...(opts.repoId !== undefined && { repoId: opts.repoId }),\n });\n output(opts, result, (r) => {\n console.log(`enabled ${pc.cyan(safeTerm(r.fullName))}`);\n if (r.discovery) printDiscovery(r.discovery);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n repos\n .command('disable')\n .description('Disable a repo — it stays connected but no runs are scheduled')\n .argument('<repo>', 'repository in owner/repo format')\n .option('--repo-id <id>', 'scope to one row when two installations grant the same name'),\n ).action(async (repo: string, opts: CommonOpts & { repoId?: string }) => {\n try {\n const result = await (await client(opts)).patch<CiRepoPatchResponse>('/api/v1/actions/repos', {\n fullName: repo,\n enabled: false,\n ...(opts.repoId !== undefined && { repoId: opts.repoId }),\n });\n output(opts, result, (r) => console.log(`disabled ${pc.cyan(safeTerm(r.fullName))}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const vault = actions\n .command('vault')\n .description('The org vault: secrets and variables (owner/admin key)');\n const vaultScope = (cmd: Command) =>\n common(cmd)\n .option('--repo <owner/repo>', 'scope to a repo\\'s own items instead of the org\\'s')\n .option('--kind <kind>', 'secret or variable', 'secret');\n type VaultOpts = CommonOpts & { repo?: string; kind?: string };\n\n vaultScope(\n vault.command('ls').description('List names and metadata (never values)'),\n ).action(async (opts: VaultOpts) => {\n try {\n const path = vaultPath('/api/v1/vault', { repo: opts.repo, kind: parseVaultKind(opts.kind) });\n const data = await (await client(opts)).get<CiVaultListResponse>(path);\n output(opts, data, (d) => {\n for (const item of d.items) console.log(formatVaultRow(item));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('set')\n .description('Store a value, read from stdin (or --from-file) and sent exactly as read')\n .argument('<name>', 'item name, e.g. NPM_TOKEN')\n .option('--from-file <path>', 'read the value from a file instead of stdin')\n .option('--revealable', 'let the value be read back with `vault get` (secrets; fixed at creation)')\n .option('--description <text>', 'what the item is for')\n .option('--labels <labels...>', 'labels (fixed at creation)'),\n ).action(async (name: string, opts: VaultOpts & { fromFile?: string; revealable?: boolean; description?: string; labels?: string[] }) => {\n try {\n if (opts.fromFile === undefined && process.stdin.isTTY) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Pipe the value on stdin (e.g. printf %s \"$VALUE\" | compute actions vault set NAME) or pass --from-file.',\n );\n }\n const value = readFileSync(opts.fromFile ?? 0, 'utf8');\n const kind = parseVaultKind(opts.kind);\n const body = vaultSetBody(name, value, { ...opts, kind });\n const result = await (await vaultValueClient(opts)).put<CiVaultSaveResponse>(\n vaultPath('/api/v1/vault', { repo: opts.repo }),\n body,\n );\n output(opts, result, (r) => {\n const where = opts.repo ? safeTerm(opts.repo) : 'org';\n console.log(`saved ${pc.cyan(safeTerm(r.item.name))} ${pc.dim(`(${r.item.kind}, v${r.item.version}, ${where})`)}`);\n if (/\\r?\\n$/.test(value)) {\n console.error(pc.yellow('note: the stored value ends with a newline; use printf %s rather than echo to avoid one.'));\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('get')\n .description('Print a value: any variable, or a secret created --revealable')\n .argument('<name>', 'item name'),\n ).action(async (name: string, opts: VaultOpts) => {\n try {\n const kind = parseVaultKind(opts.kind);\n const result = await (await vaultValueClient(opts)).post<CiVaultRevealResponse>(\n vaultPath('/api/v1/vault/reveal', { repo: opts.repo }),\n { name, kind },\n );\n output(opts, result, (r) => process.stdout.write(r.value));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n vaultScope(\n vault\n .command('rm')\n .description('Delete an item (with --repo, only the repo\\'s override)')\n .argument('<name>', 'item name'),\n ).action(async (name: string, opts: VaultOpts) => {\n try {\n const path = vaultPath('/api/v1/vault', { repo: opts.repo, kind: parseVaultKind(opts.kind), name });\n const result = await (await client(opts)).del<CiVaultDeleteResponse>(path);\n output(opts, result, (r) => console.log(`deleted ${pc.cyan(safeTerm(r.name))} ${pc.dim(`(${r.kind})`)}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('cancel')\n .description('Cancel a run')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).post<{ cancelled: boolean }>(\n `/api/v1/actions/runs/${runId}/cancel`,\n );\n output(opts, result, (r) => {\n console.log(r.cancelled ? `Cancelled ${runId}` : `Run ${runId} was already finished`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('rerun')\n .description('Re-run a finished run at the same commit')\n .argument('<run-id>', 'run ID'),\n ).action(async (runId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const result = await c.post<{ runId: string; created: boolean }>(\n `/api/v1/actions/runs/${runId}/rerun`,\n );\n const org = await c.org();\n const url = `${c.baseUrl}/${org.slug}/actions/runs/${result.runId}`;\n output(opts, { ...result, url }, (r) => {\n console.log(`${r.created ? 'rerun dispatched' : 'rerun already running'} ${pc.cyan(r.runId)}`);\n console.log(`url: ${r.url}`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n actions\n .command('artifacts')\n .description('List or download a run\\'s artifacts')\n .argument('<run-id>', 'run ID')\n .option('--job <job>', 'job ID or name (default: all jobs)')\n .option('--out <dir>', 'download artifacts into this directory instead of listing'),\n ).action(async (runId: string, opts: CommonOpts & { job?: string; out?: string }) => {\n try {\n const c = await client(opts);\n let jobs = await listRunJobs(c, runId);\n if (opts.job) {\n const job = matchJob(jobs, opts.job);\n if (!job) throw new Error(`No job \"${opts.job}\" in run ${runId}.`);\n jobs = [job];\n }\n const entries: { job: CiJob; artifacts: CiArtifactListItem[] }[] = [];\n for (const job of jobs) {\n const artifacts = await c.get<CiArtifactListItem[]>(\n `/api/v1/actions/jobs/${job.id}/artifacts`,\n );\n entries.push({ job, artifacts });\n }\n\n if (opts.out) {\n const written: { jobId: string; id: string; file: string }[] = [];\n for (const { job, artifacts } of entries) {\n // Per-job directory: artifact names are not unique across jobs.\n const jobDir = join(opts.out, sanitizePathPart(job.name || job.id));\n mkdirSync(jobDir, { recursive: true });\n for (const artifact of artifacts) {\n if (artifact.expired || artifact.skippedReason) continue;\n const bytes = await c.download(\n `/api/v1/actions/jobs/${job.id}/artifacts/${artifact.id}`,\n );\n const file = join(jobDir, sanitizePathPart(artifact.fileName || artifact.name));\n writeFileSync(file, bytes);\n written.push({ jobId: job.id, id: artifact.id, file });\n }\n }\n output(opts, written, (ws) => {\n for (const w of ws) console.log(`wrote ${w.file}`);\n if (ws.length === 0) console.log('No downloadable artifacts.');\n });\n return;\n }\n\n output(opts, entries.map((e) => ({ jobId: e.job.id, job: e.job.name, artifacts: e.artifacts })), (es) => {\n let any = false;\n for (const { job, artifacts } of es) {\n for (const a of artifacts) {\n any = true;\n const flags = a.expired ? ' expired' : a.skippedReason ? ` skipped: ${a.skippedReason}` : '';\n console.log(\n `${job} ${a.id} ${a.name} ${a.contentType} ${a.byteLength}B${flags}`,\n );\n }\n }\n if (!any) console.log('No artifacts.');\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * Thin client for the benchmarks-platform Actions v1 API.\n * Types mirror the wire shapes in benchmarks-platform `lib/ci/types.ts` —\n * keep them in sync by hand; the API is the contract.\n */\n\n\nexport const DEFAULT_BASE_URL = 'https://platform.computesdk.com';\n\nexport interface ActionsAuth {\n apiKey: string;\n baseUrl: string;\n}\n\nexport interface CiWorkflowInput {\n name: string;\n description: string;\n type: 'string' | 'number' | 'boolean' | 'choice' | 'environment';\n required: boolean;\n default: string;\n options?: string[];\n}\n\nexport interface CiWorkflow {\n id: string;\n repoFullName: string;\n name: string;\n path: string;\n dispatchable: boolean;\n refs: string[];\n inputs: CiWorkflowInput[];\n schedules: unknown[];\n}\n\nexport type CiConclusion = 'passed' | 'failed' | 'running' | 'cancelled' | 'none';\nexport type CiJobState =\n | 'queued'\n | 'running'\n | 'passed'\n | 'failed'\n | 'skipped'\n | 'cancelled';\n\nexport interface CiPlacementAttempt {\n provider: string;\n region?: string | null;\n error: string;\n}\n\nexport interface CiStep {\n name: string;\n state: CiJobState;\n durationMs: number | null;\n exitCode: number | null;\n}\n\nexport interface CiJob {\n id: string;\n name: string;\n needs: string[];\n workflowJobId: string | null;\n matrix: Record<string, string> | null;\n state: CiJobState;\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n placementAttempts: CiPlacementAttempt[];\n durationMs: number | null;\n steps: CiStep[];\n}\n\nexport interface CiRun {\n id: string;\n repoFullName: string;\n ref: string;\n branchReason: string | null;\n headSha: string;\n event: string;\n prNumber: number | null;\n runNumber: number | null;\n title: string;\n workflowPath: string;\n workflowName: string;\n conclusion: CiConclusion;\n startedAt: string;\n durationMs: number | null;\n supersededByRunId: string | null;\n concurrencyGroup: string | null;\n cancellationReason: string | null;\n /** `provider[:region]` the dispatch pinned this run to, else null. */\n providerOverride?: string | null;\n jobs: CiJob[];\n logTail: string[];\n}\n\n/**\n * One job of `GET /api/v1/actions/runs/{id}/state`: the live fields plus the\n * context that decided how the job ran — resolved runner image, container\n * pin, concurrency group, timeout/fetch-depth overrides.\n */\nexport interface CiJobInspection {\n id: string;\n name: string;\n state: CiJobState;\n provider: string | null;\n region: string | null;\n sandboxId: string | null;\n startedAt: string | null;\n finishedAt: string | null;\n placementAttempts: CiPlacementAttempt[];\n /** Why the platform failed the job before steps ran, when it did. */\n failureReason: string | null;\n /** The `runs-on:` labels as declared. */\n runsOn: string[];\n /** The `computesdk:` placement pin the labels carried, when one did. */\n placementHint: { provider: string; region: string | null; label: string } | null;\n /** Labels act actually read (placement labels stripped, default substituted). */\n resolvedRunsOn: string[] | null;\n runsOnHasExpression: boolean;\n /** The image the job's steps ran in: container pin, else the mapped label. */\n runnerImage: string | null;\n /** The literal `container:` image the job declared, if any. */\n container: string | null;\n timeoutMinutes: number | null;\n /** Deepest `fetch-depth` a checkout step pinned (0 = full history). */\n fetchDepth: number | null;\n concurrencyGroup: string | null;\n concurrencyCancelInProgress: boolean;\n matrix: Record<string, string> | null;\n steps: {\n ordinal: number;\n name: string;\n state: CiJobState;\n exitCode: number | null;\n startedAt: string | null;\n finishedAt: string | null;\n }[];\n}\n\n/** A cache entry the run's window touched (saved or restored). */\nexport interface CiRunCacheTouch {\n key: string;\n version: string;\n scopeRef: string;\n sizeBytes: number;\n savedAt: string | null;\n restoredAt: string | null;\n}\n\n/** `GET /api/v1/actions/runs/{id}/state` — a run plus its effective context. */\nexport interface CiRunInspection {\n id: string;\n conclusion: CiConclusion;\n runNumber: number | null;\n ref: string;\n headSha: string;\n event: string;\n queuedAt: string;\n startedAt: string | null;\n finishedAt: string | null;\n supersededByRunId: string | null;\n cancellationReason: string | null;\n /** Why the run was refused before placement, when it was. */\n blockedReason: string | null;\n concurrencyGroup: string | null;\n dispatchInputs: Record<string, string> | null;\n providerOverride: string | null;\n /** The commit the stored workflow definition was parsed from. */\n workflowParsedFromSha: string | null;\n /**\n * True when the stored parse came from a different commit than the run's\n * head — the definition-derived fields may then describe a newer workflow\n * than the run used (a fork pull request always shows this by design).\n */\n definitionStale: boolean;\n /** Secret *names* the jobs could reference — never values. */\n secrets: {\n access: 'declared' | 'all';\n /** Whether named secrets are also exported as job env vars. */\n env: boolean;\n names: string[];\n } | null;\n caches: CiRunCacheTouch[];\n jobs: CiJobInspection[];\n}\n\n/**\n * `GET /api/v1/actions/runs/{runId}/summary` — a run's failure digest.\n * Wire shape mirrors `CiRunSummary` in benchmarks-platform `lib/ci/run-summary.ts`.\n */\nexport interface CiRunSummaryJob {\n id: string;\n name: string;\n conclusion: CiJobState;\n provider: string | null;\n region: string | null;\n}\n\nexport interface CiRunSummaryFailedStep {\n ordinal: number;\n name: string;\n exitCode: number | null;\n}\n\nexport interface CiRunSummaryFailure extends CiRunSummaryJob {\n failureReason: string | null;\n failedSteps: CiRunSummaryFailedStep[];\n excerpt: {\n stepOrdinal: number | null;\n text: string;\n truncated: boolean;\n } | null;\n}\n\nexport interface CiRunSummary {\n runId: string;\n conclusion: CiConclusion;\n jobs: CiRunSummaryJob[];\n failures: CiRunSummaryFailure[];\n}\n\nexport interface CiArtifactListItem {\n id: string;\n name: string;\n fileName: string;\n contentType: string;\n byteLength: number;\n fileCount: number;\n skippedReason: string | null;\n expiresAt: string;\n expired: boolean;\n}\n\nexport interface CiLogSegment {\n byteOffset: number;\n stream: 'stdout' | 'stderr';\n stepOrdinal: number | null;\n text: string;\n}\n\n/** One resumable read of a job log. Resume from `nextOffset`. */\nexport interface CiLogSlice {\n jobId: string;\n fromOffset: number;\n nextOffset: number;\n totalBytes: number;\n segments: CiLogSegment[];\n state: 'running' | 'complete' | 'failed' | 'cancelled' | 'expired' | 'pending';\n truncated: boolean;\n}\n\nexport interface CiProviderInfo {\n provider: string;\n /** Selectable regions for `provider:region` order entries; empty when unknown. */\n regions: string[];\n credential: 'ambient' | 'configured' | 'not-configured';\n /** In the effective act set: built-ins, CI_ACT_PROVIDERS override, act-probe-verified keys. */\n actCapable: boolean;\n /** A placement reaching the provider finds credentials. */\n usable: boolean;\n /** 1-based position in the effective provider order, null when absent. */\n position: number | null;\n}\n\nexport interface CiProvidersResponse {\n providerOrder: string[];\n providers: CiProviderInfo[];\n}\n\n/** A saved provider credential — never carries key material, only the hint. */\nexport interface CiProviderKeyRecord {\n provider: string;\n keyHint: string;\n lastCheckedAt: string | null;\n status: 'connected' | 'error' | 'unconfigured';\n statusDetail: string | null;\n actCapable: boolean;\n credential: 'key';\n fields: unknown[];\n}\n\nexport interface CiProviderKeyResponse {\n key: CiProviderKeyRecord;\n /** Present on the verify response. */\n verified?: boolean;\n}\n\n/** One failed job inside a run-history entry — step is the first failed step. */\nexport interface CiRunJobFailure {\n job: string;\n workflowJobId: string | null;\n step: string | null;\n stepOrdinal: number | null;\n}\n\nexport interface CiRunHistoryEntry {\n id: string;\n ref: string;\n headSha: string;\n runNumber: number | null;\n conclusion: CiConclusion;\n startedAt: string;\n failedJobs: CiRunJobFailure[];\n}\n\nexport interface CiJobHistory {\n job: string;\n /** The workflow job key, when recorded; disambiguates same-named jobs. */\n workflowJobId: string | null;\n /** Runs in the window that contained this job. */\n runs: number;\n failedRuns: number;\n /** Runs where the job failed with no step blamed (platform failures). */\n failedBeforeSteps: number;\n steps: { step: string; ordinal: number; failedRuns: number }[];\n}\n\n/** `GET /api/v1/actions/history` — the window plus the rollup over it. */\nexport interface CiRunHistory {\n runCount: number;\n conclusions: Partial<Record<CiConclusion, number>>;\n jobs: CiJobHistory[];\n runs: CiRunHistoryEntry[];\n}\n\nexport interface ActionsOrg {\n organizationId: string;\n name: string;\n slug: string;\n}\n\n/**\n * One row of `GET /api/v1/actions/repos`: a repo the org can run CI on,\n * GitHub-App-granted or a generic git remote.\n */\nexport interface CiRepo {\n repoId: string;\n fullName: string;\n defaultBranch: string;\n enabled: boolean;\n private: boolean;\n forkPullRequests: boolean;\n /** `github_app` for App-granted repos; `none`/`token`/`basic`/`ssh` for remotes. */\n authType: string;\n cloneUrl: string | null;\n githubInstallationId: number | null;\n workflowPaths: string[];\n disabledWorkflowCount: number;\n lastPolledAt: string | null;\n lastPollError: string | null;\n}\n\nexport interface CiReposResponse {\n repos: CiRepo[];\n}\n\n/** What an enable/remote-connect discovered before answering. */\nexport interface CiRepoDiscovery {\n workflowsFound: boolean;\n seeded: boolean;\n error: string | null;\n}\n\nexport interface CiRepoConnectResponse {\n repoId: string | null;\n fullName: string;\n defaultBranch: string;\n authType: string;\n discovery: CiRepoDiscovery;\n}\n\nexport interface CiRepoPatchResponse {\n fullName: string;\n enabled?: boolean;\n forkPullRequests?: boolean;\n discovery: CiRepoDiscovery | null;\n}\n\nexport type CiVaultKind = 'secret' | 'variable';\n\n/** One row of `GET /api/v1/vault` — metadata only; values never list. */\nexport interface CiVaultItem {\n name: string;\n kind: CiVaultKind;\n description: string | null;\n revealable: boolean;\n labels: string[];\n version: number;\n createdAt: string;\n updatedAt: string;\n /** Present when listing or writing with `?repo=`. */\n source?: 'organization' | 'repository';\n overridesOrganization?: boolean;\n}\n\nexport interface CiVaultListResponse {\n items: CiVaultItem[];\n}\n\nexport interface CiVaultSaveResponse {\n item: CiVaultItem;\n}\n\nexport interface CiVaultRevealResponse {\n name: string;\n kind: CiVaultKind;\n value: string;\n}\n\nexport interface CiVaultDeleteResponse {\n name: string;\n kind: CiVaultKind;\n deleted: true;\n}\n\nexport class ActionsApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public body?: unknown,\n ) {\n super(message);\n this.name = 'ActionsApiError';\n }\n}\n\n/** Stable machine-readable codes for errors raised by the CLI itself. */\nexport type ActionsCliErrorCode =\n | 'no_credentials'\n | 'untrusted_host'\n | 'untrusted_host_stored_auth'\n | 'insecure_transport'\n | 'invalid_argument'\n | 'workflow_not_found';\n\n/** An error the CLI raised before or instead of an API call. */\nexport class ActionsCliError extends Error {\n constructor(\n public code: ActionsCliErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'ActionsCliError';\n }\n}\n\n/** The `--json` error envelope; `code` is stable, `message` is for humans. */\nexport interface ActionsErrorEnvelope {\n ok: false;\n error: {\n code: string;\n message: string;\n /** Present when the platform answered; absent for local/transport failures. */\n httpStatus?: number;\n retryable: boolean;\n /** The platform's `details` object, when its error response carried one. */\n details?: Record<string, unknown>;\n };\n}\n\nfunction codeForStatus(status: number): string {\n switch (status) {\n case 400: return 'bad_request';\n case 401: return 'unauthenticated';\n case 403: return 'forbidden';\n case 404: return 'not_found';\n case 409: return 'conflict';\n case 413: return 'payload_too_large';\n case 429: return 'rate_limited';\n default: return status >= 500 ? 'server_error' : 'http_error';\n }\n}\n\nfunction errorDetails(body: unknown): Record<string, unknown> | undefined {\n if (body && typeof body === 'object' && 'details' in body) {\n const details = (body as { details: unknown }).details;\n if (details && typeof details === 'object' && !Array.isArray(details)) {\n return details as Record<string, unknown>;\n }\n }\n return undefined;\n}\n\n/**\n * Classify any error thrown by an Actions command. API errors carry the HTTP\n * status; CLI errors carry their own code; a fetch rejection (DNS, refused\n * connection, TLS) is `network`; anything else is `unknown`.\n */\nexport function toErrorEnvelope(error: unknown): ActionsErrorEnvelope {\n if (error instanceof ActionsApiError) {\n const details = errorDetails(error.body);\n return {\n ok: false,\n error: {\n code: codeForStatus(error.status),\n message: error.message,\n httpStatus: error.status,\n retryable: error.status === 429 || error.status === 502 || error.status === 503 || error.status === 504,\n ...(details !== undefined && { details }),\n },\n };\n }\n if (error instanceof ActionsCliError) {\n return { ok: false, error: { code: error.code, message: error.message, retryable: false } };\n }\n // undici/Node fetch rejects with a TypeError whose cause is the socket error.\n if (error instanceof TypeError && /fetch failed/i.test(error.message)) {\n const cause = (error as { cause?: unknown }).cause;\n const detail = cause instanceof Error ? `: ${cause.message}` : '';\n return {\n ok: false,\n error: { code: 'network', message: `${error.message}${detail}`, retryable: true },\n };\n }\n return {\n ok: false,\n error: {\n code: 'unknown',\n message: error instanceof Error ? error.message : String(error),\n retryable: false,\n },\n };\n}\n\nexport class ActionsClient {\n private orgPromise: Promise<ActionsOrg> | null = null;\n\n constructor(\n private readonly auth: ActionsAuth,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {}\n\n get baseUrl(): string {\n return this.auth.baseUrl;\n }\n\n /** The credential's org — fetched once, needed for dashboard URLs. */\n org(): Promise<ActionsOrg> {\n this.orgPromise ??= this.get<ActionsOrg>('/api/v1/actions/org');\n return this.orgPromise;\n }\n\n async get<T>(path: string, params?: Record<string, string | string[] | undefined>): Promise<T> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, { headers: this.headers() });\n return this.parse<T>(res);\n }\n\n async post<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'POST',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async put<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'PUT',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async patch<T>(path: string, body: Record<string, unknown> = {}): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'PATCH',\n headers: { ...this.headers(), 'content-type': 'application/json' },\n body: JSON.stringify(body),\n });\n return this.parse<T>(res);\n }\n\n async del<T>(path: string): Promise<T> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n method: 'DELETE',\n headers: this.headers(),\n });\n return this.parse<T>(res);\n }\n\n /**\n * One `data:` JSON payload per SSE event. `next()` resolves to the payload,\n * or null when the stream ends. Call `close()` to abort.\n */\n async *sse(path: string, params?: Record<string, string | string[] | undefined>): AsyncGenerator<unknown> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, {\n headers: { ...this.headers(), accept: 'text/event-stream' },\n });\n if (!res.ok) {\n await this.parse(res); // throws\n }\n if (!res.body) throw new Error('SSE response has no body');\n yield* readSseEvents(res.body);\n }\n\n /**\n * `sse()` with the frame's `event:` name preserved — for streams whose\n * events are distinguished by name rather than payload shape (process\n * follow: stdout/stderr share a `{chunk}` payload).\n */\n async *sseNamed(\n path: string,\n params?: Record<string, string | string[] | undefined>,\n ): AsyncGenerator<{ event: string; data: unknown }> {\n const url = new URL(`${this.auth.baseUrl}${path}`);\n for (const [key, value] of Object.entries(params ?? {})) {\n if (value === undefined) continue;\n for (const v of Array.isArray(value) ? value : [value]) url.searchParams.append(key, v);\n }\n const res = await this.fetchImpl(url, {\n headers: { ...this.headers(), accept: 'text/event-stream' },\n });\n if (!res.ok) {\n await this.parse(res); // throws\n }\n if (!res.body) throw new Error('SSE response has no body');\n yield* readSseNamedEvents(res.body);\n }\n\n /** Download bytes following redirects (artifact URLs 302 to storage). */\n async download(path: string): Promise<Uint8Array> {\n const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {\n headers: this.headers(),\n redirect: 'follow',\n });\n if (!res.ok) {\n const body = await res.json().catch(() => undefined);\n throw new ActionsApiError(res.status, errorMessage(body, res.status), body);\n }\n return new Uint8Array(await res.arrayBuffer());\n }\n\n private headers(): Record<string, string> {\n return { authorization: `Bearer ${this.auth.apiKey}`, accept: 'application/json' };\n }\n\n private async parse<T>(res: Response): Promise<T> {\n const body = await res.json().catch(() => undefined);\n if (!res.ok) throw new ActionsApiError(res.status, errorMessage(body, res.status), body);\n return body as T;\n }\n}\n\nfunction errorMessage(body: unknown, status: number): string {\n if (body && typeof body === 'object' && 'error' in body && typeof (body as { error: unknown }).error === 'string') {\n return (body as { error: string }).error;\n }\n return `Request failed with status ${status}`;\n}\n\n/** Minimal SSE reader: yields the JSON payload of each `data:` event. */\nexport async function* readSseEvents(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<unknown> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let idx;\n while ((idx = buffer.indexOf('\\n\\n')) !== -1) {\n const event = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n for (const line of event.split('\\n')) {\n if (line.startsWith('data: ')) {\n yield JSON.parse(line.slice(6));\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/** `readSseEvents` with the `event:` name preserved alongside the JSON payload. */\nexport async function* readSseNamedEvents(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<{ event: string; data: unknown }> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = '';\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let idx;\n while ((idx = buffer.indexOf('\\n\\n')) !== -1) {\n const frame = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 2);\n let event = 'message';\n const dataLines: string[] = [];\n for (const line of frame.split('\\n')) {\n if (line.startsWith('event: ')) event = line.slice(7);\n else if (line.startsWith('data: ')) dataLines.push(line.slice(6));\n }\n if (dataLines.length > 0) {\n yield { event, data: JSON.parse(dataLines.join('\\n')) };\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n\n/** `id:jobId:step:offset` — the run-stream watch cursor wire format. */\nexport function encodeWatchCursor(\n id: string,\n jobId: string,\n step: number | 'runner' | null,\n offset: number,\n): string {\n const stepPart = step === null ? '-' : step === 'runner' ? 'runner' : String(step);\n return `${id}:${jobId}:${stepPart}:${offset}`;\n}\n\n/** The subset of `@benchsdk/cli`'s `resolveAuth` result Actions needs. */\nexport type StoredPlatformAuth = { apiKey?: string; token?: string };\nexport type StoredPlatformAuthResolver = (opts: { baseUrl: string }) => Promise<StoredPlatformAuth>;\n\nconst NO_CREDENTIALS_HINT =\n 'Set COMPUTE_API_KEY, pass --api-key, or run `compute bench auth login`.';\n\n/**\n * Precedence: `--api-key` > `COMPUTE_API_KEY` > `BENCHMARKS_PLATFORM_API_KEY`\n * (legacy) > platform OAuth credentials stored by `compute bench auth login`\n * (`~/.benchsdk/credentials.json`, via `@benchsdk/cli`'s `resolveAuth`, which\n * refreshes an expired access token but never opens a browser). The gateway\n * key written by `compute login` is a different credential and is not used.\n */\nexport async function resolveActionsAuth(\n opts: {\n apiKey?: string;\n baseUrl?: string;\n allowUntrustedHost?: boolean;\n },\n resolveStored: StoredPlatformAuthResolver = resolveStoredPlatformAuth,\n): Promise<ActionsAuth> {\n const baseUrl = (\n opts.baseUrl ||\n process.env.COMPUTE_PLATFORM_URL ||\n process.env.BENCHMARKS_PLATFORM_URL || // legacy name\n DEFAULT_BASE_URL\n ).replace(/\\/+$/, '');\n\n // The bearer key is attached to every request, so an attacker-controlled\n // --base-url would exfiltrate it. Only trusted hosts are allowed silently;\n // anything else must be opted into with --allow-untrusted-host.\n if (!opts.allowUntrustedHost && !isTrustedActionsHost(baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host',\n `Refusing to send the API key to ${baseUrl} — it is not a computesdk.com or localhost host. ` +\n 'If this is a self-hosted/dev deployment you trust, pass --allow-untrusted-host.',\n );\n }\n // Host trust and transport security are separate: --allow-untrusted-host\n // says who may receive the key, never that it may travel in plaintext.\n if (!isSecureActionsTransport(baseUrl)) {\n throw new ActionsCliError(\n 'insecure_transport',\n `Refusing to send the API key over plaintext HTTP to ${baseUrl}. ` +\n 'Use an https:// base URL; http:// is only allowed for localhost/loopback.',\n );\n }\n\n // `||` not `??`: empty-string env vars (common in CI matrices) should fall\n // through to the next source, not count as configured.\n let apiKey =\n opts.apiKey ||\n process.env.COMPUTE_API_KEY ||\n process.env.BENCHMARKS_PLATFORM_API_KEY || // legacy name\n undefined;\n if (!apiKey) {\n // Stored platform OAuth is only ever resolved (and refreshed) for trusted\n // hosts. --allow-untrusted-host opts an explicit key into a host, not the\n // user's saved session.\n if (!isTrustedActionsHost(baseUrl)) {\n throw new ActionsCliError(\n 'untrusted_host_stored_auth',\n `Refusing to use stored platform credentials with untrusted host ${baseUrl}. ` +\n 'Pass --api-key or set COMPUTE_API_KEY to use an explicit key with --allow-untrusted-host.',\n );\n }\n let stored: StoredPlatformAuth;\n try {\n stored = await resolveStored({ baseUrl });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n // `@benchsdk/cli`'s \"nothing stored\" message names `bench` commands and\n // env vars that only apply to that CLI; keep ours for that case and\n // surface the reason only for expired/failed-refresh sessions.\n const detail = reason.startsWith('No credentials found') ? 'No API key.' : reason;\n throw new ActionsCliError('no_credentials', `${detail} ${NO_CREDENTIALS_HINT}`);\n }\n apiKey = stored.apiKey || stored.token || undefined;\n }\n if (!apiKey) {\n throw new ActionsCliError('no_credentials', `No API key. ${NO_CREDENTIALS_HINT}`);\n }\n return { apiKey, baseUrl };\n}\n\nasync function resolveStoredPlatformAuth(opts: { baseUrl: string }): Promise<StoredPlatformAuth> {\n const { resolveAuth } = await import('@benchsdk/cli');\n const auth = await resolveAuth({ baseUrl: opts.baseUrl });\n return { apiKey: auth.apiKey, token: auth.token };\n}\n\nfunction isLoopbackHost(host: string): boolean {\n return host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host === '::1';\n}\n\n/** https://, or http:// to a loopback host only. */\nexport function isSecureActionsTransport(baseUrl: string): boolean {\n let url: URL;\n try {\n url = new URL(baseUrl);\n } catch {\n return false;\n }\n if (url.protocol === 'https:') return true;\n return url.protocol === 'http:' && isLoopbackHost(url.hostname);\n}\n\n/** computesdk.com (and subdomains) or localhost — safe to receive the API key. */\nexport function isTrustedActionsHost(baseUrl: string): boolean {\n let host: string;\n try {\n host = new URL(baseUrl).hostname;\n } catch {\n return false;\n }\n return host === 'computesdk.com' || host.endsWith('.computesdk.com') || isLoopbackHost(host);\n}\n","/**\n * `compute market` — the sell side of the compute market: post listings,\n * reprice/pause/resume/withdraw them, read the book, and read payouts.\n *\n * Auth: identical to `compute actions` — --api-key / COMPUTE_API_KEY / the\n * stored `compute bench auth login` session. The key must belong to an org\n * the platform flags `market_provider`; the seller principal (which\n * executor provider these listings sell) is resolved server-side from the\n * key. Types mirror the wire shapes in benchmarks-platform `lib/market/*`\n * describe functions — keep them in sync by hand; the API is the contract.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { ActionsCliError } from './actions-client.js';\nimport {\n client,\n fail,\n output,\n parseInputs,\n safeTerm,\n secretValueClient,\n usageErrorOutput,\n type CommonOpts,\n} from './actions.js';\n\n// ─── Wire types (mirror benchmarks-platform lib/market describes) ───────────\n\nexport type MarketRatePer = 'second' | 'minute' | 'hour';\nexport type MarketAskStatus = 'live' | 'paused' | 'withdrawn';\n\n/** `describeAsk` — one row of GET /api/v1/market/asks. */\nexport interface MarketAsk {\n id: string;\n provider: string;\n region: string | null;\n size: string;\n 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 /** 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 usd: number;\n per: MarketRatePer;\n takeBps: number;\n maxConcurrent: number;\n expiresAt: string | null;\n rollover: boolean;\n updatedAt: string;\n }[];\n bids: {\n id: string;\n organizationId: string;\n size: string;\n 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 region: string | null;\n usd: number;\n per: MarketRatePer;\n /** 'replaced' = the seller took the capacity back mid-sale. */\n status: 'live' | 'closed' | 'replaced';\n createdAt: string;\n }[];\n prices: { askId: string; usd: number; per: MarketRatePer; changedAt: string }[];\n}\n\n/** One evicted sale — POST /api/v1/market/fills/:id/replace and each entry of the listing replace. */\nexport interface MarketReplacedFill {\n fillId: string;\n askId: string;\n /** Charged to the buyer — the seconds the fill actually lived. */\n settledMicroUsd: number;\n /** An Actions job on the evicted capacity re-places on the buyer's next provider. */\n jobRequeued: boolean;\n}\n\nexport type MarketReplaceFillOutcome =\n | { ok: true; fill: MarketReplacedFill }\n | { ok: false; status: number; error: string };\n\n/** POST /api/v1/market/listings/:id/replace — paused listing + per-fill outcomes. */\nexport interface MarketListingReplaceResult {\n listing: MarketAsk;\n fills: MarketReplaceFillOutcome[];\n}\n\n/** `describeSettlement` — one row of GET /api/v1/market/settlements. */\nexport interface MarketSettlement {\n id: string;\n providerId: string;\n provider?: string;\n periodStart: string;\n periodEnd: string;\n vcpuSeconds: number;\n grossUsd: number;\n netUsd: number;\n grossMicroUsd: number;\n netMicroUsd: number;\n invoiceRef: string | null;\n paidAt: string | null;\n createdAt: string;\n}\n\n// ─── Parsing helpers (pure, exported for tests) ─────────────────────────────\n\nconst USD_RE = /^\\d+(\\.\\d+)?([eE][+-]?\\d+)?$/;\nconst RATE_UNITS: MarketRatePer[] = ['second', 'minute', 'hour'];\n\n/**\n * `--price`/`--per` → the body's `usd`/`per`. Providers quote per-second, so\n * an absent --per is 'second', not an error.\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>.');\n }\n const usd = Number(price);\n if (!USD_RE.test(price) || !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).`,\n );\n }\n const unit = per ?? 'second';\n if (!RATE_UNITS.includes(unit as MarketRatePer)) {\n throw new ActionsCliError(\n 'invalid_argument',\n `--per must be second, minute, or hour, got \"${per}\".`,\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}): 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 ...(opts.region !== undefined && { region: opts.region }),\n usd: rate.usd,\n per: rate.per,\n ...(maxConcurrent !== undefined && { maxConcurrent }),\n ...(expiresInHours !== undefined && { expiresInHours }),\n ...(opts.renew && { rollover: true }),\n };\n}\n\n/**\n * The `POST /api/v1/market/asks` update body for `price`/`pause`/`resume`:\n * `{askId, usd?, per?, maxConcurrent?, status?}` — exactly one of the\n * change fields must be present.\n */\nexport function listingPatchBody(\n listingId: string,\n change: {\n price?: string;\n per?: string;\n capacity?: string;\n status?: 'live' | 'paused';\n },\n): Record<string, unknown> {\n const body: Record<string, unknown> = { askId: listingId };\n if (change.price !== undefined || change.per !== undefined) {\n const rate = parseRate(change.price, change.per);\n body.usd = rate.usd;\n body.per = rate.per;\n }\n const maxConcurrent = parseCapacity(change.capacity);\n if (maxConcurrent !== undefined) body.maxConcurrent = maxConcurrent;\n if (change.status !== undefined) body.status = change.status;\n if (body.usd === undefined && body.maxConcurrent === undefined && body.status === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Nothing to change — pass --price, --capacity, or a status command.',\n );\n }\n return body;\n}\n\n/**\n * The env var `credential connect` reads a field from: the provider and\n * field names upper-snake-cased — tensorlake + apiKey → TENSORLAKE_API_KEY,\n * blaxel + workspace → BLAXEL_WORKSPACE, namespace + token → NAMESPACE_TOKEN.\n * Secrets belong here (or a session env), never in argv where shell history\n * keeps them.\n */\nexport function credentialEnvVar(providerId: string, fieldName: string): string {\n const snake = (s: string) =>\n s\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[^A-Za-z0-9]+/g, '_')\n .toUpperCase();\n return `${snake(providerId)}_${snake(fieldName)}`;\n}\n\nexport interface CredentialResolution {\n /** Every field's value, declared fields only. */\n values: Record<string, string>;\n /** Required fields with no value from either source. */\n missing: MarketCredentialField[];\n /** Field names taken from --field (visible in shell history). */\n fromFlag: string[];\n /** The env var each declared field was looked up under. */\n envNames: Record<string, string>;\n}\n\n/**\n * Resolve each declared credential field: an explicit `--field name=value`\n * wins, then the `<PROVIDER>_<FIELD>` env var. Empty strings count as\n * missing on both.\n */\nexport function credentialValues(\n providerId: string,\n fields: MarketCredentialField[],\n overrides: Record<string, string>,\n env: Record<string, string | undefined> = process.env,\n): CredentialResolution {\n const declared = new Set(fields.map((f) => f.name));\n const unknown = Object.keys(overrides).filter((name) => !declared.has(name));\n if (unknown.length > 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `${providerId} takes no credential field \"${unknown.join('\", \"')}\" — expected one of ${fields\n .map((f) => f.name)\n .join(', ')}.`,\n );\n }\n const values: Record<string, string> = {};\n const fromFlag: string[] = [];\n const missing: MarketCredentialField[] = [];\n const envNames: Record<string, string> = {};\n for (const field of fields) {\n envNames[field.name] = credentialEnvVar(providerId, field.name);\n const fromOverride = overrides[field.name];\n if (fromOverride !== undefined && fromOverride.trim() !== '') {\n values[field.name] = fromOverride.trim();\n fromFlag.push(field.name);\n continue;\n }\n const fromEnv = env[envNames[field.name]];\n if (fromEnv !== undefined && fromEnv.trim() !== '') {\n values[field.name] = fromEnv.trim();\n continue;\n }\n if (field.required !== false) missing.push(field);\n }\n return { values, missing, fromFlag, envNames };\n}\n\n/**\n * The `POST /api/v1/market/provider/credential` body: `{key}` for a\n * single-field executor, `{fields}` for a multi-field one — the same two\n * shapes the org provider-key routes take.\n */\nexport function credentialBody(\n fields: MarketCredentialField[],\n values: Record<string, string>,\n): Record<string, unknown> {\n if (fields.length === 1) {\n return { key: values[fields[0].name] };\n }\n return { fields: values };\n}\n\n// ─── Formatting (pure, exported for tests) ──────────────────────────────────\n\n/** `$0.12`, `$5` — micro-USD-precision dollars without trailing zeros. */\nexport function formatUsd(usd: number): string {\n return `$${usd.toFixed(6).replace(/\\.?0+$/, '')}`;\n}\n\n/** `$0.12/second` — how a listing (or offer, or sale) is priced. */\nexport function formatRate(usd: number, per: string): string {\n return `${formatUsd(usd)}/${per}`;\n}\n\n/** The human status: withdrawn > paused > expired > live. */\nexport function formatListingStatus(ask: Pick<MarketAsk, 'status' | 'live' | 'pendingUsd' | 'pendingPer'>): string {\n let label: string;\n if (ask.status === 'withdrawn') label = pc.gray('withdrawn');\n else if (ask.status === 'paused') label = pc.yellow('paused');\n else if (!ask.live) label = pc.gray('expired');\n else label = pc.green('live');\n if (ask.pendingUsd !== null && ask.pendingPer !== null) {\n label += pc.dim(` → ${formatRate(ask.pendingUsd, ask.pendingPer)} next window`);\n }\n return label;\n}\n\nexport function formatListingRow(ask: MarketAsk): string {\n const expiry = ask.expiresAt\n ? ask.rollover\n ? `renews ${ask.expiresAt}`\n : `expires ${ask.expiresAt}`\n : 'standing';\n return [\n ask.id,\n formatListingStatus(ask),\n 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 `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 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 ` ${formatRate(ask.usd, ask.per)} ${safeTerm(ask.providerName)} ${safeTerm(ask.size)} ${where} up to ${ask.maxConcurrent} at once${expiry}`,\n );\n }\n lines.push('');\n lines.push(pc.bold('buyer offers'));\n if (book.bids.length === 0) lines.push(pc.dim(' no open offers'));\n for (const bid of book.bids) {\n const where = bid.region ? safeTerm(bid.region) : 'anywhere';\n lines.push(\n ` pays up to ${formatRate(bid.maxUsd, bid.per)} ${safeTerm(bid.size)} ${where} ${pc.dim(`posted ${bid.createdAt}`)}`,\n );\n }\n lines.push('');\n lines.push(pc.bold('recent sales'));\n if (book.fills.length === 0) lines.push(pc.dim(' nothing has sold yet'));\n for (const fill of book.fills) {\n const statusNote =\n fill.status === 'replaced'\n ? pc.yellow(' replaced')\n : fill.status === 'closed'\n ? pc.gray(' closed')\n : '';\n lines.push(\n ` ${pc.dim(fill.id)} ${formatRate(fill.usd, fill.per)} ${safeTerm(fill.provider)} ${safeTerm(fill.size)} ${safeTerm(fill.region ?? '-')} ${pc.dim(fill.createdAt)}${statusNote}`,\n );\n }\n return lines.join('\\n');\n}\n\n/** `replaced f-1 settled $0.0003` (+ a note when an Actions job re-places). */\nexport function formatReplacedFill(fill: MarketReplacedFill): string {\n const settled = formatUsd(fill.settledMicroUsd / 1e6);\n const job = fill.jobRequeued\n ? pc.dim(\" — job re-places on the buyer's next provider\")\n : '';\n return `replaced ${pc.cyan(fill.fillId)} settled ${settled}${job}`;\n}\n\n/**\n * `compute market replace` resolves to exactly one endpoint: `--fill` evicts\n * one sale, a listing ID pauses the listing and evicts every sale on it.\n */\nexport function replaceTarget(\n listingId: string | undefined,\n fillId: string | undefined,\n): { path: string; scope: 'listing' | 'fill' } {\n if (fillId !== undefined) {\n return {\n path: `/api/v1/market/fills/${encodeURIComponent(fillId)}/replace`,\n scope: 'fill',\n };\n }\n if (listingId === undefined) {\n throw new ActionsCliError(\n 'invalid_argument',\n 'Nothing to replace — pass a listing ID or --fill <fill-id>.',\n );\n }\n return {\n path: `/api/v1/market/listings/${encodeURIComponent(listingId)}/replace`,\n scope: 'listing',\n };\n}\n\nexport function formatSettlementRow(s: MarketSettlement): string {\n const period = `${s.periodStart.slice(0, 10)} → ${s.periodEnd.slice(0, 10)}`;\n const paid = s.paidAt\n ? pc.green(`paid ${s.paidAt.slice(0, 10)}`)\n : s.invoiceRef\n ? pc.yellow(`invoiced ${safeTerm(s.invoiceRef)}`)\n : pc.dim('unpaid');\n return [\n pc.dim(period),\n `${s.vcpuSeconds.toLocaleString('en-US')} vCPU·s`,\n `gross ${formatUsd(s.grossUsd)}`,\n `net ${formatUsd(s.netUsd)}`,\n paid,\n ].join(' ');\n}\n\n// ─── Commands ───────────────────────────────────────────────────────────────\n\nexport function registerMarketCommands(program: Command): void {\n const market = program\n .command('market')\n .description('Sell compute capacity on the compute market')\n .configureOutput({ outputError: usageErrorOutput });\n\n const common = (cmd: Command) =>\n cmd\n .option('--api-key <key>', 'API key (default: $COMPUTE_API_KEY)')\n .option('--base-url <url>', 'API base URL (default: https://platform.computesdk.com)')\n .option('--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>', 'price per unit of time (e.g. 0.12)')\n .option('--per <unit>', 'time unit the price is per: second, minute, or hour (default: second)')\n .option('--size <tier>', 'size tier to sell (default: medium, else the provider\\'s first tier)')\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 }) => {\n try {\n const c = await client(opts);\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 }),\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>', 'new price per unit of time (e.g. 0.08)')\n .option('--per <unit>', 'time unit the price is per: second, minute, or hour (default: second)'),\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 ).action(async (opts: CommonOpts) => {\n try {\n const book = await (await client(opts)).get<MarketOrderBook>(\n '/api/v1/market/book',\n );\n output(opts, book, (b) => console.log(formatBook(b)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('settlements')\n .description('Your monthly payout reports'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { settlements } = await (await client(opts)).get<{\n settlements: MarketSettlement[];\n }>('/api/v1/market/settlements');\n output(opts, settlements, (rows) => {\n if (rows.length === 0) {\n console.log('No settlements yet.');\n return;\n }\n for (const s of rows) console.log(formatSettlementRow(s));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n market\n .command('status')\n .description('Who you are on the market: seller identity, credential, sizes, regions'),\n ).action(async (opts: CommonOpts) => {\n try {\n const { provider } = await (await client(opts)).get<{\n provider: MarketProvider;\n }>('/api/v1/market/provider');\n output(opts, provider, (p) => console.log(formatProviderStatus(p)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n const credential = market\n .command('credential')\n .description('Connect the credential your listings fill under');\n\n common(\n credential\n .command('connect')\n .description(\n 'Save the executor credential your sold capacity runs under. Each field is read from\\n' +\n 'a <PROVIDER>_<FIELD> env var (e.g. TENSORLAKE_API_KEY) — never pass secrets in argv;\\n' +\n '--field name=value overrides a field (visible in shell history)',\n )\n .option('--field <pairs...>', 'credential fields as name=value (prefer env vars for secrets)'),\n ).action(async (opts: CommonOpts & { field?: string[] }) => {\n try {\n const c = await secretValueClient(opts, 'credential values');\n const { provider } = await c.get<{ provider: MarketProvider }>(\n '/api/v1/market/provider',\n );\n if (provider.credentialFields.length === 0) {\n throw new ActionsCliError(\n 'invalid_argument',\n `${provider.provider} authenticates with the deployment's own identity — there is no credential to connect.`,\n );\n }\n const resolved = credentialValues(\n provider.provider,\n provider.credentialFields,\n parseInputs(opts.field),\n );\n if (resolved.missing.length > 0) {\n const hints = resolved.missing\n .map((f) => ` export ${resolved.envNames[f.name]}=… # ${f.label}`)\n .join('\\n');\n throw new ActionsCliError(\n 'invalid_argument',\n `Missing credential field${resolved.missing.length === 1 ? '' : 's'}. Set:\\n${hints}`,\n );\n }\n if (resolved.fromFlag.some((name) => provider.credentialFields.find((f) => f.name === name)?.secret)) {\n console.error(\n pc.yellow('note: a secret passed via --field stays in your shell history — prefer the env vars.'),\n );\n }\n const result = await c.post<{ provider: MarketProvider }>(\n '/api/v1/market/provider/credential',\n credentialBody(provider.credentialFields, resolved.values),\n );\n output(opts, result, (r) => {\n console.log(`connected ${pc.cyan(safeTerm(r.provider.name))} credential saved`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n common(\n credential\n .command('disconnect')\n .description('Remove the stored credential — listings stop filling until a new one connects'),\n ).action(async (opts: CommonOpts) => {\n try {\n const result = await (await client(opts)).del<{ provider: MarketProvider }>(\n '/api/v1/market/provider/credential',\n );\n output(opts, result, (r) => {\n console.log(`disconnected ${pc.cyan(safeTerm(r.provider.name))} credential removed`);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n","/**\n * `compute sandboxes` — drive sandboxes placed through the platform's\n * `/api/v1/sandboxes` API: create/list/get/destroy, exec commands, spawn and\n * control detached processes, read/write the filesystem, and resolve port\n * URLs.\n *\n * Auth: identical to `compute actions`/`compute market` — --api-key /\n * COMPUTE_API_KEY / the stored `compute bench auth login` session. Types\n * mirror the wire shapes in benchmarks-platform `lib/sandboxes/*` — keep\n * them in sync by hand; the API is the contract.\n */\n\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport type { ActionsClient } from './actions-client.js';\nimport {\n client,\n fail,\n output,\n parseInputs,\n safeTerm,\n usageErrorOutput,\n type CommonOpts,\n} from './actions.js';\n\n// ─── Wire types (mirror benchmarks-platform lib/sandboxes) ──────────────────\n\nexport interface SandboxCost {\n rate: { usd: number; unit: string } | null;\n runtimeSeconds: number;\n costUsd: number | null;\n settled: boolean;\n}\n\n/** `toSummary` — one row of GET /api/v1/sandboxes. */\nexport interface SandboxSummary {\n id: string;\n label: string | null;\n provider: string | null;\n providerSandboxId: string | null;\n status: 'creating' | 'running' | 'destroyed' | string;\n placementAttempts: unknown[];\n commandCount: number;\n secrets: string[];\n /** The `boot.image` asked for, and what the provider actually booted. */\n requestedImage: string | null;\n image: string | null;\n createdAt: string;\n lastCommandAt: string | null;\n destroyedAt: string | null;\n destroyError: string | null;\n cost: SandboxCost;\n}\n\n/** `toDetail` — POST /sandboxes and GET /sandboxes/{id}. */\nexport interface SandboxDetail extends SandboxSummary {\n /** BYOK direct-attach descriptor — null on market fills and ambient providers. */\n attach: { provider: string; providerSandboxId: string; region: string | null } | null;\n}\n\nexport interface SandboxProcess {\n id: string;\n jobId: string;\n pid: number | null;\n command: string;\n cwd: string | null;\n envNames: string[];\n /** Whether the job's stdin pipe is open (spawn `--stdin`). */\n stdin: boolean;\n status: string;\n exitCode: number | null;\n signal: string | null;\n startedAt: string;\n exitedAt: string | null;\n}\n\nexport interface SandboxProcessStatus extends SandboxProcess {\n stdout: string;\n stderr: string;\n}\n\nexport interface CommandResult {\n commandId: string;\n exitCode: number;\n durationMs: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface FileEntry {\n name: string;\n type: 'file' | 'directory';\n size?: number;\n modified?: string;\n}\n\nexport type PathView =\n | { path: string; type: 'file'; content: string }\n | { path: string; type: 'directory'; entries: FileEntry[] };\n\n/** `snapshotView` — one row of GET /sandboxes/{id}/snapshots. */\nexport interface SandboxSnapshot {\n id: string;\n sandboxId: string;\n provider: string;\n region: string | null;\n providerSnapshotId: string;\n label: string | null;\n expiresAt: string | null;\n createdAt: string;\n deletedAt: string | null;\n}\n\n/** POSIX single-quote: argv survives intact through the remote `sh -lc`. */\nfunction shellQuote(arg: string): string {\n return `'${arg.replace(/'/g, `'\\\\''`)}'`;\n}\n\n// ─── Rendering ───────────────────────────────────────────────────────────────\n\nfunction printSandbox(s: SandboxSummary): void {\n const attach = 'attach' in s ? (s as SandboxDetail).attach : undefined;\n console.log(`${pc.cyan(s.id)} ${s.status} ${s.provider ?? '—'} ${s.providerSandboxId ?? '—'}`);\n console.log(` label: ${s.label ?? '—'} commands: ${s.commandCount} created: ${s.createdAt}`);\n if (s.image !== undefined) {\n console.log(` image: ${s.image ?? '—'}${s.requestedImage !== null && s.requestedImage !== s.image ? ` ${pc.dim(`(requested: ${s.requestedImage})`)}` : ''}`);\n }\n if (s.destroyError) console.log(` destroyError: ${pc.red(s.destroyError)}`);\n if (attach !== undefined) {\n console.log(\n attach === null\n ? ' attach: none (market fill or ambient provider — platform drive only)'\n : ` attach: ${attach.provider} / ${attach.providerSandboxId}${attach.region ? ` (${attach.region})` : ''}`,\n );\n }\n}\n\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\nexport function registerSandboxesCommands(program: Command): void {\n const cmd = program\n .command('sandboxes')\n .alias('sbx')\n .description('Create and drive sandboxes through the platform')\n .configureOutput({ outputError: usageErrorOutput });\n\n cmd\n .command('create')\n .description('Place a sandbox (provider order walks 1,2,3; \"market\" bids first)')\n .option('--order <providers>', 'provider order, comma-separated (e.g. \"market,blaxel,vercel\")')\n .option('--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')\n .option('--memory-mb <n>', 'memory in MB')\n .option('--disk-mb <n>', 'ephemeral disk in MB')\n .option('--timeout-ms <ms>', 'sandbox timeout in ms')\n .option('--secret <name>', 'vault secret name to inject (repeatable)', (v, a: string[]) => a.concat(v), [] as string[])\n .option('--api-key <key>', 'platform API key (or COMPUTE_API_KEY)')\n .option('--base-url <url>', 'platform base URL')\n .option('--allow-untrusted-host', 'allow non-computesdk.com base URLs')\n .option('--json', 'print the raw response')\n .action(async (opts: CommonOpts & {\n order?: string; label?: string; image?: string; snapshotId?: string;\n cpus?: string; memoryMb?: string; diskMb?: string; timeoutMs?: string;\n secret?: string[];\n }) => {\n try {\n const c = await client(opts);\n const resources: Record<string, number> = {};\n if (opts.cpus) resources.cpus = Number(opts.cpus);\n if (opts.memoryMb) resources.memoryMb = Number(opts.memoryMb);\n if (opts.diskMb) resources.ephemeralDiskMb = Number(opts.diskMb);\n const body: Record<string, unknown> = {};\n if (opts.order) body.providerOrder = opts.order.split(',').map((s) => s.trim());\n if (opts.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 res = await c.post<{ sandbox: SandboxDetail }>('/api/v1/sandboxes', body);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('list')\n .description('List sandboxes')\n .option('--status <status>', 'creating | running | destroyed')\n .option('--limit <n>', 'page size')\n .option('--cursor <cursor>', 'page cursor from a previous response')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (opts: CommonOpts & { status?: string; limit?: string; cursor?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ sandboxes: SandboxSummary[]; nextCursor: string | null }>(\n '/api/v1/sandboxes',\n { status: opts.status, limit: opts.limit, cursor: opts.cursor },\n );\n output(opts, res, (page) => {\n page.sandboxes.forEach(printSandbox);\n if (page.nextCursor) console.log(pc.dim(`nextCursor: ${page.nextCursor}`));\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('get <sandboxId>')\n .description('Show one sandbox (includes the BYOK attach descriptor)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ sandbox: SandboxDetail }>(`/api/v1/sandboxes/${sandboxId}`);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('destroy <sandboxId>')\n .description('Destroy a sandbox (verified teardown + cost settle)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.del<{ sandbox: SandboxSummary }>(`/api/v1/sandboxes/${sandboxId}`);\n output(opts, res.sandbox, printSandbox);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('exec <sandboxId> <command...>')\n .description('Run a one-shot command and print its result')\n .option('--timeout-ms <ms>', 'command timeout in ms')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, command: string[], opts: CommonOpts & { timeoutMs?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ commandId: string } & CommandResult>(\n `/api/v1/sandboxes/${sandboxId}/commands`,\n {\n command: command.map(shellQuote).join(' '),\n ...(opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {}),\n },\n );\n output(opts, res, (r) => {\n process.stdout.write(r.stdout);\n if (r.stderr) process.stderr.write(r.stderr);\n if (!r.stdout) console.log(`exit ${r.exitCode} (${r.durationMs}ms)`);\n });\n // exitCode, not exit(): a piped stdout flushes before the CLI exits.\n if (res.exitCode !== 0) process.exitCode = res.exitCode;\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('spawn <sandboxId> <command...>')\n .description('Start a detached process that outlives this request')\n .option('--cwd <dir>', 'working directory')\n .option('-e, --env <key=value>', 'environment variable (repeatable)', (v, a: string[]) => a.concat(v), [] as string[])\n .option('--stdin', 'keep the process\\'s stdin pipe open for `stdin`/`close-stdin`')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, command: string[], opts: CommonOpts & { cwd?: string; env?: string[]; stdin?: boolean }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcess }>(\n `/api/v1/sandboxes/${sandboxId}/processes`,\n {\n command: command.map(shellQuote).join(' '),\n ...(opts.cwd ? { cwd: opts.cwd } : {}),\n ...(opts.env && opts.env.length > 0 ? { env: parseInputs(opts.env) } : {}),\n ...(opts.stdin ? { stdin: true } : {}),\n },\n );\n output(opts, res.process, printProcess);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('ps <sandboxId>')\n .description('List the sandbox\\'s tracked processes')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ processes: SandboxProcess[] }>(\n `/api/v1/sandboxes/${sandboxId}/processes`,\n );\n output(opts, res.processes, (list) => list.forEach(printProcess));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('logs <sandboxId> <jobId>')\n .description('Show a process\\'s buffered output (--follow streams until exit)')\n .option('-f, --follow', 'stream output until the process exits')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { follow?: boolean }) => {\n try {\n const c = await client(opts);\n if (opts.follow) {\n await followProcess(c, sandboxId, jobId);\n return;\n }\n const res = await c.get<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}`,\n );\n output(opts, res.process, (p) => {\n if (p.stdout) process.stdout.write(p.stdout);\n if (p.stderr) process.stderr.write(p.stderr);\n if (!p.stdout && !p.stderr) printProcess(p);\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('wait <sandboxId> <jobId>')\n .description('Block until a process exits')\n .option('--timeout-ms <ms>', 'bound the wait (job keeps running on timeout)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { timeoutMs?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/wait`,\n opts.timeoutMs ? { timeoutMs: Number(opts.timeoutMs) } : {},\n );\n output(opts, res.process, printProcess);\n if (res.process.status === 'exited') {\n // A null exit code (signal-terminated) is still a failure, not 0.\n process.exitCode = res.process.exitCode ?? 128;\n }\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('kill <sandboxId> <jobId>')\n .description('Signal a process (default SIGTERM)')\n .option('--signal <signal>', 'signal name or number, e.g. SIGKILL or 9')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { signal?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ process: SandboxProcessStatus }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/kill`,\n opts.signal ? { signal: opts.signal } : {},\n );\n output(opts, res.process, printProcess);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('stdin <sandboxId> <jobId>')\n .description('Write to a process\\'s stdin pipe (spawn with --stdin; --data, --file, or piped)')\n .option('--data <text>', 'data to write')\n .option('--file <local>', 'read data from a local file')\n .option('--base64', 'base64-encode the input before sending (binary-safe)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts & { data?: string; file?: string; base64?: boolean }) => {\n try {\n let data = opts.data;\n if (data === undefined && opts.file) {\n const { readFile } = await import('node:fs/promises');\n data = opts.base64\n ? (await readFile(opts.file)).toString('base64')\n : await readFile(opts.file, 'utf8');\n }\n if (data === undefined && !process.stdin.isTTY) {\n // Buffer raw bytes — decoding as utf8 first would corrupt binary\n // input before --base64 could encode it.\n const piped = await new Promise<Buffer>((resolve) => {\n const chunks: Buffer[] = [];\n process.stdin.on('data', (chunk) => chunks.push(chunk));\n process.stdin.on('end', () => resolve(Buffer.concat(chunks)));\n });\n data = opts.base64 ? piped.toString('base64') : piped.toString('utf8');\n }\n if (data === undefined || data === '') {\n console.error(pc.red('Pass --data, --file, or pipe stdin'));\n process.exit(1);\n }\n if (opts.base64 && opts.data !== undefined) {\n data = Buffer.from(data).toString('base64');\n }\n const c = await client(opts);\n const res = await c.post<{ ok: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/stdin`,\n { data, ...(opts.base64 ? { encoding: 'base64' } : {}) },\n );\n output(opts, res, () => console.log(`wrote ${data.length} chars to ${jobId}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('close-stdin <sandboxId> <jobId>')\n .description('Close a process\\'s stdin pipe')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, jobId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ ok: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/processes/${jobId}/close-stdin`,\n {},\n );\n output(opts, res, () => console.log(`closed stdin on ${jobId}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('ls <sandboxId> [path]')\n .description('List a directory (or stat a path) inside the sandbox')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string | undefined, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${sandboxId}/files`, {\n path: path ?? '/',\n });\n output(opts, res, (view) => {\n if (view.type === 'directory') {\n for (const e of view.entries) {\n console.log(`${e.type === 'directory' ? pc.blue('d') : ' '} ${e.name}${e.size !== undefined ? ` ${pc.dim(String(e.size))}` : ''}`);\n }\n } else {\n console.log(`${view.path} file ${view.content.length} chars`);\n }\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('cat <sandboxId> <path>')\n .description('Print a file\\'s contents')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<PathView>(`/api/v1/sandboxes/${sandboxId}/files`, { path });\n output(opts, res, (view) => {\n if (view.type !== 'file') {\n console.error(pc.red(`${view.path} is a directory`));\n process.exit(1);\n }\n process.stdout.write(view.content);\n if (!view.content.endsWith('\\n')) process.stdout.write('\\n');\n });\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('write <sandboxId> <path>')\n .description('Write a file inside the sandbox (--content or --file <local>, else stdin)')\n .option('--content <text>', 'file contents')\n .option('--file <local>', 'read contents from a local file')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts & { content?: string; file?: string }) => {\n try {\n let content = opts.content;\n if (content === undefined && opts.file) {\n const { readFile } = await import('node:fs/promises');\n content = await readFile(opts.file, 'utf8');\n }\n if (content === undefined && !process.stdin.isTTY) {\n content = await new Promise<string>((resolve) => {\n let data = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk) => (data += chunk));\n process.stdin.on('end', () => resolve(data));\n });\n }\n if (content === undefined) {\n console.error(pc.red('Pass --content, --file, or pipe stdin'));\n process.exit(1);\n }\n const c = await client(opts);\n const res = await c.post<{ path: string; type: string }>(\n `/api/v1/sandboxes/${sandboxId}/files`,\n { path, content },\n );\n output(opts, res, (r) => console.log(`wrote ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('mkdir <sandboxId> <path>')\n .description('Create a directory (parents included)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ path: string }>(`/api/v1/sandboxes/${sandboxId}/files`, {\n path,\n mkdir: true,\n });\n output(opts, res, (r) => console.log(`created ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('rm <sandboxId> <path>')\n .description('Remove a file or directory inside the sandbox')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, path: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.del<{ path: string; removed: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/files?path=${encodeURIComponent(path)}`,\n );\n output(opts, res, (r) => console.log(`removed ${r.path}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('url <sandboxId>')\n .description('Resolve the provider\\'s public URL for a port')\n .requiredOption('--port <n>', 'port the service listens on')\n .option('--protocol <protocol>', 'protocol (default provider-chosen)')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts & { port: string; protocol?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ url: string }>(`/api/v1/sandboxes/${sandboxId}/urls`, {\n port: opts.port,\n protocol: opts.protocol,\n });\n output(opts, res, (r) => console.log(safeTerm(r.url)));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('snapshots <sandboxId>')\n .description('List the sandbox\\'s snapshots')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.get<{ snapshots: SandboxSnapshot[] }>(\n `/api/v1/sandboxes/${sandboxId}/snapshots`,\n );\n output(opts, res.snapshots, (list) => list.forEach(printSnapshot));\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('snapshot <sandboxId>')\n .description('Snapshot a running sandbox through its provider')\n .option('--label <label>', 'label for the snapshot')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, opts: CommonOpts & { label?: string }) => {\n try {\n const c = await client(opts);\n const res = await c.post<{ snapshot: SandboxSnapshot }>(\n `/api/v1/sandboxes/${sandboxId}/snapshots`,\n opts.label ? { label: opts.label } : {},\n );\n output(opts, res.snapshot, printSnapshot);\n } catch (e) {\n fail(e, opts);\n }\n });\n\n cmd\n .command('snapshot-delete <sandboxId> <snapshotId>')\n .description('Delete a snapshot\\'s provider artifact')\n .option('--api-key <key>').option('--base-url <url>').option('--allow-untrusted-host')\n .option('--json', 'print the raw response')\n .action(async (sandboxId: string, snapshotId: string, opts: CommonOpts) => {\n try {\n const c = await client(opts);\n const res = await c.del<{ ok: boolean }>(\n `/api/v1/sandboxes/${sandboxId}/snapshots/${snapshotId}`,\n );\n output(opts, res, () => console.log(`deleted snapshot ${snapshotId}`));\n } catch (e) {\n fail(e, opts);\n }\n });\n}\n\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 * Browser-based CLI authentication flow\n *\n * Precedence: env var > stored credentials > browser auth flow\n */\n\nimport * as http from 'node:http';\nimport * as crypto from 'node:crypto';\nimport { exec } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as os from 'os';\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\n\nfunction getCredentialsDir(): string {\n return path.join(os.homedir(), '.computesdk');\n}\n\nfunction getCredentialsFile(): string {\n return path.join(getCredentialsDir(), 'credentials.json');\n}\n\nconst AUTH_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes\nconst CONSOLE_AUTH_URL = 'https://console.computesdk.com/cli/auth';\n\nconst SUCCESS_HTML = `<!DOCTYPE html>\n<html>\n<head><title>ComputeSDK CLI</title></head>\n<body style=\"font-family: system-ui, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0;\">\n <div style=\"text-align: center;\">\n <h1>Authenticated</h1>\n <p>You can close this tab and return to the terminal.</p>\n </div>\n</body>\n</html>`;\n\n/**\n * Load stored credentials from ~/.computesdk/credentials.json.\n * Returns the API key if found and valid, or null.\n */\nexport function loadStoredCredentials(): string | null {\n try {\n if (!fs.existsSync(getCredentialsFile())) {\n return null;\n }\n const raw = fs.readFileSync(getCredentialsFile(), 'utf-8');\n const data = JSON.parse(raw);\n if (typeof data.apiKey === 'string' && data.apiKey.length > 0) {\n return data.apiKey;\n }\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * Store credentials to ~/.computesdk/credentials.json.\n * Creates ~/.computesdk/ directory if it doesn't exist.\n */\nexport function storeCredentials(apiKey: string): void {\n if (!fs.existsSync(getCredentialsDir())) {\n fs.mkdirSync(getCredentialsDir(), { recursive: true, mode: 0o700 });\n }\n fs.writeFileSync(\n getCredentialsFile(),\n JSON.stringify({ apiKey }, null, 2) + '\\n',\n { mode: 0o600 }\n );\n}\n\n/**\n * Delete stored credentials file.\n */\nexport function clearStoredCredentials(): void {\n try {\n if (fs.existsSync(getCredentialsFile())) {\n fs.unlinkSync(getCredentialsFile());\n }\n } catch {\n // Ignore - file may not exist or may not be writable\n }\n}\n\n/**\n * Open a URL in the user's default browser.\n * Falls back to printing the URL if the browser fails to open.\n */\nfunction openBrowser(url: string): void {\n const command =\n process.platform === 'darwin'\n ? `open \"${url}\"`\n : process.platform === 'win32'\n ? `start \"\" \"${url}\"`\n : `xdg-open \"${url}\"`;\n\n exec(command, (err) => {\n if (err) {\n p.log.warn('Could not open browser automatically.');\n p.log.info(`Open this URL manually:\\n ${pc.cyan(url)}`);\n }\n });\n}\n\nexport interface AuthFlowOptions {\n /** Override timeout for tests */\n timeoutMs?: number;\n /** Callback when server is listening (for tests) */\n onServerReady?: (port: number, state: string) => void;\n /** Skip opening browser (for tests) */\n skipBrowserOpen?: boolean;\n}\n\n/**\n * Run the browser-based authentication flow.\n *\n * 1. Start a local HTTP server on a random port\n * 2. Open browser to console.computesdk.com/cli/auth\n * 3. Wait for callback with token and validated state\n * 4. Return the API key\n */\nexport function runBrowserAuthFlow(options?: AuthFlowOptions): Promise<string> {\n const timeoutMs = options?.timeoutMs ?? AUTH_TIMEOUT_MS;\n const state = crypto.randomBytes(32).toString('hex');\n\n return new Promise<string>((resolve, reject) => {\n const server = http.createServer();\n\n const timeout = setTimeout(() => {\n server.close();\n reject(\n new Error('Authentication timed out after 5 minutes. Please try again.')\n );\n }, timeoutMs);\n\n server.on('request', (req, res) => {\n const url = new URL(req.url || '/', 'http://localhost');\n\n if (req.method !== 'GET' || url.pathname !== '/callback') {\n res.writeHead(404, { 'Content-Type': 'text/plain' });\n res.end('Not Found');\n return;\n }\n\n const receivedState = url.searchParams.get('state');\n const token = url.searchParams.get('token');\n\n if (receivedState !== state) {\n res.writeHead(403, { 'Content-Type': 'text/plain' });\n res.end('Error: State mismatch. Please try authenticating again.');\n return;\n }\n\n if (!token) {\n res.writeHead(400, { 'Content-Type': 'text/plain' });\n res.end('Error: No token received.');\n return;\n }\n\n res.writeHead(200, { 'Content-Type': 'text/html' });\n res.end(SUCCESS_HTML);\n\n clearTimeout(timeout);\n server.close();\n resolve(token);\n });\n\n server.listen(0, '127.0.0.1', () => {\n const addr = server.address();\n if (!addr || typeof addr === 'string') {\n clearTimeout(timeout);\n server.close();\n reject(new Error('Failed to start auth server'));\n return;\n }\n\n const port = addr.port;\n const authUrl = `${CONSOLE_AUTH_URL}?port=${port}&state=${state}`;\n\n if (options?.onServerReady) {\n options.onServerReady(port, state);\n }\n\n if (!options?.skipBrowserOpen) {\n openBrowser(authUrl);\n }\n });\n\n server.on('error', (err) => {\n clearTimeout(timeout);\n reject(new Error(`Auth server error: ${err.message}`));\n });\n });\n}\n\n/**\n * Resolve an API key through the precedence chain:\n * env var > stored credentials > browser auth flow\n */\nexport async function resolveApiKey(options?: {\n forceLogin?: boolean;\n}): Promise<string> {\n // 1. Check environment variable (highest precedence)\n if (process.env.COMPUTESDK_API_KEY) {\n return process.env.COMPUTESDK_API_KEY;\n }\n\n // 2. Check stored credentials (skip if forcing re-auth)\n if (!options?.forceLogin) {\n const stored = loadStoredCredentials();\n if (stored) {\n p.log.info(\n `Using stored credentials from ${pc.dim('~/.computesdk/credentials.json')}`\n );\n return stored;\n }\n }\n\n // 3. Run browser auth flow\n p.log.info('No API key found. Starting browser authentication...');\n\n const spinner = p.spinner();\n spinner.start('Waiting for browser authentication...');\n\n try {\n const apiKey = await runBrowserAuthFlow();\n spinner.stop('Authentication successful');\n\n // Store for next time\n try {\n storeCredentials(apiKey);\n p.log.success(\n `Credentials saved to ${pc.dim('~/.computesdk/credentials.json')}`\n );\n } catch {\n p.log.warn('Could not save credentials to disk. You may need to authenticate again next time.');\n }\n\n return apiKey;\n } catch (error) {\n spinner.stop(pc.red('Authentication failed'));\n throw error;\n }\n}\n","/**\n * Shared setup logic for CLI commands\n *\n * Resolves authentication and configures the compute client\n * for a given provider. Used by both subcommands and the REPL.\n */\n\nimport * as p from '@clack/prompts';\nimport pc from 'picocolors';\nimport { compute } from 'computesdk';\nimport { detectAvailableProviders, getProviderStatus, buildProviderConfig, type ProviderStatus } from './providers.js';\nimport { resolveApiKey } from './auth.js';\n\n/**\n * Authenticate and set COMPUTESDK_API_KEY in the environment.\n * Exits the process on failure.\n */\nexport async function ensureAuth(options?: { forceLogin?: boolean }): Promise<void> {\n try {\n const apiKey = await resolveApiKey({ forceLogin: options?.forceLogin });\n process.env.COMPUTESDK_API_KEY = apiKey;\n } catch (error) {\n p.log.error((error as Error).message);\n p.log.info(`Get your API key at ${pc.cyan('https://console.computesdk.com')}`);\n p.outro(pc.red('Setup incomplete'));\n process.exit(1);\n }\n}\n\n/**\n * Resolve which provider to use.\n *\n * If `--provider` is given, validates it's configured and returns it.\n * If `interactive` is true and multiple providers are available, prompts user.\n * In non-interactive mode, requires `--provider` when multiple are configured.\n * Exits the process if no providers are available.\n */\nexport async function resolveProvider(\n providerFlag?: string,\n options?: { interactive?: boolean },\n): Promise<string> {\n const interactive = options?.interactive ?? false;\n const available = detectAvailableProviders();\n const providerStatus = getProviderStatus();\n\n if (providerFlag) {\n const match = providerStatus.find(\n (s: ProviderStatus) => s.name.toLowerCase() === providerFlag.toLowerCase(),\n );\n\n if (!match) {\n p.log.error(`Unknown provider: ${providerFlag}`);\n p.log.info(`Available providers: ${providerStatus.map((s: ProviderStatus) => s.name).join(', ')}`);\n process.exit(1);\n }\n\n if (!match.ready) {\n p.log.error(`Provider ${providerFlag} is not configured`);\n if (match.missing.length > 0) {\n p.log.info(`Missing env vars: ${match.missing.join(', ')}`);\n }\n process.exit(1);\n }\n\n return match.name;\n }\n\n if (available.length === 0) {\n p.log.error('No provider credentials detected');\n p.log.info('Set one of: E2B_API_KEY, MODAL_TOKEN_ID, RAILWAY_API_KEY, etc.');\n p.outro(pc.red('Setup incomplete'));\n process.exit(1);\n }\n\n // Single provider — no ambiguity\n if (available.length === 1) {\n return available[0];\n }\n\n // Multiple providers — interactive mode can prompt, non-interactive must fail\n if (!interactive) {\n p.log.error('Multiple providers configured. Use --provider to specify one.');\n p.log.info(`Available: ${available.join(', ')}`);\n process.exit(1);\n }\n\n const providerOptions = providerStatus\n .filter((status: ProviderStatus) => status.ready)\n .map((status: ProviderStatus) => ({\n value: status.name,\n label: status.name,\n }));\n\n const provider = await p.select({\n message: 'Select provider',\n options: providerOptions,\n });\n\n if (p.isCancel(provider)) {\n p.cancel('Cancelled');\n process.exit(0);\n }\n\n return provider as string;\n}\n\n/**\n * Configure the compute client for a provider.\n * Must be called after ensureAuth().\n */\nexport function configureCompute(provider: string): void {\n const config = buildProviderConfig(provider);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n compute.setConfig(config as any);\n}\n"],"mappings":";;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACOA,YAAY,cAAc;AAC1B,YAAYA,WAAU;AACtB,YAAY,QAAQ;AACpB,YAAY,QAAQ;AACpB,OAAOC,SAAQ;AACf,SAAS,eAAsC;AAY/C,eAAsB,UAAU,SAA2B,UAAiC;AAE1F,OAAK;AACL,QAAM,MAAmB;AAAA,IACvB,WAAW,oBAAI,IAAI,CAAC,CAAC,QAAQ,WAAW,OAAO,CAAC,CAAC;AAAA,IACjD,iBAAiB,QAAQ;AAAA,EAC3B;AAEA,QAAM,WAAW,GAAG;AACtB;AAEA,SAAS,YAAY,WAA2B;AAC9C,MAAI,CAAC,UAAW,QAAOA,IAAG,KAAK,eAAe,IAAIA,IAAG,KAAK,IAAI;AAC9D,SAAOA,IAAG,KAAK,IAAI,SAAS,IAAI,IAAIA,IAAG,KAAK,IAAI;AAClD;AAQA,SAAS,WAAW,KAA0C;AAC5D,QAAM,KAAc,yBAAgB;AAAA,IAClC,OAAO,QAAQ;AAAA,IACf,QAAQ,QAAQ;AAAA,IAChB,QAAQ,YAAY,IAAI,eAAe;AAAA,IACvC,UAAU;AAAA,IACV,aAAa;AAAA,EACf,CAAC;AAGD,cAAY,EAAE;AAEd,SAAO,IAAI,QAAuB,CAAC,YAAY;AAC7C,QAAI,WAAW;AACf,UAAM,OAAO,CAAC,WAA0B;AACtC,UAAI,SAAU;AACd,iBAAW;AACX,SAAG,MAAM;AACT,cAAQ,MAAM;AAAA,IAChB;AAEA,OAAG,GAAG,UAAU,MAAM;AACpB,cAAQ,IAAI;AACZ,SAAG,OAAO;AAAA,IACZ,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AM,OAAO,kBAAkB;AACzD,UAAM,SAAS,QAAQ,KAAK,MAAM,CAAC,CAAC;AACpC;AAAA,EACF;AACA,QAAM,QAAQ,WAAW,QAAQ,IAAI;AACvC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAMN,IAAG,IAAI;AAAA,SAAY,MAAM,OAAO,EAAE,CAAC;AACjD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["path","pc","compute","fs","path","os","p","pc","sandbox","spinner","output","p","pc","readFileSync","fileURLToPath","dirname","join","compute","path","client","p","path","program","text","pc","pc","p","program","pc","pc","p","program","path","fs","path","os","pc","spinner","p","pc","compute","pc","compute","__filename","fileURLToPath","__dirname","dirname","readFileSync","join","pc","spinner","compute","saveSandbox","loadState","saveState","shellEscape"]}
|